1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71 const X86Subtarget &STI)
72 : TargetLowering(TM), Subtarget(&STI) {
73 X86ScalarSSEf64 = Subtarget->hasSSE2();
74 X86ScalarSSEf32 = Subtarget->hasSSE1();
75 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77 // Set up the TargetLowering object.
78 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
81 setBooleanContents(ZeroOrOneBooleanContent);
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85 // For 64-bit, since we have so many registers, use the ILP scheduler.
86 // For 32-bit, use the register pressure specific scheduling.
87 // For Atom, always use ILP scheduling.
88 if (Subtarget->isAtom())
89 setSchedulingPreference(Sched::ILP);
90 else if (Subtarget->is64Bit())
91 setSchedulingPreference(Sched::ILP);
93 setSchedulingPreference(Sched::RegPressure);
94 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97 // Bypass expensive divides on Atom when compiling with O2.
98 if (TM.getOptLevel() >= CodeGenOpt::Default) {
99 if (Subtarget->hasSlowDivide32())
100 addBypassSlowDiv(32, 8);
101 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102 addBypassSlowDiv(64, 16);
105 if (Subtarget->isTargetKnownWindowsMSVC()) {
106 // Setup Windows compiler runtime calls.
107 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109 setLibcallName(RTLIB::SREM_I64, "_allrem");
110 setLibcallName(RTLIB::UREM_I64, "_aullrem");
111 setLibcallName(RTLIB::MUL_I64, "_allmul");
112 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168 // f32/f64 are legal, f80 is custom.
169 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 } else if (!Subtarget->useSoftFloat()) {
174 // We have an algorithm for SSE2->double, and we turn this into a
175 // 64-bit FILD followed by conditional FADD for other targets.
176 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
177 // We have an algorithm for SSE2, and we turn this into a 64-bit
178 // FILD or VCVTUSI2SS/SD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
182 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
187 if (!Subtarget->useSoftFloat()) {
188 // SSE has no i16 to fp conversion, only i32
189 if (X86ScalarSSEf32) {
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
191 // f32 and f64 cases are Legal, f80 case is not
192 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
202 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
203 // are Legal, f80 is custom lowered.
204 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
205 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
207 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
209 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
210 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
212 if (X86ScalarSSEf32) {
213 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
214 // f32 and f64 cases are Legal, f80 case is not
215 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
217 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
218 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
221 // Handle FP_TO_UINT by promoting the destination to a larger signed
223 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
224 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
225 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
227 if (Subtarget->is64Bit()) {
228 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
229 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
230 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
233 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
234 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
236 } else if (!Subtarget->useSoftFloat()) {
237 // Since AVX is a superset of SSE3, only check for SSE here.
238 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
239 // Expand FP_TO_UINT into a select.
240 // FIXME: We would like to use a Custom expander here eventually to do
241 // the optimal thing for SSE vs. the default expansion in the legalizer.
242 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
244 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
245 // With SSE3 we can use fisttpll to convert to a signed i64; without
246 // SSE, we're stuck with a fistpll.
247 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
249 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
252 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253 if (!X86ScalarSSEf64) {
254 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
255 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
258 // Without SSE, i64->f64 goes through memory.
259 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
263 // Scalar integer divide and remainder are lowered to use operations that
264 // produce two results, to match the available instructions. This exposes
265 // the two-result form to trivial CSE, which is able to combine x/y and x%y
266 // into a single instruction.
268 // Scalar integer multiply-high is also lowered to use two-result
269 // operations, to match the available instructions. However, plain multiply
270 // (low) operations are left as Legal, as there are single-result
271 // instructions for this in x86. Using the two-result multiply instructions
272 // when both high and low results are needed must be arranged by dagcombine.
273 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
275 setOperationAction(ISD::MULHS, VT, Expand);
276 setOperationAction(ISD::MULHU, VT, Expand);
277 setOperationAction(ISD::SDIV, VT, Expand);
278 setOperationAction(ISD::UDIV, VT, Expand);
279 setOperationAction(ISD::SREM, VT, Expand);
280 setOperationAction(ISD::UREM, VT, Expand);
282 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283 setOperationAction(ISD::ADDC, VT, Custom);
284 setOperationAction(ISD::ADDE, VT, Custom);
285 setOperationAction(ISD::SUBC, VT, Custom);
286 setOperationAction(ISD::SUBE, VT, Custom);
289 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
290 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
291 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
292 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
293 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
294 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
295 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
296 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
297 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
301 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
305 if (Subtarget->is64Bit())
306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
308 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
309 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
310 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
312 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
313 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
314 // is. We should promote the value to 64-bits to solve this.
315 // This is what the CRT headers do - `fmodf` is an inline header
316 // function casting to f64 and calling `fmod`.
317 setOperationAction(ISD::FREM , MVT::f32 , Promote);
319 setOperationAction(ISD::FREM , MVT::f32 , Expand);
322 setOperationAction(ISD::FREM , MVT::f64 , Expand);
323 setOperationAction(ISD::FREM , MVT::f80 , Expand);
324 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
326 // Promote the i8 variants and force them on up to i32 which has a shorter
328 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
329 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
331 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
332 if (Subtarget->hasBMI()) {
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
335 if (Subtarget->is64Bit())
336 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
338 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
339 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
340 if (Subtarget->is64Bit())
341 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
344 if (Subtarget->hasLZCNT()) {
345 // When promoting the i8 variants, force them to i32 for a shorter
347 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
348 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
350 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
352 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
353 if (Subtarget->is64Bit())
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
356 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
357 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
358 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
362 if (Subtarget->is64Bit()) {
363 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
364 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
368 // Special handling for half-precision floating point conversions.
369 // If we don't have F16C support, then lower half float conversions
370 // into library calls.
371 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
376 // There's never any support for operations beyond MVT::f32.
377 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
382 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
389 if (Subtarget->hasPOPCNT()) {
390 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
392 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
393 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
394 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
399 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
401 if (!Subtarget->hasMOVBE())
402 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
404 // These should be promoted to a larger select which is supported.
405 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
406 // X86 wants to expand cmov itself.
407 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
408 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
409 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
410 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
411 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
413 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
414 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
416 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
417 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
423 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
424 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426 // support continuation, user-level threading, and etc.. As a result, no
427 // other SjLj exception interfaces are implemented and please don't build
428 // your own exception handling based on them.
429 // LLVM/Clang supports zero-cost DWARF exception handling.
430 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
434 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
435 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
436 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
437 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
438 if (Subtarget->is64Bit())
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
442 if (Subtarget->is64Bit()) {
443 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
444 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
445 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
446 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
447 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
449 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
451 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
452 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
455 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
456 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
459 if (Subtarget->hasSSE1())
460 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
462 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
464 // Expand certain atomics
465 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
472 if (Subtarget->hasCmpxchg16b()) {
473 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
476 // FIXME - use subtarget debug flags
477 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
482 if (Subtarget->isTarget64BitLP64()) {
483 setExceptionPointerRegister(X86::RAX);
484 setExceptionSelectorRegister(X86::RDX);
486 setExceptionPointerRegister(X86::EAX);
487 setExceptionSelectorRegister(X86::EDX);
489 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499 setOperationAction(ISD::VASTART , MVT::Other, Custom);
500 setOperationAction(ISD::VAEND , MVT::Other, Expand);
501 if (Subtarget->is64Bit()) {
502 setOperationAction(ISD::VAARG , MVT::Other, Custom);
503 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
505 // TargetInfo::CharPtrBuiltinVaList
506 setOperationAction(ISD::VAARG , MVT::Other, Expand);
507 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
510 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
511 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
513 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
515 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
517 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
520 // f32 and f64 use SSE.
521 // Set up the FP register classes.
522 addRegisterClass(MVT::f32, &X86::FR32RegClass);
523 addRegisterClass(MVT::f64, &X86::FR64RegClass);
525 // Use ANDPD to simulate FABS.
526 setOperationAction(ISD::FABS , MVT::f64, Custom);
527 setOperationAction(ISD::FABS , MVT::f32, Custom);
529 // Use XORP to simulate FNEG.
530 setOperationAction(ISD::FNEG , MVT::f64, Custom);
531 setOperationAction(ISD::FNEG , MVT::f32, Custom);
533 // Use ANDPD and ORPD to simulate FCOPYSIGN.
534 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
535 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537 // Lower this to FGETSIGNx86 plus an AND.
538 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
539 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541 // We don't support sin/cos/fmod
542 setOperationAction(ISD::FSIN , MVT::f64, Expand);
543 setOperationAction(ISD::FCOS , MVT::f64, Expand);
544 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
545 setOperationAction(ISD::FSIN , MVT::f32, Expand);
546 setOperationAction(ISD::FCOS , MVT::f32, Expand);
547 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549 // Expand FP immediates into loads from the stack, except for the special
551 addLegalFPImmediate(APFloat(+0.0)); // xorpd
552 addLegalFPImmediate(APFloat(+0.0f)); // xorps
553 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
554 // Use SSE for f32, x87 for f64.
555 // Set up the FP register classes.
556 addRegisterClass(MVT::f32, &X86::FR32RegClass);
557 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559 // Use ANDPS to simulate FABS.
560 setOperationAction(ISD::FABS , MVT::f32, Custom);
562 // Use XORP to simulate FNEG.
563 setOperationAction(ISD::FNEG , MVT::f32, Custom);
565 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
567 // Use ANDPS and ORPS to simulate FCOPYSIGN.
568 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
569 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571 // We don't support sin/cos/fmod
572 setOperationAction(ISD::FSIN , MVT::f32, Expand);
573 setOperationAction(ISD::FCOS , MVT::f32, Expand);
574 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576 // Special cases we handle for FP constants.
577 addLegalFPImmediate(APFloat(+0.0f)); // xorps
578 addLegalFPImmediate(APFloat(+0.0)); // FLD0
579 addLegalFPImmediate(APFloat(+1.0)); // FLD1
580 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
581 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583 if (!TM.Options.UnsafeFPMath) {
584 setOperationAction(ISD::FSIN , MVT::f64, Expand);
585 setOperationAction(ISD::FCOS , MVT::f64, Expand);
586 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588 } else if (!Subtarget->useSoftFloat()) {
589 // f32 and f64 in x87.
590 // Set up the FP register classes.
591 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
592 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
595 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
596 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599 if (!TM.Options.UnsafeFPMath) {
600 setOperationAction(ISD::FSIN , MVT::f64, Expand);
601 setOperationAction(ISD::FSIN , MVT::f32, Expand);
602 setOperationAction(ISD::FCOS , MVT::f64, Expand);
603 setOperationAction(ISD::FCOS , MVT::f32, Expand);
604 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
605 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607 addLegalFPImmediate(APFloat(+0.0)); // FLD0
608 addLegalFPImmediate(APFloat(+1.0)); // FLD1
609 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
612 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
613 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
614 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
617 // We don't support FMA.
618 setOperationAction(ISD::FMA, MVT::f64, Expand);
619 setOperationAction(ISD::FMA, MVT::f32, Expand);
621 // Long double always uses X87.
622 if (!Subtarget->useSoftFloat()) {
623 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
624 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
628 addLegalFPImmediate(TmpFlt); // FLD0
630 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
633 APFloat TmpFlt2(+1.0);
634 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636 addLegalFPImmediate(TmpFlt2); // FLD1
637 TmpFlt2.changeSign();
638 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
641 if (!TM.Options.UnsafeFPMath) {
642 setOperationAction(ISD::FSIN , MVT::f80, Expand);
643 setOperationAction(ISD::FCOS , MVT::f80, Expand);
644 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
647 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
648 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
649 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
650 setOperationAction(ISD::FRINT, MVT::f80, Expand);
651 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
652 setOperationAction(ISD::FMA, MVT::f80, Expand);
655 // Always use a library call for pow.
656 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
657 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
658 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
660 setOperationAction(ISD::FLOG, MVT::f80, Expand);
661 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
662 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
663 setOperationAction(ISD::FEXP, MVT::f80, Expand);
664 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
665 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
666 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668 // First set operation action for all vector types to either promote
669 // (for widening) or expand (for scalarization). Then we will selectively
670 // turn on ones that can be effectively codegen'd.
671 for (MVT VT : MVT::vector_valuetypes()) {
672 setOperationAction(ISD::ADD , VT, Expand);
673 setOperationAction(ISD::SUB , VT, Expand);
674 setOperationAction(ISD::FADD, VT, Expand);
675 setOperationAction(ISD::FNEG, VT, Expand);
676 setOperationAction(ISD::FSUB, VT, Expand);
677 setOperationAction(ISD::MUL , VT, Expand);
678 setOperationAction(ISD::FMUL, VT, Expand);
679 setOperationAction(ISD::SDIV, VT, Expand);
680 setOperationAction(ISD::UDIV, VT, Expand);
681 setOperationAction(ISD::FDIV, VT, Expand);
682 setOperationAction(ISD::SREM, VT, Expand);
683 setOperationAction(ISD::UREM, VT, Expand);
684 setOperationAction(ISD::LOAD, VT, Expand);
685 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
686 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
687 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
688 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
689 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
690 setOperationAction(ISD::FABS, VT, Expand);
691 setOperationAction(ISD::FSIN, VT, Expand);
692 setOperationAction(ISD::FSINCOS, VT, Expand);
693 setOperationAction(ISD::FCOS, VT, Expand);
694 setOperationAction(ISD::FSINCOS, VT, Expand);
695 setOperationAction(ISD::FREM, VT, Expand);
696 setOperationAction(ISD::FMA, VT, Expand);
697 setOperationAction(ISD::FPOWI, VT, Expand);
698 setOperationAction(ISD::FSQRT, VT, Expand);
699 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
700 setOperationAction(ISD::FFLOOR, VT, Expand);
701 setOperationAction(ISD::FCEIL, VT, Expand);
702 setOperationAction(ISD::FTRUNC, VT, Expand);
703 setOperationAction(ISD::FRINT, VT, Expand);
704 setOperationAction(ISD::FNEARBYINT, VT, Expand);
705 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
706 setOperationAction(ISD::MULHS, VT, Expand);
707 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
708 setOperationAction(ISD::MULHU, VT, Expand);
709 setOperationAction(ISD::SDIVREM, VT, Expand);
710 setOperationAction(ISD::UDIVREM, VT, Expand);
711 setOperationAction(ISD::FPOW, VT, Expand);
712 setOperationAction(ISD::CTPOP, VT, Expand);
713 setOperationAction(ISD::CTTZ, VT, Expand);
714 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
715 setOperationAction(ISD::CTLZ, VT, Expand);
716 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
717 setOperationAction(ISD::SHL, VT, Expand);
718 setOperationAction(ISD::SRA, VT, Expand);
719 setOperationAction(ISD::SRL, VT, Expand);
720 setOperationAction(ISD::ROTL, VT, Expand);
721 setOperationAction(ISD::ROTR, VT, Expand);
722 setOperationAction(ISD::BSWAP, VT, Expand);
723 setOperationAction(ISD::SETCC, VT, Expand);
724 setOperationAction(ISD::FLOG, VT, Expand);
725 setOperationAction(ISD::FLOG2, VT, Expand);
726 setOperationAction(ISD::FLOG10, VT, Expand);
727 setOperationAction(ISD::FEXP, VT, Expand);
728 setOperationAction(ISD::FEXP2, VT, Expand);
729 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
730 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
731 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
732 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
733 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
734 setOperationAction(ISD::TRUNCATE, VT, Expand);
735 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
736 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
737 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
738 setOperationAction(ISD::VSELECT, VT, Expand);
739 setOperationAction(ISD::SELECT_CC, VT, Expand);
740 for (MVT InnerVT : MVT::vector_valuetypes()) {
741 setTruncStoreAction(InnerVT, VT, Expand);
743 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
744 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
747 // types, we have to deal with them whether we ask for Expansion or not.
748 // Setting Expand causes its own optimisation problems though, so leave
750 if (VT.getVectorElementType() == MVT::i1)
751 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
754 // split/scalarized right now.
755 if (VT.getVectorElementType() == MVT::f16)
756 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
760 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
761 // with -msoft-float, disable use of MMX as well.
762 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
763 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
764 // No operations on x86mmx supported, everything uses intrinsics.
767 // MMX-sized vectors (other than x86mmx) are expected to be expanded
768 // into smaller operations.
769 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
770 setOperationAction(ISD::MULHS, MMXTy, Expand);
771 setOperationAction(ISD::AND, MMXTy, Expand);
772 setOperationAction(ISD::OR, MMXTy, Expand);
773 setOperationAction(ISD::XOR, MMXTy, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
775 setOperationAction(ISD::SELECT, MMXTy, Expand);
776 setOperationAction(ISD::BITCAST, MMXTy, Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
781 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
784 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
785 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
786 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
787 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
788 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
789 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
790 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
791 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
792 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
793 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
794 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
795 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
796 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
799 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
800 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
803 // registers cannot be used even for integer operations.
804 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
805 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
806 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
807 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
810 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
811 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
812 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
813 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
814 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
815 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
816 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
817 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
818 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
819 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
820 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
821 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
822 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
823 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
825 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
831 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
833 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
834 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
835 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
836 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
838 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
839 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
840 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
841 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
844 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
847 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
850 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
851 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
852 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
854 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
855 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
856 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
857 // ISD::CTTZ v2i64 - scalarization is faster.
858 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
859 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
861 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
863 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
864 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
865 MVT VT = (MVT::SimpleValueType)i;
866 // Do not attempt to custom lower non-power-of-2 vectors
867 if (!isPowerOf2_32(VT.getVectorNumElements()))
869 // Do not attempt to custom lower non-128-bit vectors
870 if (!VT.is128BitVector())
872 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
873 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
874 setOperationAction(ISD::VSELECT, VT, Custom);
875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
878 // We support custom legalizing of sext and anyext loads for specific
879 // memory vector types which we can load as a scalar (or sequence of
880 // scalars) and extend in-register to a legal 128-bit vector type. For sext
881 // loads these must work with a single scalar load.
882 for (MVT VT : MVT::integer_vector_valuetypes()) {
883 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
884 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
885 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
886 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
887 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
888 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
889 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
890 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
891 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
895 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
897 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
898 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
899 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
901 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
903 if (Subtarget->is64Bit()) {
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
908 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910 MVT VT = (MVT::SimpleValueType)i;
912 // Do not attempt to promote non-128-bit vectors
913 if (!VT.is128BitVector())
916 setOperationAction(ISD::AND, VT, Promote);
917 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
918 setOperationAction(ISD::OR, VT, Promote);
919 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
920 setOperationAction(ISD::XOR, VT, Promote);
921 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
922 setOperationAction(ISD::LOAD, VT, Promote);
923 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
924 setOperationAction(ISD::SELECT, VT, Promote);
925 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928 // Custom lower v2i64 and v2f64 selects.
929 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
930 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
931 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
932 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
934 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
935 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
937 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
939 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
940 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
941 // As there is no 64-bit GPR available, we need build a special custom
942 // sequence to convert from v2i32 to v2f32.
943 if (!Subtarget->is64Bit())
944 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
946 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
947 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
949 for (MVT VT : MVT::fp_vector_valuetypes())
950 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
953 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
954 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
957 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
960 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
961 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
962 setOperationAction(ISD::FRINT, RoundedTy, Legal);
963 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
966 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
967 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
968 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
969 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
970 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
971 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
972 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
973 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
975 // FIXME: Do we need to handle scalar-to-vector here?
976 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
978 // We directly match byte blends in the backend as they match the VSELECT
980 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
982 // SSE41 brings specific instructions for doing vector sign extend even in
983 // cases where we don't have SRA.
984 for (MVT VT : MVT::integer_vector_valuetypes()) {
985 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
992 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
999 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005 // i8 and i16 vectors are custom because the source register and source
1006 // source memory operand types are not the same width. f32 vectors are
1007 // custom since the immediate controlling the insert encodes additional
1009 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1014 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019 // FIXME: these should be Legal, but that's only for the case where
1020 // the index is constant. For now custom expand to deal with that.
1021 if (Subtarget->is64Bit()) {
1022 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1027 if (Subtarget->hasSSE2()) {
1028 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1035 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1036 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1038 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1039 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1041 // In the customized shift lowering, the legal cases in AVX2 will be
1043 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1044 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1046 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1047 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1049 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1050 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1053 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1054 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1055 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1058 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1059 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1061 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1062 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1063 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1065 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1066 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1074 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1075 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1076 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1078 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1079 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1087 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1088 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1089 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1091 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1092 // even though v8i16 is a legal type.
1093 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1094 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1095 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1097 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1098 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1099 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1101 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1102 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1104 for (MVT VT : MVT::fp_vector_valuetypes())
1105 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1107 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1108 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1110 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1111 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1113 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1114 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1116 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1117 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1118 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1119 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1121 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1122 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1123 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1125 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1126 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1127 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1128 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1129 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1130 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1131 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1132 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1133 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1134 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1135 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1136 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1138 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1139 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1140 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1141 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1143 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1144 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1145 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1146 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1147 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1148 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1149 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1150 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1152 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1153 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1154 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1156 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1157 setOperationAction(ISD::FMA, MVT::f32, Legal);
1158 setOperationAction(ISD::FMA, MVT::f64, Legal);
1161 if (Subtarget->hasInt256()) {
1162 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1163 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1164 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1165 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1167 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1168 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1169 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1170 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1172 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1173 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1174 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1175 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1177 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1178 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1179 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1180 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1182 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1183 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1184 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1185 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1186 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1187 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1188 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1189 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1190 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1191 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1192 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1193 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1195 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1196 // when we have a 256bit-wide blend with immediate.
1197 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1199 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1200 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1201 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1202 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1203 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1204 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1205 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1207 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1208 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1209 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1210 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1211 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1212 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1214 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1215 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1216 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1217 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1219 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1220 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1221 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1222 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1224 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1226 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1227 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1229 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1231 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1232 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1233 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1234 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1235 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1237 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1238 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1239 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1240 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1243 // In the customized shift lowering, the legal cases in AVX2 will be
1245 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1246 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1248 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1249 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1254 // Custom lower several nodes for 256-bit types.
1255 for (MVT VT : MVT::vector_valuetypes()) {
1256 if (VT.getScalarSizeInBits() >= 32) {
1257 setOperationAction(ISD::MLOAD, VT, Legal);
1258 setOperationAction(ISD::MSTORE, VT, Legal);
1260 // Extract subvector is special because the value type
1261 // (result) is 128-bit but the source is 256-bit wide.
1262 if (VT.is128BitVector()) {
1263 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1265 // Do not attempt to custom lower other non-256-bit vectors
1266 if (!VT.is256BitVector())
1269 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1270 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1271 setOperationAction(ISD::VSELECT, VT, Custom);
1272 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1273 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1275 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1276 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1279 if (Subtarget->hasInt256())
1280 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1282 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284 MVT VT = (MVT::SimpleValueType)i;
1286 // Do not attempt to promote non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::AND, VT, Promote);
1291 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1292 setOperationAction(ISD::OR, VT, Promote);
1293 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1294 setOperationAction(ISD::XOR, VT, Promote);
1295 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1296 setOperationAction(ISD::LOAD, VT, Promote);
1297 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1298 setOperationAction(ISD::SELECT, VT, Promote);
1299 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1304 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1313 for (MVT VT : MVT::fp_vector_valuetypes())
1314 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1316 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1317 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1318 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1319 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1320 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1321 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1322 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1323 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1324 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1325 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1326 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1327 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1329 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1330 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1331 setOperationAction(ISD::XOR, MVT::i1, Legal);
1332 setOperationAction(ISD::OR, MVT::i1, Legal);
1333 setOperationAction(ISD::AND, MVT::i1, Legal);
1334 setOperationAction(ISD::SUB, MVT::i1, Custom);
1335 setOperationAction(ISD::ADD, MVT::i1, Custom);
1336 setOperationAction(ISD::MUL, MVT::i1, Custom);
1337 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1338 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1343 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1350 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1351 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1356 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1357 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1359 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1361 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1363 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1364 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1365 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1367 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1368 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1371 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1372 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1373 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1374 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1376 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1377 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1378 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1379 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1380 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1381 if (Subtarget->hasVLX()){
1382 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1383 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1384 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1385 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1386 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1388 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1389 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1390 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1391 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1392 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1394 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1395 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1396 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1397 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1398 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1399 if (Subtarget->hasDQI()) {
1400 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1401 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1403 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1404 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1405 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1406 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1407 if (Subtarget->hasVLX()) {
1408 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1409 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1410 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1411 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1412 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1413 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1414 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1418 if (Subtarget->hasVLX()) {
1419 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1421 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1422 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1423 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1424 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1425 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1426 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1428 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1429 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1430 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1431 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1432 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1433 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1434 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1437 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1438 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1439 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1440 if (Subtarget->hasDQI()) {
1441 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1442 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1444 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1445 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1446 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1447 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1448 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1449 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1450 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1451 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1452 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1453 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1455 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1456 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1457 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1458 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1459 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1461 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1462 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1464 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1466 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1467 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1468 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1469 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1470 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1471 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1472 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1473 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1474 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1475 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1476 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1478 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1479 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1480 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1481 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1482 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1483 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1484 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1485 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1487 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1488 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1490 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1491 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1493 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1495 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1496 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1498 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1499 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1501 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1502 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1504 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1505 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1506 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1507 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1508 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1509 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1511 if (Subtarget->hasCDI()) {
1512 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1513 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1515 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1517 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1518 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1520 if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1521 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1522 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1523 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1524 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1525 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1526 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1527 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1528 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1530 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1531 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1532 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1533 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1535 if (Subtarget->hasDQI()) {
1536 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1537 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1538 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1540 // Custom lower several nodes.
1541 for (MVT VT : MVT::vector_valuetypes()) {
1542 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544 setOperationAction(ISD::AND, VT, Legal);
1545 setOperationAction(ISD::OR, VT, Legal);
1546 setOperationAction(ISD::XOR, VT, Legal);
1548 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1549 setOperationAction(ISD::MGATHER, VT, Custom);
1550 setOperationAction(ISD::MSCATTER, VT, Custom);
1552 // Extract subvector is special because the value type
1553 // (result) is 256/128-bit but the source is 512-bit wide.
1554 if (VT.is128BitVector() || VT.is256BitVector()) {
1555 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1557 if (VT.getVectorElementType() == MVT::i1)
1558 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1560 // Do not attempt to custom lower other non-512-bit vectors
1561 if (!VT.is512BitVector())
1564 if (EltSize >= 32) {
1565 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1566 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1567 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1568 setOperationAction(ISD::VSELECT, VT, Legal);
1569 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1570 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1571 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1572 setOperationAction(ISD::MLOAD, VT, Legal);
1573 setOperationAction(ISD::MSTORE, VT, Legal);
1576 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1577 MVT VT = (MVT::SimpleValueType)i;
1579 // Do not attempt to promote non-512-bit vectors.
1580 if (!VT.is512BitVector())
1583 setOperationAction(ISD::SELECT, VT, Promote);
1584 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1588 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1589 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1590 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1592 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1593 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1595 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1596 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1597 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1598 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1599 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1600 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1601 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1602 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1603 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1604 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1605 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1606 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Legal);
1607 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Legal);
1608 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1609 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1610 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1611 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1612 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1613 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1614 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1615 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1616 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1617 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1618 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1619 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1621 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1622 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1623 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1624 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1625 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1626 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1627 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1628 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1629 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1630 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1631 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1632 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1633 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1635 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1636 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1637 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1638 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1639 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1640 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1641 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1642 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1644 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1645 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1646 if (Subtarget->hasVLX())
1647 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1649 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1650 const MVT VT = (MVT::SimpleValueType)i;
1652 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1654 // Do not attempt to promote non-512-bit vectors.
1655 if (!VT.is512BitVector())
1659 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1660 setOperationAction(ISD::VSELECT, VT, Legal);
1665 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1666 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1667 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1669 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1670 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1671 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1672 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1673 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1674 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1675 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1676 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1677 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1678 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1679 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1680 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1682 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1683 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1684 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1685 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1686 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1687 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1688 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1689 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1691 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1692 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1693 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1694 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1695 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1696 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1697 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1698 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1701 // We want to custom lower some of our intrinsics.
1702 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1703 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1704 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1705 if (!Subtarget->is64Bit())
1706 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1708 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1709 // handle type legalization for these operations here.
1711 // FIXME: We really should do custom legalization for addition and
1712 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1713 // than generic legalization for 64-bit multiplication-with-overflow, though.
1714 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1715 // Add/Sub/Mul with overflow operations are custom lowered.
1717 setOperationAction(ISD::SADDO, VT, Custom);
1718 setOperationAction(ISD::UADDO, VT, Custom);
1719 setOperationAction(ISD::SSUBO, VT, Custom);
1720 setOperationAction(ISD::USUBO, VT, Custom);
1721 setOperationAction(ISD::SMULO, VT, Custom);
1722 setOperationAction(ISD::UMULO, VT, Custom);
1725 if (!Subtarget->is64Bit()) {
1726 // These libcalls are not available in 32-bit.
1727 setLibcallName(RTLIB::SHL_I128, nullptr);
1728 setLibcallName(RTLIB::SRL_I128, nullptr);
1729 setLibcallName(RTLIB::SRA_I128, nullptr);
1732 // Combine sin / cos into one node or libcall if possible.
1733 if (Subtarget->hasSinCos()) {
1734 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1735 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1736 if (Subtarget->isTargetDarwin()) {
1737 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1738 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1739 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1740 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1744 if (Subtarget->isTargetWin64()) {
1745 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1746 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1747 setOperationAction(ISD::SREM, MVT::i128, Custom);
1748 setOperationAction(ISD::UREM, MVT::i128, Custom);
1749 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1750 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1753 // We have target-specific dag combine patterns for the following nodes:
1754 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1755 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1756 setTargetDAGCombine(ISD::BITCAST);
1757 setTargetDAGCombine(ISD::VSELECT);
1758 setTargetDAGCombine(ISD::SELECT);
1759 setTargetDAGCombine(ISD::SHL);
1760 setTargetDAGCombine(ISD::SRA);
1761 setTargetDAGCombine(ISD::SRL);
1762 setTargetDAGCombine(ISD::OR);
1763 setTargetDAGCombine(ISD::AND);
1764 setTargetDAGCombine(ISD::ADD);
1765 setTargetDAGCombine(ISD::FADD);
1766 setTargetDAGCombine(ISD::FSUB);
1767 setTargetDAGCombine(ISD::FMA);
1768 setTargetDAGCombine(ISD::SUB);
1769 setTargetDAGCombine(ISD::LOAD);
1770 setTargetDAGCombine(ISD::MLOAD);
1771 setTargetDAGCombine(ISD::STORE);
1772 setTargetDAGCombine(ISD::MSTORE);
1773 setTargetDAGCombine(ISD::ZERO_EXTEND);
1774 setTargetDAGCombine(ISD::ANY_EXTEND);
1775 setTargetDAGCombine(ISD::SIGN_EXTEND);
1776 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1777 setTargetDAGCombine(ISD::SINT_TO_FP);
1778 setTargetDAGCombine(ISD::UINT_TO_FP);
1779 setTargetDAGCombine(ISD::SETCC);
1780 setTargetDAGCombine(ISD::BUILD_VECTOR);
1781 setTargetDAGCombine(ISD::MUL);
1782 setTargetDAGCombine(ISD::XOR);
1784 computeRegisterProperties(Subtarget->getRegisterInfo());
1786 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1787 MaxStoresPerMemsetOptSize = 8;
1788 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1789 MaxStoresPerMemcpyOptSize = 4;
1790 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1791 MaxStoresPerMemmoveOptSize = 4;
1792 setPrefLoopAlignment(4); // 2^4 bytes.
1794 // A predictable cmov does not hurt on an in-order CPU.
1795 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1796 PredictableSelectIsExpensive = !Subtarget->isAtom();
1797 EnableExtLdPromotion = true;
1798 setPrefFunctionAlignment(4); // 2^4 bytes.
1800 verifyIntrinsicTables();
1803 // This has so far only been implemented for 64-bit MachO.
1804 bool X86TargetLowering::useLoadStackGuardNode() const {
1805 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1808 TargetLoweringBase::LegalizeTypeAction
1809 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1810 if (ExperimentalVectorWideningLegalization &&
1811 VT.getVectorNumElements() != 1 &&
1812 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1813 return TypeWidenVector;
1815 return TargetLoweringBase::getPreferredVectorAction(VT);
1818 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1821 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1823 const unsigned NumElts = VT.getVectorNumElements();
1824 const EVT EltVT = VT.getVectorElementType();
1825 if (VT.is512BitVector()) {
1826 if (Subtarget->hasAVX512())
1827 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1828 EltVT == MVT::f32 || EltVT == MVT::f64)
1830 case 8: return MVT::v8i1;
1831 case 16: return MVT::v16i1;
1833 if (Subtarget->hasBWI())
1834 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1836 case 32: return MVT::v32i1;
1837 case 64: return MVT::v64i1;
1841 if (VT.is256BitVector() || VT.is128BitVector()) {
1842 if (Subtarget->hasVLX())
1843 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1844 EltVT == MVT::f32 || EltVT == MVT::f64)
1846 case 2: return MVT::v2i1;
1847 case 4: return MVT::v4i1;
1848 case 8: return MVT::v8i1;
1850 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1851 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1853 case 8: return MVT::v8i1;
1854 case 16: return MVT::v16i1;
1855 case 32: return MVT::v32i1;
1859 return VT.changeVectorElementTypeToInteger();
1862 /// Helper for getByValTypeAlignment to determine
1863 /// the desired ByVal argument alignment.
1864 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1867 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1868 if (VTy->getBitWidth() == 128)
1870 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1871 unsigned EltAlign = 0;
1872 getMaxByValAlign(ATy->getElementType(), EltAlign);
1873 if (EltAlign > MaxAlign)
1874 MaxAlign = EltAlign;
1875 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1876 for (auto *EltTy : STy->elements()) {
1877 unsigned EltAlign = 0;
1878 getMaxByValAlign(EltTy, EltAlign);
1879 if (EltAlign > MaxAlign)
1880 MaxAlign = EltAlign;
1887 /// Return the desired alignment for ByVal aggregate
1888 /// function arguments in the caller parameter area. For X86, aggregates
1889 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1890 /// are at 4-byte boundaries.
1891 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1892 const DataLayout &DL) const {
1893 if (Subtarget->is64Bit()) {
1894 // Max of 8 and alignment of type.
1895 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1902 if (Subtarget->hasSSE1())
1903 getMaxByValAlign(Ty, Align);
1907 /// Returns the target specific optimal type for load
1908 /// and store operations as a result of memset, memcpy, and memmove
1909 /// lowering. If DstAlign is zero that means it's safe to destination
1910 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1911 /// means there isn't a need to check it against alignment requirement,
1912 /// probably because the source does not need to be loaded. If 'IsMemset' is
1913 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1914 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1915 /// source is constant so it does not need to be loaded.
1916 /// It returns EVT::Other if the type should be determined using generic
1917 /// target-independent logic.
1919 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1920 unsigned DstAlign, unsigned SrcAlign,
1921 bool IsMemset, bool ZeroMemset,
1923 MachineFunction &MF) const {
1924 const Function *F = MF.getFunction();
1925 if ((!IsMemset || ZeroMemset) &&
1926 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1928 (!Subtarget->isUnalignedMem16Slow() ||
1929 ((DstAlign == 0 || DstAlign >= 16) &&
1930 (SrcAlign == 0 || SrcAlign >= 16)))) {
1932 // FIXME: Check if unaligned 32-byte accesses are slow.
1933 if (Subtarget->hasInt256())
1935 if (Subtarget->hasFp256())
1938 if (Subtarget->hasSSE2())
1940 if (Subtarget->hasSSE1())
1942 } else if (!MemcpyStrSrc && Size >= 8 &&
1943 !Subtarget->is64Bit() &&
1944 Subtarget->hasSSE2()) {
1945 // Do not use f64 to lower memcpy if source is string constant. It's
1946 // better to use i32 to avoid the loads.
1950 // This is a compromise. If we reach here, unaligned accesses may be slow on
1951 // this target. However, creating smaller, aligned accesses could be even
1952 // slower and would certainly be a lot more code.
1953 if (Subtarget->is64Bit() && Size >= 8)
1958 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1960 return X86ScalarSSEf32;
1961 else if (VT == MVT::f64)
1962 return X86ScalarSSEf64;
1967 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1972 switch (VT.getSizeInBits()) {
1974 // 8-byte and under are always assumed to be fast.
1978 *Fast = !Subtarget->isUnalignedMem16Slow();
1981 *Fast = !Subtarget->isUnalignedMem32Slow();
1983 // TODO: What about AVX-512 (512-bit) accesses?
1986 // Misaligned accesses of any size are always allowed.
1990 /// Return the entry encoding for a jump table in the
1991 /// current function. The returned value is a member of the
1992 /// MachineJumpTableInfo::JTEntryKind enum.
1993 unsigned X86TargetLowering::getJumpTableEncoding() const {
1994 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1996 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1997 Subtarget->isPICStyleGOT())
1998 return MachineJumpTableInfo::EK_Custom32;
2000 // Otherwise, use the normal jump table encoding heuristics.
2001 return TargetLowering::getJumpTableEncoding();
2004 bool X86TargetLowering::useSoftFloat() const {
2005 return Subtarget->useSoftFloat();
2009 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2010 const MachineBasicBlock *MBB,
2011 unsigned uid,MCContext &Ctx) const{
2012 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2013 Subtarget->isPICStyleGOT());
2014 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2016 return MCSymbolRefExpr::create(MBB->getSymbol(),
2017 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2020 /// Returns relocation base for the given PIC jumptable.
2021 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2022 SelectionDAG &DAG) const {
2023 if (!Subtarget->is64Bit())
2024 // This doesn't have SDLoc associated with it, but is not really the
2025 // same as a Register.
2026 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2027 getPointerTy(DAG.getDataLayout()));
2031 /// This returns the relocation base for the given PIC jumptable,
2032 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2033 const MCExpr *X86TargetLowering::
2034 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2035 MCContext &Ctx) const {
2036 // X86-64 uses RIP relative addressing based on the jump table label.
2037 if (Subtarget->isPICStyleRIPRel())
2038 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2040 // Otherwise, the reference is relative to the PIC base.
2041 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2044 std::pair<const TargetRegisterClass *, uint8_t>
2045 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2047 const TargetRegisterClass *RRC = nullptr;
2049 switch (VT.SimpleTy) {
2051 return TargetLowering::findRepresentativeClass(TRI, VT);
2052 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2053 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2056 RRC = &X86::VR64RegClass;
2058 case MVT::f32: case MVT::f64:
2059 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2060 case MVT::v4f32: case MVT::v2f64:
2061 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2063 RRC = &X86::VR128RegClass;
2066 return std::make_pair(RRC, Cost);
2069 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2070 unsigned &Offset) const {
2071 if (!Subtarget->isTargetLinux())
2074 if (Subtarget->is64Bit()) {
2075 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2077 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2089 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2090 if (!Subtarget->isTargetAndroid())
2091 return TargetLowering::getSafeStackPointerLocation(IRB);
2093 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2094 // definition of TLS_SLOT_SAFESTACK in
2095 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2096 unsigned AddressSpace, Offset;
2097 if (Subtarget->is64Bit()) {
2098 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2100 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2110 return ConstantExpr::getIntToPtr(
2111 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2112 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2115 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2116 unsigned DestAS) const {
2117 assert(SrcAS != DestAS && "Expected different address spaces!");
2119 return SrcAS < 256 && DestAS < 256;
2122 //===----------------------------------------------------------------------===//
2123 // Return Value Calling Convention Implementation
2124 //===----------------------------------------------------------------------===//
2126 #include "X86GenCallingConv.inc"
2128 bool X86TargetLowering::CanLowerReturn(
2129 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2130 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2131 SmallVector<CCValAssign, 16> RVLocs;
2132 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2133 return CCInfo.CheckReturn(Outs, RetCC_X86);
2136 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2137 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2142 X86TargetLowering::LowerReturn(SDValue Chain,
2143 CallingConv::ID CallConv, bool isVarArg,
2144 const SmallVectorImpl<ISD::OutputArg> &Outs,
2145 const SmallVectorImpl<SDValue> &OutVals,
2146 SDLoc dl, SelectionDAG &DAG) const {
2147 MachineFunction &MF = DAG.getMachineFunction();
2148 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2150 SmallVector<CCValAssign, 16> RVLocs;
2151 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2152 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2155 SmallVector<SDValue, 6> RetOps;
2156 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2157 // Operand #1 = Bytes To Pop
2158 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2161 // Copy the result values into the output registers.
2162 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2163 CCValAssign &VA = RVLocs[i];
2164 assert(VA.isRegLoc() && "Can only return in registers!");
2165 SDValue ValToCopy = OutVals[i];
2166 EVT ValVT = ValToCopy.getValueType();
2168 // Promote values to the appropriate types.
2169 if (VA.getLocInfo() == CCValAssign::SExt)
2170 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2171 else if (VA.getLocInfo() == CCValAssign::ZExt)
2172 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2173 else if (VA.getLocInfo() == CCValAssign::AExt) {
2174 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2175 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2177 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2179 else if (VA.getLocInfo() == CCValAssign::BCvt)
2180 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2182 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2183 "Unexpected FP-extend for return value.");
2185 // If this is x86-64, and we disabled SSE, we can't return FP values,
2186 // or SSE or MMX vectors.
2187 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2188 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2189 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2190 report_fatal_error("SSE register return with SSE disabled");
2192 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2193 // llvm-gcc has never done it right and no one has noticed, so this
2194 // should be OK for now.
2195 if (ValVT == MVT::f64 &&
2196 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2197 report_fatal_error("SSE2 register return with SSE2 disabled");
2199 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2200 // the RET instruction and handled by the FP Stackifier.
2201 if (VA.getLocReg() == X86::FP0 ||
2202 VA.getLocReg() == X86::FP1) {
2203 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2204 // change the value to the FP stack register class.
2205 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2206 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2207 RetOps.push_back(ValToCopy);
2208 // Don't emit a copytoreg.
2212 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2213 // which is returned in RAX / RDX.
2214 if (Subtarget->is64Bit()) {
2215 if (ValVT == MVT::x86mmx) {
2216 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2217 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2218 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2220 // If we don't have SSE2 available, convert to v4f32 so the generated
2221 // register is legal.
2222 if (!Subtarget->hasSSE2())
2223 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2228 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2229 Flag = Chain.getValue(1);
2230 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2233 // All x86 ABIs require that for returning structs by value we copy
2234 // the sret argument into %rax/%eax (depending on ABI) for the return.
2235 // We saved the argument into a virtual register in the entry block,
2236 // so now we copy the value out and into %rax/%eax.
2238 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2239 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2240 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2241 // either case FuncInfo->setSRetReturnReg() will have been called.
2242 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2243 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2244 getPointerTy(MF.getDataLayout()));
2247 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2248 X86::RAX : X86::EAX;
2249 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2250 Flag = Chain.getValue(1);
2252 // RAX/EAX now acts like a return value.
2254 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2257 RetOps[0] = Chain; // Update chain.
2259 // Add the flag if we have it.
2261 RetOps.push_back(Flag);
2263 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2266 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2267 if (N->getNumValues() != 1)
2269 if (!N->hasNUsesOfValue(1, 0))
2272 SDValue TCChain = Chain;
2273 SDNode *Copy = *N->use_begin();
2274 if (Copy->getOpcode() == ISD::CopyToReg) {
2275 // If the copy has a glue operand, we conservatively assume it isn't safe to
2276 // perform a tail call.
2277 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2279 TCChain = Copy->getOperand(0);
2280 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2283 bool HasRet = false;
2284 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2286 if (UI->getOpcode() != X86ISD::RET_FLAG)
2288 // If we are returning more than one value, we can definitely
2289 // not make a tail call see PR19530
2290 if (UI->getNumOperands() > 4)
2292 if (UI->getNumOperands() == 4 &&
2293 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2306 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2307 ISD::NodeType ExtendKind) const {
2309 // TODO: Is this also valid on 32-bit?
2310 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2311 ReturnMVT = MVT::i8;
2313 ReturnMVT = MVT::i32;
2315 EVT MinVT = getRegisterType(Context, ReturnMVT);
2316 return VT.bitsLT(MinVT) ? MinVT : VT;
2319 /// Lower the result values of a call into the
2320 /// appropriate copies out of appropriate physical registers.
2323 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2324 CallingConv::ID CallConv, bool isVarArg,
2325 const SmallVectorImpl<ISD::InputArg> &Ins,
2326 SDLoc dl, SelectionDAG &DAG,
2327 SmallVectorImpl<SDValue> &InVals) const {
2329 // Assign locations to each value returned by this call.
2330 SmallVector<CCValAssign, 16> RVLocs;
2331 bool Is64Bit = Subtarget->is64Bit();
2332 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2334 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2336 // Copy all of the result registers out of their specified physreg.
2337 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2338 CCValAssign &VA = RVLocs[i];
2339 EVT CopyVT = VA.getLocVT();
2341 // If this is x86-64, and we disabled SSE, we can't return FP values
2342 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2343 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2344 report_fatal_error("SSE register return with SSE disabled");
2347 // If we prefer to use the value in xmm registers, copy it out as f80 and
2348 // use a truncate to move it from fp stack reg to xmm reg.
2349 bool RoundAfterCopy = false;
2350 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2351 isScalarFPTypeInSSEReg(VA.getValVT())) {
2353 RoundAfterCopy = (CopyVT != VA.getLocVT());
2356 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2357 CopyVT, InFlag).getValue(1);
2358 SDValue Val = Chain.getValue(0);
2361 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2362 // This truncation won't change the value.
2363 DAG.getIntPtrConstant(1, dl));
2365 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2366 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2368 InFlag = Chain.getValue(2);
2369 InVals.push_back(Val);
2375 //===----------------------------------------------------------------------===//
2376 // C & StdCall & Fast Calling Convention implementation
2377 //===----------------------------------------------------------------------===//
2378 // StdCall calling convention seems to be standard for many Windows' API
2379 // routines and around. It differs from C calling convention just a little:
2380 // callee should clean up the stack, not caller. Symbols should be also
2381 // decorated in some fancy way :) It doesn't support any vector arguments.
2382 // For info on fast calling convention see Fast Calling Convention (tail call)
2383 // implementation LowerX86_32FastCCCallTo.
2385 /// CallIsStructReturn - Determines whether a call uses struct return
2387 enum StructReturnType {
2392 static StructReturnType
2393 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2395 return NotStructReturn;
2397 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2398 if (!Flags.isSRet())
2399 return NotStructReturn;
2400 if (Flags.isInReg())
2401 return RegStructReturn;
2402 return StackStructReturn;
2405 /// Determines whether a function uses struct return semantics.
2406 static StructReturnType
2407 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2409 return NotStructReturn;
2411 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2412 if (!Flags.isSRet())
2413 return NotStructReturn;
2414 if (Flags.isInReg())
2415 return RegStructReturn;
2416 return StackStructReturn;
2419 /// Make a copy of an aggregate at address specified by "Src" to address
2420 /// "Dst" with size and alignment information specified by the specific
2421 /// parameter attribute. The copy will be passed as a byval function parameter.
2423 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2424 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2426 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2428 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2429 /*isVolatile*/false, /*AlwaysInline=*/true,
2430 /*isTailCall*/false,
2431 MachinePointerInfo(), MachinePointerInfo());
2434 /// Return true if the calling convention is one that
2435 /// supports tail call optimization.
2436 static bool IsTailCallConvention(CallingConv::ID CC) {
2437 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2438 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2441 /// \brief Return true if the calling convention is a C calling convention.
2442 static bool IsCCallConvention(CallingConv::ID CC) {
2443 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2444 CC == CallingConv::X86_64_SysV);
2447 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2449 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2450 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2454 CallingConv::ID CalleeCC = CS.getCallingConv();
2455 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2461 /// Return true if the function is being made into
2462 /// a tailcall target by changing its ABI.
2463 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2464 bool GuaranteedTailCallOpt) {
2465 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2469 X86TargetLowering::LowerMemArgument(SDValue Chain,
2470 CallingConv::ID CallConv,
2471 const SmallVectorImpl<ISD::InputArg> &Ins,
2472 SDLoc dl, SelectionDAG &DAG,
2473 const CCValAssign &VA,
2474 MachineFrameInfo *MFI,
2476 // Create the nodes corresponding to a load from this parameter slot.
2477 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2478 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2479 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2480 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2483 // If value is passed by pointer we have address passed instead of the value
2485 bool ExtendedInMem = VA.isExtInLoc() &&
2486 VA.getValVT().getScalarType() == MVT::i1;
2488 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2489 ValVT = VA.getLocVT();
2491 ValVT = VA.getValVT();
2493 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2494 // changed with more analysis.
2495 // In case of tail call optimization mark all arguments mutable. Since they
2496 // could be overwritten by lowering of arguments in case of a tail call.
2497 if (Flags.isByVal()) {
2498 unsigned Bytes = Flags.getByValSize();
2499 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2500 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2501 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2503 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2504 VA.getLocMemOffset(), isImmutable);
2505 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2506 SDValue Val = DAG.getLoad(
2507 ValVT, dl, Chain, FIN,
2508 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2510 return ExtendedInMem ?
2511 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2515 // FIXME: Get this from tablegen.
2516 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2517 const X86Subtarget *Subtarget) {
2518 assert(Subtarget->is64Bit());
2520 if (Subtarget->isCallingConvWin64(CallConv)) {
2521 static const MCPhysReg GPR64ArgRegsWin64[] = {
2522 X86::RCX, X86::RDX, X86::R8, X86::R9
2524 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2527 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2528 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2530 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2533 // FIXME: Get this from tablegen.
2534 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2535 CallingConv::ID CallConv,
2536 const X86Subtarget *Subtarget) {
2537 assert(Subtarget->is64Bit());
2538 if (Subtarget->isCallingConvWin64(CallConv)) {
2539 // The XMM registers which might contain var arg parameters are shadowed
2540 // in their paired GPR. So we only need to save the GPR to their home
2542 // TODO: __vectorcall will change this.
2546 const Function *Fn = MF.getFunction();
2547 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2548 bool isSoftFloat = Subtarget->useSoftFloat();
2549 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2550 "SSE register cannot be used when SSE is disabled!");
2551 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2552 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2556 static const MCPhysReg XMMArgRegs64Bit[] = {
2557 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2558 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2560 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2563 SDValue X86TargetLowering::LowerFormalArguments(
2564 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2565 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2566 SmallVectorImpl<SDValue> &InVals) const {
2567 MachineFunction &MF = DAG.getMachineFunction();
2568 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2569 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2571 const Function* Fn = MF.getFunction();
2572 if (Fn->hasExternalLinkage() &&
2573 Subtarget->isTargetCygMing() &&
2574 Fn->getName() == "main")
2575 FuncInfo->setForceFramePointer(true);
2577 MachineFrameInfo *MFI = MF.getFrameInfo();
2578 bool Is64Bit = Subtarget->is64Bit();
2579 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2581 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2582 "Var args not supported with calling convention fastcc, ghc or hipe");
2584 // Assign locations to all of the incoming arguments.
2585 SmallVector<CCValAssign, 16> ArgLocs;
2586 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2588 // Allocate shadow area for Win64
2590 CCInfo.AllocateStack(32, 8);
2592 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2594 unsigned LastVal = ~0U;
2596 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2597 CCValAssign &VA = ArgLocs[i];
2598 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2600 assert(VA.getValNo() != LastVal &&
2601 "Don't support value assigned to multiple locs yet");
2603 LastVal = VA.getValNo();
2605 if (VA.isRegLoc()) {
2606 EVT RegVT = VA.getLocVT();
2607 const TargetRegisterClass *RC;
2608 if (RegVT == MVT::i32)
2609 RC = &X86::GR32RegClass;
2610 else if (Is64Bit && RegVT == MVT::i64)
2611 RC = &X86::GR64RegClass;
2612 else if (RegVT == MVT::f32)
2613 RC = &X86::FR32RegClass;
2614 else if (RegVT == MVT::f64)
2615 RC = &X86::FR64RegClass;
2616 else if (RegVT.is512BitVector())
2617 RC = &X86::VR512RegClass;
2618 else if (RegVT.is256BitVector())
2619 RC = &X86::VR256RegClass;
2620 else if (RegVT.is128BitVector())
2621 RC = &X86::VR128RegClass;
2622 else if (RegVT == MVT::x86mmx)
2623 RC = &X86::VR64RegClass;
2624 else if (RegVT == MVT::i1)
2625 RC = &X86::VK1RegClass;
2626 else if (RegVT == MVT::v8i1)
2627 RC = &X86::VK8RegClass;
2628 else if (RegVT == MVT::v16i1)
2629 RC = &X86::VK16RegClass;
2630 else if (RegVT == MVT::v32i1)
2631 RC = &X86::VK32RegClass;
2632 else if (RegVT == MVT::v64i1)
2633 RC = &X86::VK64RegClass;
2635 llvm_unreachable("Unknown argument type!");
2637 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2638 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2640 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2641 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2643 if (VA.getLocInfo() == CCValAssign::SExt)
2644 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2645 DAG.getValueType(VA.getValVT()));
2646 else if (VA.getLocInfo() == CCValAssign::ZExt)
2647 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2648 DAG.getValueType(VA.getValVT()));
2649 else if (VA.getLocInfo() == CCValAssign::BCvt)
2650 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2652 if (VA.isExtInLoc()) {
2653 // Handle MMX values passed in XMM regs.
2654 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2655 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2657 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2660 assert(VA.isMemLoc());
2661 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2664 // If value is passed via pointer - do a load.
2665 if (VA.getLocInfo() == CCValAssign::Indirect)
2666 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2667 MachinePointerInfo(), false, false, false, 0);
2669 InVals.push_back(ArgValue);
2672 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2673 // All x86 ABIs require that for returning structs by value we copy the
2674 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2675 // the argument into a virtual register so that we can access it from the
2677 if (Ins[i].Flags.isSRet()) {
2678 unsigned Reg = FuncInfo->getSRetReturnReg();
2680 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2681 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2682 FuncInfo->setSRetReturnReg(Reg);
2684 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2685 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2690 unsigned StackSize = CCInfo.getNextStackOffset();
2691 // Align stack specially for tail calls.
2692 if (FuncIsMadeTailCallSafe(CallConv,
2693 MF.getTarget().Options.GuaranteedTailCallOpt))
2694 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2696 // If the function takes variable number of arguments, make a frame index for
2697 // the start of the first vararg value... for expansion of llvm.va_start. We
2698 // can skip this if there are no va_start calls.
2699 if (MFI->hasVAStart() &&
2700 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2701 CallConv != CallingConv::X86_ThisCall))) {
2702 FuncInfo->setVarArgsFrameIndex(
2703 MFI->CreateFixedObject(1, StackSize, true));
2706 MachineModuleInfo &MMI = MF.getMMI();
2708 // Figure out if XMM registers are in use.
2709 assert(!(Subtarget->useSoftFloat() &&
2710 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2711 "SSE register cannot be used when SSE is disabled!");
2713 // 64-bit calling conventions support varargs and register parameters, so we
2714 // have to do extra work to spill them in the prologue.
2715 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2716 // Find the first unallocated argument registers.
2717 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2718 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2719 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2720 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2721 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2722 "SSE register cannot be used when SSE is disabled!");
2724 // Gather all the live in physical registers.
2725 SmallVector<SDValue, 6> LiveGPRs;
2726 SmallVector<SDValue, 8> LiveXMMRegs;
2728 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2729 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2731 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2733 if (!ArgXMMs.empty()) {
2734 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2735 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2736 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2737 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2738 LiveXMMRegs.push_back(
2739 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2744 // Get to the caller-allocated home save location. Add 8 to account
2745 // for the return address.
2746 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2747 FuncInfo->setRegSaveFrameIndex(
2748 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2749 // Fixup to set vararg frame on shadow area (4 x i64).
2751 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2753 // For X86-64, if there are vararg parameters that are passed via
2754 // registers, then we must store them to their spots on the stack so
2755 // they may be loaded by deferencing the result of va_next.
2756 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2757 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2758 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2759 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2762 // Store the integer parameter registers.
2763 SmallVector<SDValue, 8> MemOps;
2764 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2765 getPointerTy(DAG.getDataLayout()));
2766 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2767 for (SDValue Val : LiveGPRs) {
2768 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2769 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2771 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2772 MachinePointerInfo::getFixedStack(
2773 DAG.getMachineFunction(),
2774 FuncInfo->getRegSaveFrameIndex(), Offset),
2776 MemOps.push_back(Store);
2780 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2781 // Now store the XMM (fp + vector) parameter registers.
2782 SmallVector<SDValue, 12> SaveXMMOps;
2783 SaveXMMOps.push_back(Chain);
2784 SaveXMMOps.push_back(ALVal);
2785 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2786 FuncInfo->getRegSaveFrameIndex(), dl));
2787 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2788 FuncInfo->getVarArgsFPOffset(), dl));
2789 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2791 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2792 MVT::Other, SaveXMMOps));
2795 if (!MemOps.empty())
2796 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2799 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2800 // Find the largest legal vector type.
2801 MVT VecVT = MVT::Other;
2802 // FIXME: Only some x86_32 calling conventions support AVX512.
2803 if (Subtarget->hasAVX512() &&
2804 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2805 CallConv == CallingConv::Intel_OCL_BI)))
2806 VecVT = MVT::v16f32;
2807 else if (Subtarget->hasAVX())
2809 else if (Subtarget->hasSSE2())
2812 // We forward some GPRs and some vector types.
2813 SmallVector<MVT, 2> RegParmTypes;
2814 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2815 RegParmTypes.push_back(IntVT);
2816 if (VecVT != MVT::Other)
2817 RegParmTypes.push_back(VecVT);
2819 // Compute the set of forwarded registers. The rest are scratch.
2820 SmallVectorImpl<ForwardedRegister> &Forwards =
2821 FuncInfo->getForwardedMustTailRegParms();
2822 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2824 // Conservatively forward AL on x86_64, since it might be used for varargs.
2825 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2826 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2827 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2830 // Copy all forwards from physical to virtual registers.
2831 for (ForwardedRegister &F : Forwards) {
2832 // FIXME: Can we use a less constrained schedule?
2833 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2834 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2835 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2839 // Some CCs need callee pop.
2840 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2841 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2842 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2844 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2845 // If this is an sret function, the return should pop the hidden pointer.
2846 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2847 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2848 argsAreStructReturn(Ins) == StackStructReturn)
2849 FuncInfo->setBytesToPopOnReturn(4);
2853 // RegSaveFrameIndex is X86-64 only.
2854 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2855 if (CallConv == CallingConv::X86_FastCall ||
2856 CallConv == CallingConv::X86_ThisCall)
2857 // fastcc functions can't have varargs.
2858 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2861 FuncInfo->setArgumentStackSize(StackSize);
2863 if (MMI.hasWinEHFuncInfo(Fn)) {
2865 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2866 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2867 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2868 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2869 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2870 MachinePointerInfo::getFixedStack(
2871 DAG.getMachineFunction(), UnwindHelpFI),
2872 /*isVolatile=*/true,
2873 /*isNonTemporal=*/false, /*Alignment=*/0);
2875 // Functions using Win32 EH are considered to have opaque SP adjustments
2876 // to force local variables to be addressed from the frame or base
2878 MFI->setHasOpaqueSPAdjustment(true);
2886 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2887 SDValue StackPtr, SDValue Arg,
2888 SDLoc dl, SelectionDAG &DAG,
2889 const CCValAssign &VA,
2890 ISD::ArgFlagsTy Flags) const {
2891 unsigned LocMemOffset = VA.getLocMemOffset();
2892 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2893 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2895 if (Flags.isByVal())
2896 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2898 return DAG.getStore(
2899 Chain, dl, Arg, PtrOff,
2900 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2904 /// Emit a load of return address if tail call
2905 /// optimization is performed and it is required.
2907 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2908 SDValue &OutRetAddr, SDValue Chain,
2909 bool IsTailCall, bool Is64Bit,
2910 int FPDiff, SDLoc dl) const {
2911 // Adjust the Return address stack slot.
2912 EVT VT = getPointerTy(DAG.getDataLayout());
2913 OutRetAddr = getReturnAddressFrameIndex(DAG);
2915 // Load the "old" Return address.
2916 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2917 false, false, false, 0);
2918 return SDValue(OutRetAddr.getNode(), 1);
2921 /// Emit a store of the return address if tail call
2922 /// optimization is performed and it is required (FPDiff!=0).
2923 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2924 SDValue Chain, SDValue RetAddrFrIdx,
2925 EVT PtrVT, unsigned SlotSize,
2926 int FPDiff, SDLoc dl) {
2927 // Store the return address to the appropriate stack slot.
2928 if (!FPDiff) return Chain;
2929 // Calculate the new stack slot for the return address.
2930 int NewReturnAddrFI =
2931 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2933 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2934 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2935 MachinePointerInfo::getFixedStack(
2936 DAG.getMachineFunction(), NewReturnAddrFI),
2941 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2942 /// operation of specified width.
2943 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2945 unsigned NumElems = VT.getVectorNumElements();
2946 SmallVector<int, 8> Mask;
2947 Mask.push_back(NumElems);
2948 for (unsigned i = 1; i != NumElems; ++i)
2950 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2954 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2955 SmallVectorImpl<SDValue> &InVals) const {
2956 SelectionDAG &DAG = CLI.DAG;
2958 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2959 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2960 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2961 SDValue Chain = CLI.Chain;
2962 SDValue Callee = CLI.Callee;
2963 CallingConv::ID CallConv = CLI.CallConv;
2964 bool &isTailCall = CLI.IsTailCall;
2965 bool isVarArg = CLI.IsVarArg;
2967 MachineFunction &MF = DAG.getMachineFunction();
2968 bool Is64Bit = Subtarget->is64Bit();
2969 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2970 StructReturnType SR = callIsStructReturn(Outs);
2971 bool IsSibcall = false;
2972 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2973 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2975 if (Attr.getValueAsString() == "true")
2978 if (Subtarget->isPICStyleGOT() &&
2979 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2980 // If we are using a GOT, disable tail calls to external symbols with
2981 // default visibility. Tail calling such a symbol requires using a GOT
2982 // relocation, which forces early binding of the symbol. This breaks code
2983 // that require lazy function symbol resolution. Using musttail or
2984 // GuaranteedTailCallOpt will override this.
2985 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2986 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2987 G->getGlobal()->hasDefaultVisibility()))
2991 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2993 // Force this to be a tail call. The verifier rules are enough to ensure
2994 // that we can lower this successfully without moving the return address
2997 } else if (isTailCall) {
2998 // Check if it's really possible to do a tail call.
2999 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3000 isVarArg, SR != NotStructReturn,
3001 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3002 Outs, OutVals, Ins, DAG);
3004 // Sibcalls are automatically detected tailcalls which do not require
3006 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3013 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
3014 "Var args not supported with calling convention fastcc, ghc or hipe");
3016 // Analyze operands of the call, assigning locations to each operand.
3017 SmallVector<CCValAssign, 16> ArgLocs;
3018 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3020 // Allocate shadow area for Win64
3022 CCInfo.AllocateStack(32, 8);
3024 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3026 // Get a count of how many bytes are to be pushed on the stack.
3027 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3029 // This is a sibcall. The memory operands are available in caller's
3030 // own caller's stack.
3032 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3033 IsTailCallConvention(CallConv))
3034 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3037 if (isTailCall && !IsSibcall && !IsMustTail) {
3038 // Lower arguments at fp - stackoffset + fpdiff.
3039 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3041 FPDiff = NumBytesCallerPushed - NumBytes;
3043 // Set the delta of movement of the returnaddr stackslot.
3044 // But only set if delta is greater than previous delta.
3045 if (FPDiff < X86Info->getTCReturnAddrDelta())
3046 X86Info->setTCReturnAddrDelta(FPDiff);
3049 unsigned NumBytesToPush = NumBytes;
3050 unsigned NumBytesToPop = NumBytes;
3052 // If we have an inalloca argument, all stack space has already been allocated
3053 // for us and be right at the top of the stack. We don't support multiple
3054 // arguments passed in memory when using inalloca.
3055 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3057 if (!ArgLocs.back().isMemLoc())
3058 report_fatal_error("cannot use inalloca attribute on a register "
3060 if (ArgLocs.back().getLocMemOffset() != 0)
3061 report_fatal_error("any parameter with the inalloca attribute must be "
3062 "the only memory argument");
3066 Chain = DAG.getCALLSEQ_START(
3067 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3069 SDValue RetAddrFrIdx;
3070 // Load return address for tail calls.
3071 if (isTailCall && FPDiff)
3072 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3073 Is64Bit, FPDiff, dl);
3075 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3076 SmallVector<SDValue, 8> MemOpChains;
3079 // Walk the register/memloc assignments, inserting copies/loads. In the case
3080 // of tail call optimization arguments are handle later.
3081 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3082 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3083 // Skip inalloca arguments, they have already been written.
3084 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3085 if (Flags.isInAlloca())
3088 CCValAssign &VA = ArgLocs[i];
3089 EVT RegVT = VA.getLocVT();
3090 SDValue Arg = OutVals[i];
3091 bool isByVal = Flags.isByVal();
3093 // Promote the value if needed.
3094 switch (VA.getLocInfo()) {
3095 default: llvm_unreachable("Unknown loc info!");
3096 case CCValAssign::Full: break;
3097 case CCValAssign::SExt:
3098 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3100 case CCValAssign::ZExt:
3101 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3103 case CCValAssign::AExt:
3104 if (Arg.getValueType().isVector() &&
3105 Arg.getValueType().getScalarType() == MVT::i1)
3106 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3107 else if (RegVT.is128BitVector()) {
3108 // Special case: passing MMX values in XMM registers.
3109 Arg = DAG.getBitcast(MVT::i64, Arg);
3110 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3111 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3113 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3115 case CCValAssign::BCvt:
3116 Arg = DAG.getBitcast(RegVT, Arg);
3118 case CCValAssign::Indirect: {
3119 // Store the argument.
3120 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3121 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3122 Chain = DAG.getStore(
3123 Chain, dl, Arg, SpillSlot,
3124 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3131 if (VA.isRegLoc()) {
3132 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3133 if (isVarArg && IsWin64) {
3134 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3135 // shadow reg if callee is a varargs function.
3136 unsigned ShadowReg = 0;
3137 switch (VA.getLocReg()) {
3138 case X86::XMM0: ShadowReg = X86::RCX; break;
3139 case X86::XMM1: ShadowReg = X86::RDX; break;
3140 case X86::XMM2: ShadowReg = X86::R8; break;
3141 case X86::XMM3: ShadowReg = X86::R9; break;
3144 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3146 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3147 assert(VA.isMemLoc());
3148 if (!StackPtr.getNode())
3149 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3150 getPointerTy(DAG.getDataLayout()));
3151 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3152 dl, DAG, VA, Flags));
3156 if (!MemOpChains.empty())
3157 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3159 if (Subtarget->isPICStyleGOT()) {
3160 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3163 RegsToPass.push_back(std::make_pair(
3164 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3165 getPointerTy(DAG.getDataLayout()))));
3167 // If we are tail calling and generating PIC/GOT style code load the
3168 // address of the callee into ECX. The value in ecx is used as target of
3169 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3170 // for tail calls on PIC/GOT architectures. Normally we would just put the
3171 // address of GOT into ebx and then call target@PLT. But for tail calls
3172 // ebx would be restored (since ebx is callee saved) before jumping to the
3175 // Note: The actual moving to ECX is done further down.
3176 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3177 if (G && !G->getGlobal()->hasLocalLinkage() &&
3178 G->getGlobal()->hasDefaultVisibility())
3179 Callee = LowerGlobalAddress(Callee, DAG);
3180 else if (isa<ExternalSymbolSDNode>(Callee))
3181 Callee = LowerExternalSymbol(Callee, DAG);
3185 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3186 // From AMD64 ABI document:
3187 // For calls that may call functions that use varargs or stdargs
3188 // (prototype-less calls or calls to functions containing ellipsis (...) in
3189 // the declaration) %al is used as hidden argument to specify the number
3190 // of SSE registers used. The contents of %al do not need to match exactly
3191 // the number of registers, but must be an ubound on the number of SSE
3192 // registers used and is in the range 0 - 8 inclusive.
3194 // Count the number of XMM registers allocated.
3195 static const MCPhysReg XMMArgRegs[] = {
3196 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3197 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3199 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3200 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3201 && "SSE registers cannot be used when SSE is disabled");
3203 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3204 DAG.getConstant(NumXMMRegs, dl,
3208 if (isVarArg && IsMustTail) {
3209 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3210 for (const auto &F : Forwards) {
3211 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3212 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3216 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3217 // don't need this because the eligibility check rejects calls that require
3218 // shuffling arguments passed in memory.
3219 if (!IsSibcall && isTailCall) {
3220 // Force all the incoming stack arguments to be loaded from the stack
3221 // before any new outgoing arguments are stored to the stack, because the
3222 // outgoing stack slots may alias the incoming argument stack slots, and
3223 // the alias isn't otherwise explicit. This is slightly more conservative
3224 // than necessary, because it means that each store effectively depends
3225 // on every argument instead of just those arguments it would clobber.
3226 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3228 SmallVector<SDValue, 8> MemOpChains2;
3231 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3232 CCValAssign &VA = ArgLocs[i];
3235 assert(VA.isMemLoc());
3236 SDValue Arg = OutVals[i];
3237 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3238 // Skip inalloca arguments. They don't require any work.
3239 if (Flags.isInAlloca())
3241 // Create frame index.
3242 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3243 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3244 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3245 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3247 if (Flags.isByVal()) {
3248 // Copy relative to framepointer.
3249 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3250 if (!StackPtr.getNode())
3251 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3252 getPointerTy(DAG.getDataLayout()));
3253 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3256 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3260 // Store relative to framepointer.
3261 MemOpChains2.push_back(DAG.getStore(
3262 ArgChain, dl, Arg, FIN,
3263 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3268 if (!MemOpChains2.empty())
3269 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3271 // Store the return address to the appropriate stack slot.
3272 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3273 getPointerTy(DAG.getDataLayout()),
3274 RegInfo->getSlotSize(), FPDiff, dl);
3277 // Build a sequence of copy-to-reg nodes chained together with token chain
3278 // and flag operands which copy the outgoing args into registers.
3280 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3281 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3282 RegsToPass[i].second, InFlag);
3283 InFlag = Chain.getValue(1);
3286 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3287 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3288 // In the 64-bit large code model, we have to make all calls
3289 // through a register, since the call instruction's 32-bit
3290 // pc-relative offset may not be large enough to hold the whole
3292 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3293 // If the callee is a GlobalAddress node (quite common, every direct call
3294 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3296 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3298 // We should use extra load for direct calls to dllimported functions in
3300 const GlobalValue *GV = G->getGlobal();
3301 if (!GV->hasDLLImportStorageClass()) {
3302 unsigned char OpFlags = 0;
3303 bool ExtraLoad = false;
3304 unsigned WrapperKind = ISD::DELETED_NODE;
3306 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3307 // external symbols most go through the PLT in PIC mode. If the symbol
3308 // has hidden or protected visibility, or if it is static or local, then
3309 // we don't need to use the PLT - we can directly call it.
3310 if (Subtarget->isTargetELF() &&
3311 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3312 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3313 OpFlags = X86II::MO_PLT;
3314 } else if (Subtarget->isPICStyleStubAny() &&
3315 !GV->isStrongDefinitionForLinker() &&
3316 (!Subtarget->getTargetTriple().isMacOSX() ||
3317 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3318 // PC-relative references to external symbols should go through $stub,
3319 // unless we're building with the leopard linker or later, which
3320 // automatically synthesizes these stubs.
3321 OpFlags = X86II::MO_DARWIN_STUB;
3322 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3323 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3324 // If the function is marked as non-lazy, generate an indirect call
3325 // which loads from the GOT directly. This avoids runtime overhead
3326 // at the cost of eager binding (and one extra byte of encoding).
3327 OpFlags = X86II::MO_GOTPCREL;
3328 WrapperKind = X86ISD::WrapperRIP;
3332 Callee = DAG.getTargetGlobalAddress(
3333 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3335 // Add a wrapper if needed.
3336 if (WrapperKind != ISD::DELETED_NODE)
3337 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3338 getPointerTy(DAG.getDataLayout()), Callee);
3339 // Add extra indirection if needed.
3341 Callee = DAG.getLoad(
3342 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3343 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3346 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3347 unsigned char OpFlags = 0;
3349 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3350 // external symbols should go through the PLT.
3351 if (Subtarget->isTargetELF() &&
3352 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3353 OpFlags = X86II::MO_PLT;
3354 } else if (Subtarget->isPICStyleStubAny() &&
3355 (!Subtarget->getTargetTriple().isMacOSX() ||
3356 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3357 // PC-relative references to external symbols should go through $stub,
3358 // unless we're building with the leopard linker or later, which
3359 // automatically synthesizes these stubs.
3360 OpFlags = X86II::MO_DARWIN_STUB;
3363 Callee = DAG.getTargetExternalSymbol(
3364 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3365 } else if (Subtarget->isTarget64BitILP32() &&
3366 Callee->getValueType(0) == MVT::i32) {
3367 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3368 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3371 // Returns a chain & a flag for retval copy to use.
3372 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3373 SmallVector<SDValue, 8> Ops;
3375 if (!IsSibcall && isTailCall) {
3376 Chain = DAG.getCALLSEQ_END(Chain,
3377 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3378 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3379 InFlag = Chain.getValue(1);
3382 Ops.push_back(Chain);
3383 Ops.push_back(Callee);
3386 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3388 // Add argument registers to the end of the list so that they are known live
3390 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3391 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3392 RegsToPass[i].second.getValueType()));
3394 // Add a register mask operand representing the call-preserved registers.
3395 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3396 assert(Mask && "Missing call preserved mask for calling convention");
3398 // If this is an invoke in a 32-bit function using a funclet-based
3399 // personality, assume the function clobbers all registers. If an exception
3400 // is thrown, the runtime will not restore CSRs.
3401 // FIXME: Model this more precisely so that we can register allocate across
3402 // the normal edge and spill and fill across the exceptional edge.
3403 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3404 const Function *CallerFn = MF.getFunction();
3405 EHPersonality Pers =
3406 CallerFn->hasPersonalityFn()
3407 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3408 : EHPersonality::Unknown;
3409 if (isFuncletEHPersonality(Pers))
3410 Mask = RegInfo->getNoPreservedMask();
3413 Ops.push_back(DAG.getRegisterMask(Mask));
3415 if (InFlag.getNode())
3416 Ops.push_back(InFlag);
3420 //// If this is the first return lowered for this function, add the regs
3421 //// to the liveout set for the function.
3422 // This isn't right, although it's probably harmless on x86; liveouts
3423 // should be computed from returns not tail calls. Consider a void
3424 // function making a tail call to a function returning int.
3425 MF.getFrameInfo()->setHasTailCall();
3426 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3429 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3430 InFlag = Chain.getValue(1);
3432 // Create the CALLSEQ_END node.
3433 unsigned NumBytesForCalleeToPop;
3434 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3435 DAG.getTarget().Options.GuaranteedTailCallOpt))
3436 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3437 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3438 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3439 SR == StackStructReturn)
3440 // If this is a call to a struct-return function, the callee
3441 // pops the hidden struct pointer, so we have to push it back.
3442 // This is common for Darwin/X86, Linux & Mingw32 targets.
3443 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3444 NumBytesForCalleeToPop = 4;
3446 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3448 // Returns a flag for retval copy to use.
3450 Chain = DAG.getCALLSEQ_END(Chain,
3451 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3452 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3455 InFlag = Chain.getValue(1);
3458 // Handle result values, copying them out of physregs into vregs that we
3460 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3461 Ins, dl, DAG, InVals);
3464 //===----------------------------------------------------------------------===//
3465 // Fast Calling Convention (tail call) implementation
3466 //===----------------------------------------------------------------------===//
3468 // Like std call, callee cleans arguments, convention except that ECX is
3469 // reserved for storing the tail called function address. Only 2 registers are
3470 // free for argument passing (inreg). Tail call optimization is performed
3472 // * tailcallopt is enabled
3473 // * caller/callee are fastcc
3474 // On X86_64 architecture with GOT-style position independent code only local
3475 // (within module) calls are supported at the moment.
3476 // To keep the stack aligned according to platform abi the function
3477 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3478 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3479 // If a tail called function callee has more arguments than the caller the
3480 // caller needs to make sure that there is room to move the RETADDR to. This is
3481 // achieved by reserving an area the size of the argument delta right after the
3482 // original RETADDR, but before the saved framepointer or the spilled registers
3483 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3495 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3498 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3499 SelectionDAG& DAG) const {
3500 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3501 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3502 unsigned StackAlignment = TFI.getStackAlignment();
3503 uint64_t AlignMask = StackAlignment - 1;
3504 int64_t Offset = StackSize;
3505 unsigned SlotSize = RegInfo->getSlotSize();
3506 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3507 // Number smaller than 12 so just add the difference.
3508 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3510 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3511 Offset = ((~AlignMask) & Offset) + StackAlignment +
3512 (StackAlignment-SlotSize);
3517 /// Return true if the given stack call argument is already available in the
3518 /// same position (relatively) of the caller's incoming argument stack.
3520 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3521 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3522 const X86InstrInfo *TII) {
3523 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3525 if (Arg.getOpcode() == ISD::CopyFromReg) {
3526 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3527 if (!TargetRegisterInfo::isVirtualRegister(VR))
3529 MachineInstr *Def = MRI->getVRegDef(VR);
3532 if (!Flags.isByVal()) {
3533 if (!TII->isLoadFromStackSlot(Def, FI))
3536 unsigned Opcode = Def->getOpcode();
3537 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3538 Opcode == X86::LEA64_32r) &&
3539 Def->getOperand(1).isFI()) {
3540 FI = Def->getOperand(1).getIndex();
3541 Bytes = Flags.getByValSize();
3545 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3546 if (Flags.isByVal())
3547 // ByVal argument is passed in as a pointer but it's now being
3548 // dereferenced. e.g.
3549 // define @foo(%struct.X* %A) {
3550 // tail call @bar(%struct.X* byval %A)
3553 SDValue Ptr = Ld->getBasePtr();
3554 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3557 FI = FINode->getIndex();
3558 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3559 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3560 FI = FINode->getIndex();
3561 Bytes = Flags.getByValSize();
3565 assert(FI != INT_MAX);
3566 if (!MFI->isFixedObjectIndex(FI))
3568 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3571 /// Check whether the call is eligible for tail call optimization. Targets
3572 /// that want to do tail call optimization should implement this function.
3573 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3574 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3575 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3576 const SmallVectorImpl<ISD::OutputArg> &Outs,
3577 const SmallVectorImpl<SDValue> &OutVals,
3578 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3579 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3582 // If -tailcallopt is specified, make fastcc functions tail-callable.
3583 const MachineFunction &MF = DAG.getMachineFunction();
3584 const Function *CallerF = MF.getFunction();
3586 // If the function return type is x86_fp80 and the callee return type is not,
3587 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3588 // perform a tailcall optimization here.
3589 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3592 CallingConv::ID CallerCC = CallerF->getCallingConv();
3593 bool CCMatch = CallerCC == CalleeCC;
3594 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3595 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3597 // Win64 functions have extra shadow space for argument homing. Don't do the
3598 // sibcall if the caller and callee have mismatched expectations for this
3600 if (IsCalleeWin64 != IsCallerWin64)
3603 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3604 if (IsTailCallConvention(CalleeCC) && CCMatch)
3609 // Look for obvious safe cases to perform tail call optimization that do not
3610 // require ABI changes. This is what gcc calls sibcall.
3612 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3613 // emit a special epilogue.
3614 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3615 if (RegInfo->needsStackRealignment(MF))
3618 // Also avoid sibcall optimization if either caller or callee uses struct
3619 // return semantics.
3620 if (isCalleeStructRet || isCallerStructRet)
3623 // An stdcall/thiscall caller is expected to clean up its arguments; the
3624 // callee isn't going to do that.
3625 // FIXME: this is more restrictive than needed. We could produce a tailcall
3626 // when the stack adjustment matches. For example, with a thiscall that takes
3627 // only one argument.
3628 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3629 CallerCC == CallingConv::X86_ThisCall))
3632 // Do not sibcall optimize vararg calls unless all arguments are passed via
3634 if (isVarArg && !Outs.empty()) {
3636 // Optimizing for varargs on Win64 is unlikely to be safe without
3637 // additional testing.
3638 if (IsCalleeWin64 || IsCallerWin64)
3641 SmallVector<CCValAssign, 16> ArgLocs;
3642 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3645 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3646 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3647 if (!ArgLocs[i].isRegLoc())
3651 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3652 // stack. Therefore, if it's not used by the call it is not safe to optimize
3653 // this into a sibcall.
3654 bool Unused = false;
3655 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3662 SmallVector<CCValAssign, 16> RVLocs;
3663 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3665 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3666 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3667 CCValAssign &VA = RVLocs[i];
3668 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3673 // If the calling conventions do not match, then we'd better make sure the
3674 // results are returned in the same way as what the caller expects.
3676 SmallVector<CCValAssign, 16> RVLocs1;
3677 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3679 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3681 SmallVector<CCValAssign, 16> RVLocs2;
3682 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3684 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3686 if (RVLocs1.size() != RVLocs2.size())
3688 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3689 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3691 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3693 if (RVLocs1[i].isRegLoc()) {
3694 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3697 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3703 // If the callee takes no arguments then go on to check the results of the
3705 if (!Outs.empty()) {
3706 // Check if stack adjustment is needed. For now, do not do this if any
3707 // argument is passed on the stack.
3708 SmallVector<CCValAssign, 16> ArgLocs;
3709 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3712 // Allocate shadow area for Win64
3714 CCInfo.AllocateStack(32, 8);
3716 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3717 if (CCInfo.getNextStackOffset()) {
3718 MachineFunction &MF = DAG.getMachineFunction();
3719 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3722 // Check if the arguments are already laid out in the right way as
3723 // the caller's fixed stack objects.
3724 MachineFrameInfo *MFI = MF.getFrameInfo();
3725 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3726 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3727 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3728 CCValAssign &VA = ArgLocs[i];
3729 SDValue Arg = OutVals[i];
3730 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3731 if (VA.getLocInfo() == CCValAssign::Indirect)
3733 if (!VA.isRegLoc()) {
3734 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3741 // If the tailcall address may be in a register, then make sure it's
3742 // possible to register allocate for it. In 32-bit, the call address can
3743 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3744 // callee-saved registers are restored. These happen to be the same
3745 // registers used to pass 'inreg' arguments so watch out for those.
3746 if (!Subtarget->is64Bit() &&
3747 ((!isa<GlobalAddressSDNode>(Callee) &&
3748 !isa<ExternalSymbolSDNode>(Callee)) ||
3749 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3750 unsigned NumInRegs = 0;
3751 // In PIC we need an extra register to formulate the address computation
3753 unsigned MaxInRegs =
3754 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3756 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3757 CCValAssign &VA = ArgLocs[i];
3760 unsigned Reg = VA.getLocReg();
3763 case X86::EAX: case X86::EDX: case X86::ECX:
3764 if (++NumInRegs == MaxInRegs)
3776 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3777 const TargetLibraryInfo *libInfo) const {
3778 return X86::createFastISel(funcInfo, libInfo);
3781 //===----------------------------------------------------------------------===//
3782 // Other Lowering Hooks
3783 //===----------------------------------------------------------------------===//
3785 static bool MayFoldLoad(SDValue Op) {
3786 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3789 static bool MayFoldIntoStore(SDValue Op) {
3790 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3793 static bool isTargetShuffle(unsigned Opcode) {
3795 default: return false;
3796 case X86ISD::BLENDI:
3797 case X86ISD::PSHUFB:
3798 case X86ISD::PSHUFD:
3799 case X86ISD::PSHUFHW:
3800 case X86ISD::PSHUFLW:
3802 case X86ISD::PALIGNR:
3803 case X86ISD::MOVLHPS:
3804 case X86ISD::MOVLHPD:
3805 case X86ISD::MOVHLPS:
3806 case X86ISD::MOVLPS:
3807 case X86ISD::MOVLPD:
3808 case X86ISD::MOVSHDUP:
3809 case X86ISD::MOVSLDUP:
3810 case X86ISD::MOVDDUP:
3813 case X86ISD::UNPCKL:
3814 case X86ISD::UNPCKH:
3815 case X86ISD::VPERMILPI:
3816 case X86ISD::VPERM2X128:
3817 case X86ISD::VPERMI:
3818 case X86ISD::VPERMV:
3819 case X86ISD::VPERMV3:
3824 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3825 SDValue V1, unsigned TargetMask,
3826 SelectionDAG &DAG) {
3828 default: llvm_unreachable("Unknown x86 shuffle node");
3829 case X86ISD::PSHUFD:
3830 case X86ISD::PSHUFHW:
3831 case X86ISD::PSHUFLW:
3832 case X86ISD::VPERMILPI:
3833 case X86ISD::VPERMI:
3834 return DAG.getNode(Opc, dl, VT, V1,
3835 DAG.getConstant(TargetMask, dl, MVT::i8));
3839 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3840 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3842 default: llvm_unreachable("Unknown x86 shuffle node");
3843 case X86ISD::MOVLHPS:
3844 case X86ISD::MOVLHPD:
3845 case X86ISD::MOVHLPS:
3846 case X86ISD::MOVLPS:
3847 case X86ISD::MOVLPD:
3850 case X86ISD::UNPCKL:
3851 case X86ISD::UNPCKH:
3852 return DAG.getNode(Opc, dl, VT, V1, V2);
3856 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3857 MachineFunction &MF = DAG.getMachineFunction();
3858 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3859 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3860 int ReturnAddrIndex = FuncInfo->getRAIndex();
3862 if (ReturnAddrIndex == 0) {
3863 // Set up a frame object for the return address.
3864 unsigned SlotSize = RegInfo->getSlotSize();
3865 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3868 FuncInfo->setRAIndex(ReturnAddrIndex);
3871 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3874 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3875 bool hasSymbolicDisplacement) {
3876 // Offset should fit into 32 bit immediate field.
3877 if (!isInt<32>(Offset))
3880 // If we don't have a symbolic displacement - we don't have any extra
3882 if (!hasSymbolicDisplacement)
3885 // FIXME: Some tweaks might be needed for medium code model.
3886 if (M != CodeModel::Small && M != CodeModel::Kernel)
3889 // For small code model we assume that latest object is 16MB before end of 31
3890 // bits boundary. We may also accept pretty large negative constants knowing
3891 // that all objects are in the positive half of address space.
3892 if (M == CodeModel::Small && Offset < 16*1024*1024)
3895 // For kernel code model we know that all object resist in the negative half
3896 // of 32bits address space. We may not accept negative offsets, since they may
3897 // be just off and we may accept pretty large positive ones.
3898 if (M == CodeModel::Kernel && Offset >= 0)
3904 /// Determines whether the callee is required to pop its own arguments.
3905 /// Callee pop is necessary to support tail calls.
3906 bool X86::isCalleePop(CallingConv::ID CallingConv,
3907 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3909 if (IsTailCallConvention(CallingConv))
3910 return IsVarArg ? false : TailCallOpt;
3912 switch (CallingConv) {
3915 case CallingConv::X86_StdCall:
3916 case CallingConv::X86_FastCall:
3917 case CallingConv::X86_ThisCall:
3922 /// \brief Return true if the condition is an unsigned comparison operation.
3923 static bool isX86CCUnsigned(unsigned X86CC) {
3925 default: llvm_unreachable("Invalid integer condition!");
3926 case X86::COND_E: return true;
3927 case X86::COND_G: return false;
3928 case X86::COND_GE: return false;
3929 case X86::COND_L: return false;
3930 case X86::COND_LE: return false;
3931 case X86::COND_NE: return true;
3932 case X86::COND_B: return true;
3933 case X86::COND_A: return true;
3934 case X86::COND_BE: return true;
3935 case X86::COND_AE: return true;
3937 llvm_unreachable("covered switch fell through?!");
3940 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3941 /// condition code, returning the condition code and the LHS/RHS of the
3942 /// comparison to make.
3943 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3944 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3946 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3947 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3948 // X > -1 -> X == 0, jump !sign.
3949 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3950 return X86::COND_NS;
3952 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3953 // X < 0 -> X == 0, jump on sign.
3956 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3958 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3959 return X86::COND_LE;
3963 switch (SetCCOpcode) {
3964 default: llvm_unreachable("Invalid integer condition!");
3965 case ISD::SETEQ: return X86::COND_E;
3966 case ISD::SETGT: return X86::COND_G;
3967 case ISD::SETGE: return X86::COND_GE;
3968 case ISD::SETLT: return X86::COND_L;
3969 case ISD::SETLE: return X86::COND_LE;
3970 case ISD::SETNE: return X86::COND_NE;
3971 case ISD::SETULT: return X86::COND_B;
3972 case ISD::SETUGT: return X86::COND_A;
3973 case ISD::SETULE: return X86::COND_BE;
3974 case ISD::SETUGE: return X86::COND_AE;
3978 // First determine if it is required or is profitable to flip the operands.
3980 // If LHS is a foldable load, but RHS is not, flip the condition.
3981 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3982 !ISD::isNON_EXTLoad(RHS.getNode())) {
3983 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3984 std::swap(LHS, RHS);
3987 switch (SetCCOpcode) {
3993 std::swap(LHS, RHS);
3997 // On a floating point condition, the flags are set as follows:
3999 // 0 | 0 | 0 | X > Y
4000 // 0 | 0 | 1 | X < Y
4001 // 1 | 0 | 0 | X == Y
4002 // 1 | 1 | 1 | unordered
4003 switch (SetCCOpcode) {
4004 default: llvm_unreachable("Condcode should be pre-legalized away");
4006 case ISD::SETEQ: return X86::COND_E;
4007 case ISD::SETOLT: // flipped
4009 case ISD::SETGT: return X86::COND_A;
4010 case ISD::SETOLE: // flipped
4012 case ISD::SETGE: return X86::COND_AE;
4013 case ISD::SETUGT: // flipped
4015 case ISD::SETLT: return X86::COND_B;
4016 case ISD::SETUGE: // flipped
4018 case ISD::SETLE: return X86::COND_BE;
4020 case ISD::SETNE: return X86::COND_NE;
4021 case ISD::SETUO: return X86::COND_P;
4022 case ISD::SETO: return X86::COND_NP;
4024 case ISD::SETUNE: return X86::COND_INVALID;
4028 /// Is there a floating point cmov for the specific X86 condition code?
4029 /// Current x86 isa includes the following FP cmov instructions:
4030 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4031 static bool hasFPCMov(unsigned X86CC) {
4047 /// Returns true if the target can instruction select the
4048 /// specified FP immediate natively. If false, the legalizer will
4049 /// materialize the FP immediate as a load from a constant pool.
4050 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4051 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4052 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4058 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4059 ISD::LoadExtType ExtTy,
4061 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4062 // relocation target a movq or addq instruction: don't let the load shrink.
4063 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4064 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4065 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4066 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4070 /// \brief Returns true if it is beneficial to convert a load of a constant
4071 /// to just the constant itself.
4072 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4074 assert(Ty->isIntegerTy());
4076 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4077 if (BitSize == 0 || BitSize > 64)
4082 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4083 unsigned Index) const {
4084 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4087 return (Index == 0 || Index == ResVT.getVectorNumElements());
4090 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4091 // Speculate cttz only if we can directly use TZCNT.
4092 return Subtarget->hasBMI();
4095 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4096 // Speculate ctlz only if we can directly use LZCNT.
4097 return Subtarget->hasLZCNT();
4100 /// Return true if every element in Mask, beginning
4101 /// from position Pos and ending in Pos+Size is undef.
4102 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4103 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4109 /// Return true if Val is undef or if its value falls within the
4110 /// specified range (L, H].
4111 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4112 return (Val < 0) || (Val >= Low && Val < Hi);
4115 /// Val is either less than zero (undef) or equal to the specified value.
4116 static bool isUndefOrEqual(int Val, int CmpVal) {
4117 return (Val < 0 || Val == CmpVal);
4120 /// Return true if every element in Mask, beginning
4121 /// from position Pos and ending in Pos+Size, falls within the specified
4122 /// sequential range (Low, Low+Size]. or is undef.
4123 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4124 unsigned Pos, unsigned Size, int Low) {
4125 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4126 if (!isUndefOrEqual(Mask[i], Low))
4131 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4132 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4133 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4134 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4135 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4138 // The index should be aligned on a vecWidth-bit boundary.
4140 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4142 MVT VT = N->getSimpleValueType(0);
4143 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4144 bool Result = (Index * ElSize) % vecWidth == 0;
4149 /// Return true if the specified INSERT_SUBVECTOR
4150 /// operand specifies a subvector insert that is suitable for input to
4151 /// insertion of 128 or 256-bit subvectors
4152 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4153 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4154 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4156 // The index should be aligned on a vecWidth-bit boundary.
4158 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4160 MVT VT = N->getSimpleValueType(0);
4161 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4162 bool Result = (Index * ElSize) % vecWidth == 0;
4167 bool X86::isVINSERT128Index(SDNode *N) {
4168 return isVINSERTIndex(N, 128);
4171 bool X86::isVINSERT256Index(SDNode *N) {
4172 return isVINSERTIndex(N, 256);
4175 bool X86::isVEXTRACT128Index(SDNode *N) {
4176 return isVEXTRACTIndex(N, 128);
4179 bool X86::isVEXTRACT256Index(SDNode *N) {
4180 return isVEXTRACTIndex(N, 256);
4183 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4184 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4185 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4186 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4189 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4191 MVT VecVT = N->getOperand(0).getSimpleValueType();
4192 MVT ElVT = VecVT.getVectorElementType();
4194 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4195 return Index / NumElemsPerChunk;
4198 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4199 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4200 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4201 llvm_unreachable("Illegal insert subvector for VINSERT");
4204 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4206 MVT VecVT = N->getSimpleValueType(0);
4207 MVT ElVT = VecVT.getVectorElementType();
4209 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4210 return Index / NumElemsPerChunk;
4213 /// Return the appropriate immediate to extract the specified
4214 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4215 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4216 return getExtractVEXTRACTImmediate(N, 128);
4219 /// Return the appropriate immediate to extract the specified
4220 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4221 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4222 return getExtractVEXTRACTImmediate(N, 256);
4225 /// Return the appropriate immediate to insert at the specified
4226 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4227 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4228 return getInsertVINSERTImmediate(N, 128);
4231 /// Return the appropriate immediate to insert at the specified
4232 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4233 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4234 return getInsertVINSERTImmediate(N, 256);
4237 /// Returns true if V is a constant integer zero.
4238 static bool isZero(SDValue V) {
4239 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4240 return C && C->isNullValue();
4243 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4244 bool X86::isZeroNode(SDValue Elt) {
4247 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4248 return CFP->getValueAPF().isPosZero();
4252 // Build a vector of constants
4253 // Use an UNDEF node if MaskElt == -1.
4254 // Spilt 64-bit constants in the 32-bit mode.
4255 static SDValue getConstVector(ArrayRef<int> Values, EVT VT,
4257 SDLoc dl, bool IsMask = false) {
4259 SmallVector<SDValue, 32> Ops;
4262 EVT ConstVecVT = VT;
4263 unsigned NumElts = VT.getVectorNumElements();
4264 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4265 if (!In64BitMode && VT.getScalarType() == MVT::i64) {
4266 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4270 EVT EltVT = ConstVecVT.getScalarType();
4271 for (unsigned i = 0; i < NumElts; ++i) {
4272 bool IsUndef = Values[i] < 0 && IsMask;
4273 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4274 DAG.getConstant(Values[i], dl, EltVT);
4275 Ops.push_back(OpNode);
4277 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4278 DAG.getConstant(0, dl, EltVT));
4280 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4282 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4286 /// Returns a vector of specified type with all zero elements.
4287 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4288 SelectionDAG &DAG, SDLoc dl) {
4289 assert(VT.isVector() && "Expected a vector type");
4291 // Always build SSE zero vectors as <4 x i32> bitcasted
4292 // to their dest type. This ensures they get CSE'd.
4294 if (VT.is128BitVector()) { // SSE
4295 if (Subtarget->hasSSE2()) { // SSE2
4296 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4297 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4299 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4300 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4302 } else if (VT.is256BitVector()) { // AVX
4303 if (Subtarget->hasInt256()) { // AVX2
4304 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4305 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4306 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4308 // 256-bit logic and arithmetic instructions in AVX are all
4309 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4310 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4311 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4312 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4314 } else if (VT.is512BitVector()) { // AVX-512
4315 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4316 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4317 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4318 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4319 } else if (VT.getScalarType() == MVT::i1) {
4321 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4322 && "Unexpected vector type");
4323 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4324 && "Unexpected vector type");
4325 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4326 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4327 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4329 llvm_unreachable("Unexpected vector type");
4331 return DAG.getBitcast(VT, Vec);
4334 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4335 SelectionDAG &DAG, SDLoc dl,
4336 unsigned vectorWidth) {
4337 assert((vectorWidth == 128 || vectorWidth == 256) &&
4338 "Unsupported vector width");
4339 EVT VT = Vec.getValueType();
4340 EVT ElVT = VT.getVectorElementType();
4341 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4342 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4343 VT.getVectorNumElements()/Factor);
4345 // Extract from UNDEF is UNDEF.
4346 if (Vec.getOpcode() == ISD::UNDEF)
4347 return DAG.getUNDEF(ResultVT);
4349 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4350 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4352 // This is the index of the first element of the vectorWidth-bit chunk
4354 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4357 // If the input is a buildvector just emit a smaller one.
4358 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4359 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4360 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4363 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4364 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4367 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4368 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4369 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4370 /// instructions or a simple subregister reference. Idx is an index in the
4371 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4372 /// lowering EXTRACT_VECTOR_ELT operations easier.
4373 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4374 SelectionDAG &DAG, SDLoc dl) {
4375 assert((Vec.getValueType().is256BitVector() ||
4376 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4377 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4380 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4381 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4382 SelectionDAG &DAG, SDLoc dl) {
4383 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4384 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4387 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4388 unsigned IdxVal, SelectionDAG &DAG,
4389 SDLoc dl, unsigned vectorWidth) {
4390 assert((vectorWidth == 128 || vectorWidth == 256) &&
4391 "Unsupported vector width");
4392 // Inserting UNDEF is Result
4393 if (Vec.getOpcode() == ISD::UNDEF)
4395 EVT VT = Vec.getValueType();
4396 EVT ElVT = VT.getVectorElementType();
4397 EVT ResultVT = Result.getValueType();
4399 // Insert the relevant vectorWidth bits.
4400 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4402 // This is the index of the first element of the vectorWidth-bit chunk
4404 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4407 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4408 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4411 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4412 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4413 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4414 /// simple superregister reference. Idx is an index in the 128 bits
4415 /// we want. It need not be aligned to a 128-bit boundary. That makes
4416 /// lowering INSERT_VECTOR_ELT operations easier.
4417 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4418 SelectionDAG &DAG, SDLoc dl) {
4419 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4421 // For insertion into the zero index (low half) of a 256-bit vector, it is
4422 // more efficient to generate a blend with immediate instead of an insert*128.
4423 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4424 // extend the subvector to the size of the result vector. Make sure that
4425 // we are not recursing on that node by checking for undef here.
4426 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4427 Result.getOpcode() != ISD::UNDEF) {
4428 EVT ResultVT = Result.getValueType();
4429 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4430 SDValue Undef = DAG.getUNDEF(ResultVT);
4431 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4434 // The blend instruction, and therefore its mask, depend on the data type.
4435 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4436 if (ScalarType.isFloatingPoint()) {
4437 // Choose either vblendps (float) or vblendpd (double).
4438 unsigned ScalarSize = ScalarType.getSizeInBits();
4439 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4440 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4441 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4442 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4445 const X86Subtarget &Subtarget =
4446 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4448 // AVX2 is needed for 256-bit integer blend support.
4449 // Integers must be cast to 32-bit because there is only vpblendd;
4450 // vpblendw can't be used for this because it has a handicapped mask.
4452 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4453 // is still more efficient than using the wrong domain vinsertf128 that
4454 // will be created by InsertSubVector().
4455 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4457 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4458 Vec256 = DAG.getBitcast(CastVT, Vec256);
4459 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4460 return DAG.getBitcast(ResultVT, Vec256);
4463 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4466 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4467 SelectionDAG &DAG, SDLoc dl) {
4468 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4469 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4472 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4473 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4474 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4475 /// large BUILD_VECTORS.
4476 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4477 unsigned NumElems, SelectionDAG &DAG,
4479 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4480 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4483 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4484 unsigned NumElems, SelectionDAG &DAG,
4486 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4487 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4490 /// Returns a vector of specified type with all bits set.
4491 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4492 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4493 /// Then bitcast to their original type, ensuring they get CSE'd.
4494 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4495 SelectionDAG &DAG, SDLoc dl) {
4496 assert(VT.isVector() && "Expected a vector type");
4498 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4500 if (VT.is512BitVector()) {
4501 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4502 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4503 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4504 } else if (VT.is256BitVector()) {
4505 if (Subtarget->hasInt256()) { // AVX2
4506 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4507 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4509 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4510 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4512 } else if (VT.is128BitVector()) {
4513 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4515 llvm_unreachable("Unexpected vector type");
4517 return DAG.getBitcast(VT, Vec);
4520 /// Returns a vector_shuffle node for an unpackl operation.
4521 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4523 unsigned NumElems = VT.getVectorNumElements();
4524 SmallVector<int, 8> Mask;
4525 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4527 Mask.push_back(i + NumElems);
4529 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4532 /// Returns a vector_shuffle node for an unpackh operation.
4533 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4535 unsigned NumElems = VT.getVectorNumElements();
4536 SmallVector<int, 8> Mask;
4537 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4538 Mask.push_back(i + Half);
4539 Mask.push_back(i + NumElems + Half);
4541 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4544 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4545 /// This produces a shuffle where the low element of V2 is swizzled into the
4546 /// zero/undef vector, landing at element Idx.
4547 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4548 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4550 const X86Subtarget *Subtarget,
4551 SelectionDAG &DAG) {
4552 MVT VT = V2.getSimpleValueType();
4554 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4555 unsigned NumElems = VT.getVectorNumElements();
4556 SmallVector<int, 16> MaskVec;
4557 for (unsigned i = 0; i != NumElems; ++i)
4558 // If this is the insertion idx, put the low elt of V2 here.
4559 MaskVec.push_back(i == Idx ? NumElems : i);
4560 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4563 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4564 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4565 /// uses one source. Note that this will set IsUnary for shuffles which use a
4566 /// single input multiple times, and in those cases it will
4567 /// adjust the mask to only have indices within that single input.
4568 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4569 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4570 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4571 unsigned NumElems = VT.getVectorNumElements();
4575 bool IsFakeUnary = false;
4576 switch(N->getOpcode()) {
4577 case X86ISD::BLENDI:
4578 ImmN = N->getOperand(N->getNumOperands()-1);
4579 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4582 ImmN = N->getOperand(N->getNumOperands()-1);
4583 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4584 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4586 case X86ISD::UNPCKH:
4587 DecodeUNPCKHMask(VT, Mask);
4588 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4590 case X86ISD::UNPCKL:
4591 DecodeUNPCKLMask(VT, Mask);
4592 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4594 case X86ISD::MOVHLPS:
4595 DecodeMOVHLPSMask(NumElems, Mask);
4596 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4598 case X86ISD::MOVLHPS:
4599 DecodeMOVLHPSMask(NumElems, Mask);
4600 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4602 case X86ISD::PALIGNR:
4603 ImmN = N->getOperand(N->getNumOperands()-1);
4604 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606 case X86ISD::PSHUFD:
4607 case X86ISD::VPERMILPI:
4608 ImmN = N->getOperand(N->getNumOperands()-1);
4609 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4612 case X86ISD::PSHUFHW:
4613 ImmN = N->getOperand(N->getNumOperands()-1);
4614 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617 case X86ISD::PSHUFLW:
4618 ImmN = N->getOperand(N->getNumOperands()-1);
4619 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4622 case X86ISD::PSHUFB: {
4624 SDValue MaskNode = N->getOperand(1);
4625 while (MaskNode->getOpcode() == ISD::BITCAST)
4626 MaskNode = MaskNode->getOperand(0);
4628 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4629 // If we have a build-vector, then things are easy.
4630 EVT VT = MaskNode.getValueType();
4631 assert(VT.isVector() &&
4632 "Can't produce a non-vector with a build_vector!");
4633 if (!VT.isInteger())
4636 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4638 SmallVector<uint64_t, 32> RawMask;
4639 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4640 SDValue Op = MaskNode->getOperand(i);
4641 if (Op->getOpcode() == ISD::UNDEF) {
4642 RawMask.push_back((uint64_t)SM_SentinelUndef);
4645 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4648 APInt MaskElement = CN->getAPIntValue();
4650 // We now have to decode the element which could be any integer size and
4651 // extract each byte of it.
4652 for (int j = 0; j < NumBytesPerElement; ++j) {
4653 // Note that this is x86 and so always little endian: the low byte is
4654 // the first byte of the mask.
4655 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4656 MaskElement = MaskElement.lshr(8);
4659 DecodePSHUFBMask(RawMask, Mask);
4663 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4667 SDValue Ptr = MaskLoad->getBasePtr();
4668 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4669 Ptr->getOpcode() == X86ISD::WrapperRIP)
4670 Ptr = Ptr->getOperand(0);
4672 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4673 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4676 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4677 DecodePSHUFBMask(C, Mask);
4685 case X86ISD::VPERMI:
4686 ImmN = N->getOperand(N->getNumOperands()-1);
4687 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4692 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4694 case X86ISD::VPERM2X128:
4695 ImmN = N->getOperand(N->getNumOperands()-1);
4696 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4697 if (Mask.empty()) return false;
4698 // Mask only contains negative index if an element is zero.
4699 if (std::any_of(Mask.begin(), Mask.end(),
4700 [](int M){ return M == SM_SentinelZero; }))
4703 case X86ISD::MOVSLDUP:
4704 DecodeMOVSLDUPMask(VT, Mask);
4707 case X86ISD::MOVSHDUP:
4708 DecodeMOVSHDUPMask(VT, Mask);
4711 case X86ISD::MOVDDUP:
4712 DecodeMOVDDUPMask(VT, Mask);
4715 case X86ISD::MOVLHPD:
4716 case X86ISD::MOVLPD:
4717 case X86ISD::MOVLPS:
4718 // Not yet implemented
4720 case X86ISD::VPERMV: {
4722 SDValue MaskNode = N->getOperand(0);
4723 while (MaskNode->getOpcode() == ISD::BITCAST)
4724 MaskNode = MaskNode->getOperand(0);
4726 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4727 SmallVector<uint64_t, 32> RawMask;
4728 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4729 // If we have a build-vector, then things are easy.
4730 assert(MaskNode.getValueType().isInteger() &&
4731 MaskNode.getValueType().getVectorNumElements() ==
4732 VT.getVectorNumElements());
4734 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4735 SDValue Op = MaskNode->getOperand(i);
4736 if (Op->getOpcode() == ISD::UNDEF)
4737 RawMask.push_back((uint64_t)SM_SentinelUndef);
4738 else if (isa<ConstantSDNode>(Op)) {
4739 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4740 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4744 DecodeVPERMVMask(RawMask, Mask);
4747 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4748 unsigned NumEltsInMask = MaskNode->getNumOperands();
4749 MaskNode = MaskNode->getOperand(0);
4750 auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4752 APInt MaskEltValue = CN->getAPIntValue();
4753 for (unsigned i = 0; i < NumEltsInMask; ++i)
4754 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4755 DecodeVPERMVMask(RawMask, Mask);
4758 // It may be a scalar load
4761 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4765 SDValue Ptr = MaskLoad->getBasePtr();
4766 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4767 Ptr->getOpcode() == X86ISD::WrapperRIP)
4768 Ptr = Ptr->getOperand(0);
4770 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4771 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4774 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4776 DecodeVPERMVMask(C, VT, Mask);
4783 case X86ISD::VPERMV3: {
4785 SDValue MaskNode = N->getOperand(1);
4786 while (MaskNode->getOpcode() == ISD::BITCAST)
4787 MaskNode = MaskNode->getOperand(1);
4789 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4790 // If we have a build-vector, then things are easy.
4791 assert(MaskNode.getValueType().isInteger() &&
4792 MaskNode.getValueType().getVectorNumElements() ==
4793 VT.getVectorNumElements());
4795 SmallVector<uint64_t, 32> RawMask;
4796 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4798 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4799 SDValue Op = MaskNode->getOperand(i);
4800 if (Op->getOpcode() == ISD::UNDEF)
4801 RawMask.push_back((uint64_t)SM_SentinelUndef);
4803 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4806 APInt MaskElement = CN->getAPIntValue();
4807 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4810 DecodeVPERMV3Mask(RawMask, Mask);
4814 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4818 SDValue Ptr = MaskLoad->getBasePtr();
4819 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4820 Ptr->getOpcode() == X86ISD::WrapperRIP)
4821 Ptr = Ptr->getOperand(0);
4823 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4824 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4827 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4829 DecodeVPERMV3Mask(C, VT, Mask);
4836 default: llvm_unreachable("unknown target shuffle node");
4839 // If we have a fake unary shuffle, the shuffle mask is spread across two
4840 // inputs that are actually the same node. Re-map the mask to always point
4841 // into the first input.
4844 if (M >= (int)Mask.size())
4850 /// Returns the scalar element that will make up the ith
4851 /// element of the result of the vector shuffle.
4852 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4855 return SDValue(); // Limit search depth.
4857 SDValue V = SDValue(N, 0);
4858 EVT VT = V.getValueType();
4859 unsigned Opcode = V.getOpcode();
4861 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4862 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4863 int Elt = SV->getMaskElt(Index);
4866 return DAG.getUNDEF(VT.getVectorElementType());
4868 unsigned NumElems = VT.getVectorNumElements();
4869 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4870 : SV->getOperand(1);
4871 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4874 // Recurse into target specific vector shuffles to find scalars.
4875 if (isTargetShuffle(Opcode)) {
4876 MVT ShufVT = V.getSimpleValueType();
4877 unsigned NumElems = ShufVT.getVectorNumElements();
4878 SmallVector<int, 16> ShuffleMask;
4881 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4884 int Elt = ShuffleMask[Index];
4886 return DAG.getUNDEF(ShufVT.getVectorElementType());
4888 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4890 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4894 // Actual nodes that may contain scalar elements
4895 if (Opcode == ISD::BITCAST) {
4896 V = V.getOperand(0);
4897 EVT SrcVT = V.getValueType();
4898 unsigned NumElems = VT.getVectorNumElements();
4900 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4904 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4905 return (Index == 0) ? V.getOperand(0)
4906 : DAG.getUNDEF(VT.getVectorElementType());
4908 if (V.getOpcode() == ISD::BUILD_VECTOR)
4909 return V.getOperand(Index);
4914 /// Custom lower build_vector of v16i8.
4915 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4916 unsigned NumNonZero, unsigned NumZero,
4918 const X86Subtarget* Subtarget,
4919 const TargetLowering &TLI) {
4927 // SSE4.1 - use PINSRB to insert each byte directly.
4928 if (Subtarget->hasSSE41()) {
4929 for (unsigned i = 0; i < 16; ++i) {
4930 bool isNonZero = (NonZeros & (1 << i)) != 0;
4934 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4936 V = DAG.getUNDEF(MVT::v16i8);
4939 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4940 MVT::v16i8, V, Op.getOperand(i),
4941 DAG.getIntPtrConstant(i, dl));
4948 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4949 for (unsigned i = 0; i < 16; ++i) {
4950 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4951 if (ThisIsNonZero && First) {
4953 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4955 V = DAG.getUNDEF(MVT::v8i16);
4960 SDValue ThisElt, LastElt;
4961 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4962 if (LastIsNonZero) {
4963 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4964 MVT::i16, Op.getOperand(i-1));
4966 if (ThisIsNonZero) {
4967 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4968 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4969 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4971 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4975 if (ThisElt.getNode())
4976 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4977 DAG.getIntPtrConstant(i/2, dl));
4981 return DAG.getBitcast(MVT::v16i8, V);
4984 /// Custom lower build_vector of v8i16.
4985 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4986 unsigned NumNonZero, unsigned NumZero,
4988 const X86Subtarget* Subtarget,
4989 const TargetLowering &TLI) {
4996 for (unsigned i = 0; i < 8; ++i) {
4997 bool isNonZero = (NonZeros & (1 << i)) != 0;
5001 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5003 V = DAG.getUNDEF(MVT::v8i16);
5006 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5007 MVT::v8i16, V, Op.getOperand(i),
5008 DAG.getIntPtrConstant(i, dl));
5015 /// Custom lower build_vector of v4i32 or v4f32.
5016 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5017 const X86Subtarget *Subtarget,
5018 const TargetLowering &TLI) {
5019 // Find all zeroable elements.
5020 std::bitset<4> Zeroable;
5021 for (int i=0; i < 4; ++i) {
5022 SDValue Elt = Op->getOperand(i);
5023 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5025 assert(Zeroable.size() - Zeroable.count() > 1 &&
5026 "We expect at least two non-zero elements!");
5028 // We only know how to deal with build_vector nodes where elements are either
5029 // zeroable or extract_vector_elt with constant index.
5030 SDValue FirstNonZero;
5031 unsigned FirstNonZeroIdx;
5032 for (unsigned i=0; i < 4; ++i) {
5035 SDValue Elt = Op->getOperand(i);
5036 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5037 !isa<ConstantSDNode>(Elt.getOperand(1)))
5039 // Make sure that this node is extracting from a 128-bit vector.
5040 MVT VT = Elt.getOperand(0).getSimpleValueType();
5041 if (!VT.is128BitVector())
5043 if (!FirstNonZero.getNode()) {
5045 FirstNonZeroIdx = i;
5049 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5050 SDValue V1 = FirstNonZero.getOperand(0);
5051 MVT VT = V1.getSimpleValueType();
5053 // See if this build_vector can be lowered as a blend with zero.
5055 unsigned EltMaskIdx, EltIdx;
5057 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5058 if (Zeroable[EltIdx]) {
5059 // The zero vector will be on the right hand side.
5060 Mask[EltIdx] = EltIdx+4;
5064 Elt = Op->getOperand(EltIdx);
5065 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5066 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5067 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5069 Mask[EltIdx] = EltIdx;
5073 // Let the shuffle legalizer deal with blend operations.
5074 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5075 if (V1.getSimpleValueType() != VT)
5076 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5077 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5080 // See if we can lower this build_vector to a INSERTPS.
5081 if (!Subtarget->hasSSE41())
5084 SDValue V2 = Elt.getOperand(0);
5085 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5088 bool CanFold = true;
5089 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5093 SDValue Current = Op->getOperand(i);
5094 SDValue SrcVector = Current->getOperand(0);
5097 CanFold = SrcVector == V1 &&
5098 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5104 assert(V1.getNode() && "Expected at least two non-zero elements!");
5105 if (V1.getSimpleValueType() != MVT::v4f32)
5106 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5107 if (V2.getSimpleValueType() != MVT::v4f32)
5108 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5110 // Ok, we can emit an INSERTPS instruction.
5111 unsigned ZMask = Zeroable.to_ulong();
5113 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5114 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5116 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5117 DAG.getIntPtrConstant(InsertPSMask, DL));
5118 return DAG.getBitcast(VT, Result);
5121 /// Return a vector logical shift node.
5122 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5123 unsigned NumBits, SelectionDAG &DAG,
5124 const TargetLowering &TLI, SDLoc dl) {
5125 assert(VT.is128BitVector() && "Unknown type for VShift");
5126 MVT ShVT = MVT::v2i64;
5127 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5128 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5129 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5130 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5131 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5132 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5136 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5138 // Check if the scalar load can be widened into a vector load. And if
5139 // the address is "base + cst" see if the cst can be "absorbed" into
5140 // the shuffle mask.
5141 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5142 SDValue Ptr = LD->getBasePtr();
5143 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5145 EVT PVT = LD->getValueType(0);
5146 if (PVT != MVT::i32 && PVT != MVT::f32)
5151 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5152 FI = FINode->getIndex();
5154 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5155 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5156 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5157 Offset = Ptr.getConstantOperandVal(1);
5158 Ptr = Ptr.getOperand(0);
5163 // FIXME: 256-bit vector instructions don't require a strict alignment,
5164 // improve this code to support it better.
5165 unsigned RequiredAlign = VT.getSizeInBits()/8;
5166 SDValue Chain = LD->getChain();
5167 // Make sure the stack object alignment is at least 16 or 32.
5168 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5169 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5170 if (MFI->isFixedObjectIndex(FI)) {
5171 // Can't change the alignment. FIXME: It's possible to compute
5172 // the exact stack offset and reference FI + adjust offset instead.
5173 // If someone *really* cares about this. That's the way to implement it.
5176 MFI->setObjectAlignment(FI, RequiredAlign);
5180 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5181 // Ptr + (Offset & ~15).
5184 if ((Offset % RequiredAlign) & 3)
5186 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5189 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5190 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5193 int EltNo = (Offset - StartOffset) >> 2;
5194 unsigned NumElems = VT.getVectorNumElements();
5196 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5197 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5198 LD->getPointerInfo().getWithOffset(StartOffset),
5199 false, false, false, 0);
5201 SmallVector<int, 8> Mask(NumElems, EltNo);
5203 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5209 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5210 /// elements can be replaced by a single large load which has the same value as
5211 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5213 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5215 /// FIXME: we'd also like to handle the case where the last elements are zero
5216 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5217 /// There's even a handy isZeroNode for that purpose.
5218 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5219 SDLoc &DL, SelectionDAG &DAG,
5220 bool isAfterLegalize) {
5221 unsigned NumElems = Elts.size();
5223 LoadSDNode *LDBase = nullptr;
5224 unsigned LastLoadedElt = -1U;
5226 // For each element in the initializer, see if we've found a load or an undef.
5227 // If we don't find an initial load element, or later load elements are
5228 // non-consecutive, bail out.
5229 for (unsigned i = 0; i < NumElems; ++i) {
5230 SDValue Elt = Elts[i];
5231 // Look through a bitcast.
5232 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5233 Elt = Elt.getOperand(0);
5234 if (!Elt.getNode() ||
5235 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5238 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5240 LDBase = cast<LoadSDNode>(Elt.getNode());
5244 if (Elt.getOpcode() == ISD::UNDEF)
5247 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5248 EVT LdVT = Elt.getValueType();
5249 // Each loaded element must be the correct fractional portion of the
5250 // requested vector load.
5251 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5253 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5258 // If we have found an entire vector of loads and undefs, then return a large
5259 // load of the entire vector width starting at the base pointer. If we found
5260 // consecutive loads for the low half, generate a vzext_load node.
5261 if (LastLoadedElt == NumElems - 1) {
5262 assert(LDBase && "Did not find base load for merging consecutive loads");
5263 EVT EltVT = LDBase->getValueType(0);
5264 // Ensure that the input vector size for the merged loads matches the
5265 // cumulative size of the input elements.
5266 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5269 if (isAfterLegalize &&
5270 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5273 SDValue NewLd = SDValue();
5275 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5276 LDBase->getPointerInfo(), LDBase->isVolatile(),
5277 LDBase->isNonTemporal(), LDBase->isInvariant(),
5278 LDBase->getAlignment());
5280 if (LDBase->hasAnyUseOfValue(1)) {
5281 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5283 SDValue(NewLd.getNode(), 1));
5284 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5285 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5286 SDValue(NewLd.getNode(), 1));
5292 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5293 //of a v4i32 / v4f32. It's probably worth generalizing.
5294 EVT EltVT = VT.getVectorElementType();
5295 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5296 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5297 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5298 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5300 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5301 LDBase->getPointerInfo(),
5302 LDBase->getAlignment(),
5303 false/*isVolatile*/, true/*ReadMem*/,
5306 // Make sure the newly-created LOAD is in the same position as LDBase in
5307 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5308 // update uses of LDBase's output chain to use the TokenFactor.
5309 if (LDBase->hasAnyUseOfValue(1)) {
5310 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5311 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5312 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5313 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5314 SDValue(ResNode.getNode(), 1));
5317 return DAG.getBitcast(VT, ResNode);
5322 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5323 /// to generate a splat value for the following cases:
5324 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5325 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5326 /// a scalar load, or a constant.
5327 /// The VBROADCAST node is returned when a pattern is found,
5328 /// or SDValue() otherwise.
5329 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5330 SelectionDAG &DAG) {
5331 // VBROADCAST requires AVX.
5332 // TODO: Splats could be generated for non-AVX CPUs using SSE
5333 // instructions, but there's less potential gain for only 128-bit vectors.
5334 if (!Subtarget->hasAVX())
5337 MVT VT = Op.getSimpleValueType();
5340 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5341 "Unsupported vector type for broadcast.");
5346 switch (Op.getOpcode()) {
5348 // Unknown pattern found.
5351 case ISD::BUILD_VECTOR: {
5352 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5353 BitVector UndefElements;
5354 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5356 // We need a splat of a single value to use broadcast, and it doesn't
5357 // make any sense if the value is only in one element of the vector.
5358 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5362 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5363 Ld.getOpcode() == ISD::ConstantFP);
5365 // Make sure that all of the users of a non-constant load are from the
5366 // BUILD_VECTOR node.
5367 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5372 case ISD::VECTOR_SHUFFLE: {
5373 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5375 // Shuffles must have a splat mask where the first element is
5377 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5380 SDValue Sc = Op.getOperand(0);
5381 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5382 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5384 if (!Subtarget->hasInt256())
5387 // Use the register form of the broadcast instruction available on AVX2.
5388 if (VT.getSizeInBits() >= 256)
5389 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5390 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5393 Ld = Sc.getOperand(0);
5394 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5395 Ld.getOpcode() == ISD::ConstantFP);
5397 // The scalar_to_vector node and the suspected
5398 // load node must have exactly one user.
5399 // Constants may have multiple users.
5401 // AVX-512 has register version of the broadcast
5402 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5403 Ld.getValueType().getSizeInBits() >= 32;
5404 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5411 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5412 bool IsGE256 = (VT.getSizeInBits() >= 256);
5414 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5415 // instruction to save 8 or more bytes of constant pool data.
5416 // TODO: If multiple splats are generated to load the same constant,
5417 // it may be detrimental to overall size. There needs to be a way to detect
5418 // that condition to know if this is truly a size win.
5419 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5421 // Handle broadcasting a single constant scalar from the constant pool
5423 // On Sandybridge (no AVX2), it is still better to load a constant vector
5424 // from the constant pool and not to broadcast it from a scalar.
5425 // But override that restriction when optimizing for size.
5426 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5427 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5428 EVT CVT = Ld.getValueType();
5429 assert(!CVT.isVector() && "Must not broadcast a vector type");
5431 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5432 // For size optimization, also splat v2f64 and v2i64, and for size opt
5433 // with AVX2, also splat i8 and i16.
5434 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5435 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5436 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5437 const Constant *C = nullptr;
5438 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5439 C = CI->getConstantIntValue();
5440 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5441 C = CF->getConstantFPValue();
5443 assert(C && "Invalid constant type");
5445 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5447 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5448 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5450 CVT, dl, DAG.getEntryNode(), CP,
5451 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5452 false, false, Alignment);
5454 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5458 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5460 // Handle AVX2 in-register broadcasts.
5461 if (!IsLoad && Subtarget->hasInt256() &&
5462 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5463 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5465 // The scalar source must be a normal load.
5469 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5470 (Subtarget->hasVLX() && ScalarSize == 64))
5471 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5473 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5474 // double since there is no vbroadcastsd xmm
5475 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5476 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5477 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5480 // Unsupported broadcast.
5484 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5485 /// underlying vector and index.
5487 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5489 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5491 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5492 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5495 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5497 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5499 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5500 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5503 // In this case the vector is the extract_subvector expression and the index
5504 // is 2, as specified by the shuffle.
5505 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5506 SDValue ShuffleVec = SVOp->getOperand(0);
5507 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5508 assert(ShuffleVecVT.getVectorElementType() ==
5509 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5511 int ShuffleIdx = SVOp->getMaskElt(Idx);
5512 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5513 ExtractedFromVec = ShuffleVec;
5519 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5520 MVT VT = Op.getSimpleValueType();
5522 // Skip if insert_vec_elt is not supported.
5523 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5524 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5528 unsigned NumElems = Op.getNumOperands();
5532 SmallVector<unsigned, 4> InsertIndices;
5533 SmallVector<int, 8> Mask(NumElems, -1);
5535 for (unsigned i = 0; i != NumElems; ++i) {
5536 unsigned Opc = Op.getOperand(i).getOpcode();
5538 if (Opc == ISD::UNDEF)
5541 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5542 // Quit if more than 1 elements need inserting.
5543 if (InsertIndices.size() > 1)
5546 InsertIndices.push_back(i);
5550 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5551 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5552 // Quit if non-constant index.
5553 if (!isa<ConstantSDNode>(ExtIdx))
5555 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5557 // Quit if extracted from vector of different type.
5558 if (ExtractedFromVec.getValueType() != VT)
5561 if (!VecIn1.getNode())
5562 VecIn1 = ExtractedFromVec;
5563 else if (VecIn1 != ExtractedFromVec) {
5564 if (!VecIn2.getNode())
5565 VecIn2 = ExtractedFromVec;
5566 else if (VecIn2 != ExtractedFromVec)
5567 // Quit if more than 2 vectors to shuffle
5571 if (ExtractedFromVec == VecIn1)
5573 else if (ExtractedFromVec == VecIn2)
5574 Mask[i] = Idx + NumElems;
5577 if (!VecIn1.getNode())
5580 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5581 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5582 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5583 unsigned Idx = InsertIndices[i];
5584 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5585 DAG.getIntPtrConstant(Idx, DL));
5591 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5592 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5593 Op.getScalarValueSizeInBits() == 1 &&
5594 "Can not convert non-constant vector");
5595 uint64_t Immediate = 0;
5596 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5597 SDValue In = Op.getOperand(idx);
5598 if (In.getOpcode() != ISD::UNDEF)
5599 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5603 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5604 return DAG.getConstant(Immediate, dl, VT);
5606 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5608 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5610 MVT VT = Op.getSimpleValueType();
5611 assert((VT.getVectorElementType() == MVT::i1) &&
5612 "Unexpected type in LowerBUILD_VECTORvXi1!");
5615 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5616 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5617 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5618 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5621 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5622 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5623 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5624 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5627 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5628 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5629 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5630 return DAG.getBitcast(VT, Imm);
5631 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5632 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5633 DAG.getIntPtrConstant(0, dl));
5636 // Vector has one or more non-const elements
5637 uint64_t Immediate = 0;
5638 SmallVector<unsigned, 16> NonConstIdx;
5639 bool IsSplat = true;
5640 bool HasConstElts = false;
5642 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5643 SDValue In = Op.getOperand(idx);
5644 if (In.getOpcode() == ISD::UNDEF)
5646 if (!isa<ConstantSDNode>(In))
5647 NonConstIdx.push_back(idx);
5649 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5650 HasConstElts = true;
5654 else if (In != Op.getOperand(SplatIdx))
5658 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5660 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5661 DAG.getConstant(1, dl, VT),
5662 DAG.getConstant(0, dl, VT));
5664 // insert elements one by one
5668 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5669 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5671 else if (HasConstElts)
5672 Imm = DAG.getConstant(0, dl, VT);
5674 Imm = DAG.getUNDEF(VT);
5675 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5676 DstVec = DAG.getBitcast(VT, Imm);
5678 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5679 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5680 DAG.getIntPtrConstant(0, dl));
5683 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5684 unsigned InsertIdx = NonConstIdx[i];
5685 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5686 Op.getOperand(InsertIdx),
5687 DAG.getIntPtrConstant(InsertIdx, dl));
5692 /// \brief Return true if \p N implements a horizontal binop and return the
5693 /// operands for the horizontal binop into V0 and V1.
5695 /// This is a helper function of LowerToHorizontalOp().
5696 /// This function checks that the build_vector \p N in input implements a
5697 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5698 /// operation to match.
5699 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5700 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5701 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5704 /// This function only analyzes elements of \p N whose indices are
5705 /// in range [BaseIdx, LastIdx).
5706 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5708 unsigned BaseIdx, unsigned LastIdx,
5709 SDValue &V0, SDValue &V1) {
5710 EVT VT = N->getValueType(0);
5712 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5713 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5714 "Invalid Vector in input!");
5716 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5717 bool CanFold = true;
5718 unsigned ExpectedVExtractIdx = BaseIdx;
5719 unsigned NumElts = LastIdx - BaseIdx;
5720 V0 = DAG.getUNDEF(VT);
5721 V1 = DAG.getUNDEF(VT);
5723 // Check if N implements a horizontal binop.
5724 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5725 SDValue Op = N->getOperand(i + BaseIdx);
5728 if (Op->getOpcode() == ISD::UNDEF) {
5729 // Update the expected vector extract index.
5730 if (i * 2 == NumElts)
5731 ExpectedVExtractIdx = BaseIdx;
5732 ExpectedVExtractIdx += 2;
5736 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5741 SDValue Op0 = Op.getOperand(0);
5742 SDValue Op1 = Op.getOperand(1);
5744 // Try to match the following pattern:
5745 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5746 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5747 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5748 Op0.getOperand(0) == Op1.getOperand(0) &&
5749 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5750 isa<ConstantSDNode>(Op1.getOperand(1)));
5754 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5755 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5757 if (i * 2 < NumElts) {
5758 if (V0.getOpcode() == ISD::UNDEF) {
5759 V0 = Op0.getOperand(0);
5760 if (V0.getValueType() != VT)
5764 if (V1.getOpcode() == ISD::UNDEF) {
5765 V1 = Op0.getOperand(0);
5766 if (V1.getValueType() != VT)
5769 if (i * 2 == NumElts)
5770 ExpectedVExtractIdx = BaseIdx;
5773 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5774 if (I0 == ExpectedVExtractIdx)
5775 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5776 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5777 // Try to match the following dag sequence:
5778 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5779 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5783 ExpectedVExtractIdx += 2;
5789 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5790 /// a concat_vector.
5792 /// This is a helper function of LowerToHorizontalOp().
5793 /// This function expects two 256-bit vectors called V0 and V1.
5794 /// At first, each vector is split into two separate 128-bit vectors.
5795 /// Then, the resulting 128-bit vectors are used to implement two
5796 /// horizontal binary operations.
5798 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5800 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5801 /// the two new horizontal binop.
5802 /// When Mode is set, the first horizontal binop dag node would take as input
5803 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5804 /// horizontal binop dag node would take as input the lower 128-bit of V1
5805 /// and the upper 128-bit of V1.
5807 /// HADD V0_LO, V0_HI
5808 /// HADD V1_LO, V1_HI
5810 /// Otherwise, the first horizontal binop dag node takes as input the lower
5811 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5812 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5814 /// HADD V0_LO, V1_LO
5815 /// HADD V0_HI, V1_HI
5817 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5818 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5819 /// the upper 128-bits of the result.
5820 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5821 SDLoc DL, SelectionDAG &DAG,
5822 unsigned X86Opcode, bool Mode,
5823 bool isUndefLO, bool isUndefHI) {
5824 EVT VT = V0.getValueType();
5825 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5826 "Invalid nodes in input!");
5828 unsigned NumElts = VT.getVectorNumElements();
5829 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5830 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5831 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5832 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5833 EVT NewVT = V0_LO.getValueType();
5835 SDValue LO = DAG.getUNDEF(NewVT);
5836 SDValue HI = DAG.getUNDEF(NewVT);
5839 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5840 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5841 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5842 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5843 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5845 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5846 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5847 V1_LO->getOpcode() != ISD::UNDEF))
5848 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5850 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5851 V1_HI->getOpcode() != ISD::UNDEF))
5852 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5855 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5858 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5860 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5861 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5862 EVT VT = BV->getValueType(0);
5863 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5864 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5868 unsigned NumElts = VT.getVectorNumElements();
5869 SDValue InVec0 = DAG.getUNDEF(VT);
5870 SDValue InVec1 = DAG.getUNDEF(VT);
5872 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5873 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5875 // Odd-numbered elements in the input build vector are obtained from
5876 // adding two integer/float elements.
5877 // Even-numbered elements in the input build vector are obtained from
5878 // subtracting two integer/float elements.
5879 unsigned ExpectedOpcode = ISD::FSUB;
5880 unsigned NextExpectedOpcode = ISD::FADD;
5881 bool AddFound = false;
5882 bool SubFound = false;
5884 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5885 SDValue Op = BV->getOperand(i);
5887 // Skip 'undef' values.
5888 unsigned Opcode = Op.getOpcode();
5889 if (Opcode == ISD::UNDEF) {
5890 std::swap(ExpectedOpcode, NextExpectedOpcode);
5894 // Early exit if we found an unexpected opcode.
5895 if (Opcode != ExpectedOpcode)
5898 SDValue Op0 = Op.getOperand(0);
5899 SDValue Op1 = Op.getOperand(1);
5901 // Try to match the following pattern:
5902 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5903 // Early exit if we cannot match that sequence.
5904 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5905 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5906 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5907 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5908 Op0.getOperand(1) != Op1.getOperand(1))
5911 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5915 // We found a valid add/sub node. Update the information accordingly.
5921 // Update InVec0 and InVec1.
5922 if (InVec0.getOpcode() == ISD::UNDEF) {
5923 InVec0 = Op0.getOperand(0);
5924 if (InVec0.getValueType() != VT)
5927 if (InVec1.getOpcode() == ISD::UNDEF) {
5928 InVec1 = Op1.getOperand(0);
5929 if (InVec1.getValueType() != VT)
5933 // Make sure that operands in input to each add/sub node always
5934 // come from a same pair of vectors.
5935 if (InVec0 != Op0.getOperand(0)) {
5936 if (ExpectedOpcode == ISD::FSUB)
5939 // FADD is commutable. Try to commute the operands
5940 // and then test again.
5941 std::swap(Op0, Op1);
5942 if (InVec0 != Op0.getOperand(0))
5946 if (InVec1 != Op1.getOperand(0))
5949 // Update the pair of expected opcodes.
5950 std::swap(ExpectedOpcode, NextExpectedOpcode);
5953 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5954 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5955 InVec1.getOpcode() != ISD::UNDEF)
5956 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5961 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5962 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5963 const X86Subtarget *Subtarget,
5964 SelectionDAG &DAG) {
5965 EVT VT = BV->getValueType(0);
5966 unsigned NumElts = VT.getVectorNumElements();
5967 unsigned NumUndefsLO = 0;
5968 unsigned NumUndefsHI = 0;
5969 unsigned Half = NumElts/2;
5971 // Count the number of UNDEF operands in the build_vector in input.
5972 for (unsigned i = 0, e = Half; i != e; ++i)
5973 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5976 for (unsigned i = Half, e = NumElts; i != e; ++i)
5977 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5980 // Early exit if this is either a build_vector of all UNDEFs or all the
5981 // operands but one are UNDEF.
5982 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5986 SDValue InVec0, InVec1;
5987 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5988 // Try to match an SSE3 float HADD/HSUB.
5989 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5990 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5992 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5993 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5994 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5995 // Try to match an SSSE3 integer HADD/HSUB.
5996 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5997 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5999 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6000 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6003 if (!Subtarget->hasAVX())
6006 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6007 // Try to match an AVX horizontal add/sub of packed single/double
6008 // precision floating point values from 256-bit vectors.
6009 SDValue InVec2, InVec3;
6010 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6011 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6012 ((InVec0.getOpcode() == ISD::UNDEF ||
6013 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6014 ((InVec1.getOpcode() == ISD::UNDEF ||
6015 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6016 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6018 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6019 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6020 ((InVec0.getOpcode() == ISD::UNDEF ||
6021 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6022 ((InVec1.getOpcode() == ISD::UNDEF ||
6023 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6024 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6025 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6026 // Try to match an AVX2 horizontal add/sub of signed integers.
6027 SDValue InVec2, InVec3;
6029 bool CanFold = true;
6031 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6032 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6033 ((InVec0.getOpcode() == ISD::UNDEF ||
6034 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6035 ((InVec1.getOpcode() == ISD::UNDEF ||
6036 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6037 X86Opcode = X86ISD::HADD;
6038 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6039 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6040 ((InVec0.getOpcode() == ISD::UNDEF ||
6041 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6042 ((InVec1.getOpcode() == ISD::UNDEF ||
6043 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6044 X86Opcode = X86ISD::HSUB;
6049 // Fold this build_vector into a single horizontal add/sub.
6050 // Do this only if the target has AVX2.
6051 if (Subtarget->hasAVX2())
6052 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6054 // Do not try to expand this build_vector into a pair of horizontal
6055 // add/sub if we can emit a pair of scalar add/sub.
6056 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6059 // Convert this build_vector into a pair of horizontal binop followed by
6061 bool isUndefLO = NumUndefsLO == Half;
6062 bool isUndefHI = NumUndefsHI == Half;
6063 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6064 isUndefLO, isUndefHI);
6068 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6069 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6071 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6072 X86Opcode = X86ISD::HADD;
6073 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6074 X86Opcode = X86ISD::HSUB;
6075 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6076 X86Opcode = X86ISD::FHADD;
6077 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6078 X86Opcode = X86ISD::FHSUB;
6082 // Don't try to expand this build_vector into a pair of horizontal add/sub
6083 // if we can simply emit a pair of scalar add/sub.
6084 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6087 // Convert this build_vector into two horizontal add/sub followed by
6089 bool isUndefLO = NumUndefsLO == Half;
6090 bool isUndefHI = NumUndefsHI == Half;
6091 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6092 isUndefLO, isUndefHI);
6099 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6102 MVT VT = Op.getSimpleValueType();
6103 MVT ExtVT = VT.getVectorElementType();
6104 unsigned NumElems = Op.getNumOperands();
6106 // Generate vectors for predicate vectors.
6107 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6108 return LowerBUILD_VECTORvXi1(Op, DAG);
6110 // Vectors containing all zeros can be matched by pxor and xorps later
6111 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6112 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6113 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6114 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6117 return getZeroVector(VT, Subtarget, DAG, dl);
6120 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6121 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6122 // vpcmpeqd on 256-bit vectors.
6123 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6124 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6127 if (!VT.is512BitVector())
6128 return getOnesVector(VT, Subtarget, DAG, dl);
6131 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6132 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6134 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6135 return HorizontalOp;
6136 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6139 unsigned EVTBits = ExtVT.getSizeInBits();
6141 unsigned NumZero = 0;
6142 unsigned NumNonZero = 0;
6143 unsigned NonZeros = 0;
6144 bool IsAllConstants = true;
6145 SmallSet<SDValue, 8> Values;
6146 for (unsigned i = 0; i < NumElems; ++i) {
6147 SDValue Elt = Op.getOperand(i);
6148 if (Elt.getOpcode() == ISD::UNDEF)
6151 if (Elt.getOpcode() != ISD::Constant &&
6152 Elt.getOpcode() != ISD::ConstantFP)
6153 IsAllConstants = false;
6154 if (X86::isZeroNode(Elt))
6157 NonZeros |= (1 << i);
6162 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6163 if (NumNonZero == 0)
6164 return DAG.getUNDEF(VT);
6166 // Special case for single non-zero, non-undef, element.
6167 if (NumNonZero == 1) {
6168 unsigned Idx = countTrailingZeros(NonZeros);
6169 SDValue Item = Op.getOperand(Idx);
6171 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6172 // the value are obviously zero, truncate the value to i32 and do the
6173 // insertion that way. Only do this if the value is non-constant or if the
6174 // value is a constant being inserted into element 0. It is cheaper to do
6175 // a constant pool load than it is to do a movd + shuffle.
6176 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6177 (!IsAllConstants || Idx == 0)) {
6178 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6180 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6181 EVT VecVT = MVT::v4i32;
6183 // Truncate the value (which may itself be a constant) to i32, and
6184 // convert it to a vector with movd (S2V+shuffle to zero extend).
6185 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6186 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6187 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6188 Item, Idx * 2, true, Subtarget, DAG));
6192 // If we have a constant or non-constant insertion into the low element of
6193 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6194 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6195 // depending on what the source datatype is.
6198 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6200 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6201 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6202 if (VT.is512BitVector()) {
6203 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6204 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6205 Item, DAG.getIntPtrConstant(0, dl));
6207 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6208 "Expected an SSE value type!");
6209 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6210 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6211 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6214 // We can't directly insert an i8 or i16 into a vector, so zero extend
6216 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6217 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6218 if (VT.is256BitVector()) {
6219 if (Subtarget->hasAVX()) {
6220 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6221 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6223 // Without AVX, we need to extend to a 128-bit vector and then
6224 // insert into the 256-bit vector.
6225 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6226 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6227 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6230 assert(VT.is128BitVector() && "Expected an SSE value type!");
6231 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6232 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6234 return DAG.getBitcast(VT, Item);
6238 // Is it a vector logical left shift?
6239 if (NumElems == 2 && Idx == 1 &&
6240 X86::isZeroNode(Op.getOperand(0)) &&
6241 !X86::isZeroNode(Op.getOperand(1))) {
6242 unsigned NumBits = VT.getSizeInBits();
6243 return getVShift(true, VT,
6244 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6245 VT, Op.getOperand(1)),
6246 NumBits/2, DAG, *this, dl);
6249 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6252 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6253 // is a non-constant being inserted into an element other than the low one,
6254 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6255 // movd/movss) to move this into the low element, then shuffle it into
6257 if (EVTBits == 32) {
6258 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6259 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6263 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6264 if (Values.size() == 1) {
6265 if (EVTBits == 32) {
6266 // Instead of a shuffle like this:
6267 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6268 // Check if it's possible to issue this instead.
6269 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6270 unsigned Idx = countTrailingZeros(NonZeros);
6271 SDValue Item = Op.getOperand(Idx);
6272 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6273 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6278 // A vector full of immediates; various special cases are already
6279 // handled, so this is best done with a single constant-pool load.
6283 // For AVX-length vectors, see if we can use a vector load to get all of the
6284 // elements, otherwise build the individual 128-bit pieces and use
6285 // shuffles to put them in place.
6286 if (VT.is256BitVector() || VT.is512BitVector()) {
6287 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6289 // Check for a build vector of consecutive loads.
6290 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6293 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6295 // Build both the lower and upper subvector.
6296 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6297 makeArrayRef(&V[0], NumElems/2));
6298 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6299 makeArrayRef(&V[NumElems / 2], NumElems/2));
6301 // Recreate the wider vector with the lower and upper part.
6302 if (VT.is256BitVector())
6303 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6304 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6307 // Let legalizer expand 2-wide build_vectors.
6308 if (EVTBits == 64) {
6309 if (NumNonZero == 1) {
6310 // One half is zero or undef.
6311 unsigned Idx = countTrailingZeros(NonZeros);
6312 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6313 Op.getOperand(Idx));
6314 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6319 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6320 if (EVTBits == 8 && NumElems == 16)
6321 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6325 if (EVTBits == 16 && NumElems == 8)
6326 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6330 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6331 if (EVTBits == 32 && NumElems == 4)
6332 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6335 // If element VT is == 32 bits, turn it into a number of shuffles.
6336 SmallVector<SDValue, 8> V(NumElems);
6337 if (NumElems == 4 && NumZero > 0) {
6338 for (unsigned i = 0; i < 4; ++i) {
6339 bool isZero = !(NonZeros & (1 << i));
6341 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6343 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6346 for (unsigned i = 0; i < 2; ++i) {
6347 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6350 V[i] = V[i*2]; // Must be a zero vector.
6353 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6356 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6359 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6364 bool Reverse1 = (NonZeros & 0x3) == 2;
6365 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6369 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6370 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6372 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6375 if (Values.size() > 1 && VT.is128BitVector()) {
6376 // Check for a build vector of consecutive loads.
6377 for (unsigned i = 0; i < NumElems; ++i)
6378 V[i] = Op.getOperand(i);
6380 // Check for elements which are consecutive loads.
6381 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6384 // Check for a build vector from mostly shuffle plus few inserting.
6385 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6388 // For SSE 4.1, use insertps to put the high elements into the low element.
6389 if (Subtarget->hasSSE41()) {
6391 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6392 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6394 Result = DAG.getUNDEF(VT);
6396 for (unsigned i = 1; i < NumElems; ++i) {
6397 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6398 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6399 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6404 // Otherwise, expand into a number of unpckl*, start by extending each of
6405 // our (non-undef) elements to the full vector width with the element in the
6406 // bottom slot of the vector (which generates no code for SSE).
6407 for (unsigned i = 0; i < NumElems; ++i) {
6408 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6409 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6411 V[i] = DAG.getUNDEF(VT);
6414 // Next, we iteratively mix elements, e.g. for v4f32:
6415 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6416 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6417 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6418 unsigned EltStride = NumElems >> 1;
6419 while (EltStride != 0) {
6420 for (unsigned i = 0; i < EltStride; ++i) {
6421 // If V[i+EltStride] is undef and this is the first round of mixing,
6422 // then it is safe to just drop this shuffle: V[i] is already in the
6423 // right place, the one element (since it's the first round) being
6424 // inserted as undef can be dropped. This isn't safe for successive
6425 // rounds because they will permute elements within both vectors.
6426 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6427 EltStride == NumElems/2)
6430 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6439 // 256-bit AVX can use the vinsertf128 instruction
6440 // to create 256-bit vectors from two other 128-bit ones.
6441 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6443 MVT ResVT = Op.getSimpleValueType();
6445 assert((ResVT.is256BitVector() ||
6446 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6448 SDValue V1 = Op.getOperand(0);
6449 SDValue V2 = Op.getOperand(1);
6450 unsigned NumElems = ResVT.getVectorNumElements();
6451 if (ResVT.is256BitVector())
6452 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6454 if (Op.getNumOperands() == 4) {
6455 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6456 ResVT.getVectorNumElements()/2);
6457 SDValue V3 = Op.getOperand(2);
6458 SDValue V4 = Op.getOperand(3);
6459 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6460 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6462 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6465 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6466 const X86Subtarget *Subtarget,
6467 SelectionDAG & DAG) {
6469 MVT ResVT = Op.getSimpleValueType();
6470 unsigned NumOfOperands = Op.getNumOperands();
6472 assert(isPowerOf2_32(NumOfOperands) &&
6473 "Unexpected number of operands in CONCAT_VECTORS");
6475 if (NumOfOperands > 2) {
6476 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6477 ResVT.getVectorNumElements()/2);
6478 SmallVector<SDValue, 2> Ops;
6479 for (unsigned i = 0; i < NumOfOperands/2; i++)
6480 Ops.push_back(Op.getOperand(i));
6481 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6483 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6484 Ops.push_back(Op.getOperand(i));
6485 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6486 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6489 SDValue V1 = Op.getOperand(0);
6490 SDValue V2 = Op.getOperand(1);
6491 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6492 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6494 if (IsZeroV1 && IsZeroV2)
6495 return getZeroVector(ResVT, Subtarget, DAG, dl);
6497 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6498 SDValue Undef = DAG.getUNDEF(ResVT);
6499 unsigned NumElems = ResVT.getVectorNumElements();
6500 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6502 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6503 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6507 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6508 // Zero the upper bits of V1
6509 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6510 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6513 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6516 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6517 const X86Subtarget *Subtarget,
6518 SelectionDAG &DAG) {
6519 MVT VT = Op.getSimpleValueType();
6520 if (VT.getVectorElementType() == MVT::i1)
6521 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6523 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6524 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6525 Op.getNumOperands() == 4)));
6527 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6528 // from two other 128-bit ones.
6530 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6531 return LowerAVXCONCAT_VECTORS(Op, DAG);
6534 //===----------------------------------------------------------------------===//
6535 // Vector shuffle lowering
6537 // This is an experimental code path for lowering vector shuffles on x86. It is
6538 // designed to handle arbitrary vector shuffles and blends, gracefully
6539 // degrading performance as necessary. It works hard to recognize idiomatic
6540 // shuffles and lower them to optimal instruction patterns without leaving
6541 // a framework that allows reasonably efficient handling of all vector shuffle
6543 //===----------------------------------------------------------------------===//
6545 /// \brief Tiny helper function to identify a no-op mask.
6547 /// This is a somewhat boring predicate function. It checks whether the mask
6548 /// array input, which is assumed to be a single-input shuffle mask of the kind
6549 /// used by the X86 shuffle instructions (not a fully general
6550 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6551 /// in-place shuffle are 'no-op's.
6552 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6553 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6554 if (Mask[i] != -1 && Mask[i] != i)
6559 /// \brief Helper function to classify a mask as a single-input mask.
6561 /// This isn't a generic single-input test because in the vector shuffle
6562 /// lowering we canonicalize single inputs to be the first input operand. This
6563 /// means we can more quickly test for a single input by only checking whether
6564 /// an input from the second operand exists. We also assume that the size of
6565 /// mask corresponds to the size of the input vectors which isn't true in the
6566 /// fully general case.
6567 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6569 if (M >= (int)Mask.size())
6574 /// \brief Test whether there are elements crossing 128-bit lanes in this
6577 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6578 /// and we routinely test for these.
6579 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6580 int LaneSize = 128 / VT.getScalarSizeInBits();
6581 int Size = Mask.size();
6582 for (int i = 0; i < Size; ++i)
6583 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6588 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6590 /// This checks a shuffle mask to see if it is performing the same
6591 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6592 /// that it is also not lane-crossing. It may however involve a blend from the
6593 /// same lane of a second vector.
6595 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6596 /// non-trivial to compute in the face of undef lanes. The representation is
6597 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6598 /// entries from both V1 and V2 inputs to the wider mask.
6600 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6601 SmallVectorImpl<int> &RepeatedMask) {
6602 int LaneSize = 128 / VT.getScalarSizeInBits();
6603 RepeatedMask.resize(LaneSize, -1);
6604 int Size = Mask.size();
6605 for (int i = 0; i < Size; ++i) {
6608 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6609 // This entry crosses lanes, so there is no way to model this shuffle.
6612 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6613 if (RepeatedMask[i % LaneSize] == -1)
6614 // This is the first non-undef entry in this slot of a 128-bit lane.
6615 RepeatedMask[i % LaneSize] =
6616 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6617 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6618 // Found a mismatch with the repeated mask.
6624 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6627 /// This is a fast way to test a shuffle mask against a fixed pattern:
6629 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6631 /// It returns true if the mask is exactly as wide as the argument list, and
6632 /// each element of the mask is either -1 (signifying undef) or the value given
6633 /// in the argument.
6634 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6635 ArrayRef<int> ExpectedMask) {
6636 if (Mask.size() != ExpectedMask.size())
6639 int Size = Mask.size();
6641 // If the values are build vectors, we can look through them to find
6642 // equivalent inputs that make the shuffles equivalent.
6643 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6644 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6646 for (int i = 0; i < Size; ++i)
6647 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6648 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6649 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6650 if (!MaskBV || !ExpectedBV ||
6651 MaskBV->getOperand(Mask[i] % Size) !=
6652 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6659 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6661 /// This helper function produces an 8-bit shuffle immediate corresponding to
6662 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6663 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6666 /// NB: We rely heavily on "undef" masks preserving the input lane.
6667 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6668 SelectionDAG &DAG) {
6669 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6670 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6671 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6672 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6673 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6676 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6677 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6678 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6679 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6680 return DAG.getConstant(Imm, DL, MVT::i8);
6683 /// \brief Compute whether each element of a shuffle is zeroable.
6685 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6686 /// Either it is an undef element in the shuffle mask, the element of the input
6687 /// referenced is undef, or the element of the input referenced is known to be
6688 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6689 /// as many lanes with this technique as possible to simplify the remaining
6691 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6692 SDValue V1, SDValue V2) {
6693 SmallBitVector Zeroable(Mask.size(), false);
6695 while (V1.getOpcode() == ISD::BITCAST)
6696 V1 = V1->getOperand(0);
6697 while (V2.getOpcode() == ISD::BITCAST)
6698 V2 = V2->getOperand(0);
6700 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6701 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6703 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6705 // Handle the easy cases.
6706 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6711 // If this is an index into a build_vector node (which has the same number
6712 // of elements), dig out the input value and use it.
6713 SDValue V = M < Size ? V1 : V2;
6714 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6717 SDValue Input = V.getOperand(M % Size);
6718 // The UNDEF opcode check really should be dead code here, but not quite
6719 // worth asserting on (it isn't invalid, just unexpected).
6720 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6727 // X86 has dedicated unpack instructions that can handle specific blend
6728 // operations: UNPCKH and UNPCKL.
6729 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6730 SDValue V1, SDValue V2,
6731 SelectionDAG &DAG) {
6732 int NumElts = VT.getVectorNumElements();
6735 bool UnpcklSwapped = true;
6736 bool UnpckhSwapped = true;
6737 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6739 for (int i = 0; i < NumElts; ++i) {
6740 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6742 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6743 int HiPos = LoPos + NumEltsInLane / 2;
6744 int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6745 int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6749 if (Mask[i] != LoPos)
6751 if (Mask[i] != HiPos)
6753 if (Mask[i] != LoPosSwapped)
6754 UnpcklSwapped = false;
6755 if (Mask[i] != HiPosSwapped)
6756 UnpckhSwapped = false;
6757 if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6761 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6763 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6765 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6767 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6769 llvm_unreachable("Unexpected result of UNPCK mask analysis");
6773 /// \brief Try to emit a bitmask instruction for a shuffle.
6775 /// This handles cases where we can model a blend exactly as a bitmask due to
6776 /// one of the inputs being zeroable.
6777 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6778 SDValue V2, ArrayRef<int> Mask,
6779 SelectionDAG &DAG) {
6780 MVT EltVT = VT.getScalarType();
6781 int NumEltBits = EltVT.getSizeInBits();
6782 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6783 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6784 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6786 if (EltVT.isFloatingPoint()) {
6787 Zero = DAG.getBitcast(EltVT, Zero);
6788 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6790 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6791 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6793 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6796 if (Mask[i] % Size != i)
6797 return SDValue(); // Not a blend.
6799 V = Mask[i] < Size ? V1 : V2;
6800 else if (V != (Mask[i] < Size ? V1 : V2))
6801 return SDValue(); // Can only let one input through the mask.
6803 VMaskOps[i] = AllOnes;
6806 return SDValue(); // No non-zeroable elements!
6808 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6809 V = DAG.getNode(VT.isFloatingPoint()
6810 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6815 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6817 /// This is used as a fallback approach when first class blend instructions are
6818 /// unavailable. Currently it is only suitable for integer vectors, but could
6819 /// be generalized for floating point vectors if desirable.
6820 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6821 SDValue V2, ArrayRef<int> Mask,
6822 SelectionDAG &DAG) {
6823 assert(VT.isInteger() && "Only supports integer vector types!");
6824 MVT EltVT = VT.getScalarType();
6825 int NumEltBits = EltVT.getSizeInBits();
6826 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6827 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6829 SmallVector<SDValue, 16> MaskOps;
6830 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6831 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6832 return SDValue(); // Shuffled input!
6833 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6836 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6837 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6838 // We have to cast V2 around.
6839 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6840 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6841 DAG.getBitcast(MaskVT, V1Mask),
6842 DAG.getBitcast(MaskVT, V2)));
6843 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6846 /// \brief Try to emit a blend instruction for a shuffle.
6848 /// This doesn't do any checks for the availability of instructions for blending
6849 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6850 /// be matched in the backend with the type given. What it does check for is
6851 /// that the shuffle mask is in fact a blend.
6852 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6853 SDValue V2, ArrayRef<int> Mask,
6854 const X86Subtarget *Subtarget,
6855 SelectionDAG &DAG) {
6856 unsigned BlendMask = 0;
6857 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6858 if (Mask[i] >= Size) {
6859 if (Mask[i] != i + Size)
6860 return SDValue(); // Shuffled V2 input!
6861 BlendMask |= 1u << i;
6864 if (Mask[i] >= 0 && Mask[i] != i)
6865 return SDValue(); // Shuffled V1 input!
6867 switch (VT.SimpleTy) {
6872 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6873 DAG.getConstant(BlendMask, DL, MVT::i8));
6877 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6881 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6882 // that instruction.
6883 if (Subtarget->hasAVX2()) {
6884 // Scale the blend by the number of 32-bit dwords per element.
6885 int Scale = VT.getScalarSizeInBits() / 32;
6887 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6888 if (Mask[i] >= Size)
6889 for (int j = 0; j < Scale; ++j)
6890 BlendMask |= 1u << (i * Scale + j);
6892 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6893 V1 = DAG.getBitcast(BlendVT, V1);
6894 V2 = DAG.getBitcast(BlendVT, V2);
6895 return DAG.getBitcast(
6896 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6897 DAG.getConstant(BlendMask, DL, MVT::i8)));
6901 // For integer shuffles we need to expand the mask and cast the inputs to
6902 // v8i16s prior to blending.
6903 int Scale = 8 / VT.getVectorNumElements();
6905 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6906 if (Mask[i] >= Size)
6907 for (int j = 0; j < Scale; ++j)
6908 BlendMask |= 1u << (i * Scale + j);
6910 V1 = DAG.getBitcast(MVT::v8i16, V1);
6911 V2 = DAG.getBitcast(MVT::v8i16, V2);
6912 return DAG.getBitcast(VT,
6913 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6914 DAG.getConstant(BlendMask, DL, MVT::i8)));
6918 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6919 SmallVector<int, 8> RepeatedMask;
6920 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6921 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6922 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6924 for (int i = 0; i < 8; ++i)
6925 if (RepeatedMask[i] >= 16)
6926 BlendMask |= 1u << i;
6927 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6928 DAG.getConstant(BlendMask, DL, MVT::i8));
6934 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6935 "256-bit byte-blends require AVX2 support!");
6937 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6938 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6941 // Scale the blend by the number of bytes per element.
6942 int Scale = VT.getScalarSizeInBits() / 8;
6944 // This form of blend is always done on bytes. Compute the byte vector
6946 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6948 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6949 // mix of LLVM's code generator and the x86 backend. We tell the code
6950 // generator that boolean values in the elements of an x86 vector register
6951 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6952 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6953 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6954 // of the element (the remaining are ignored) and 0 in that high bit would
6955 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6956 // the LLVM model for boolean values in vector elements gets the relevant
6957 // bit set, it is set backwards and over constrained relative to x86's
6959 SmallVector<SDValue, 32> VSELECTMask;
6960 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6961 for (int j = 0; j < Scale; ++j)
6962 VSELECTMask.push_back(
6963 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6964 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6967 V1 = DAG.getBitcast(BlendVT, V1);
6968 V2 = DAG.getBitcast(BlendVT, V2);
6969 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6970 DAG.getNode(ISD::BUILD_VECTOR, DL,
6971 BlendVT, VSELECTMask),
6976 llvm_unreachable("Not a supported integer vector type!");
6980 /// \brief Try to lower as a blend of elements from two inputs followed by
6981 /// a single-input permutation.
6983 /// This matches the pattern where we can blend elements from two inputs and
6984 /// then reduce the shuffle to a single-input permutation.
6985 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6988 SelectionDAG &DAG) {
6989 // We build up the blend mask while checking whether a blend is a viable way
6990 // to reduce the shuffle.
6991 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6992 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6994 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6998 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7000 if (BlendMask[Mask[i] % Size] == -1)
7001 BlendMask[Mask[i] % Size] = Mask[i];
7002 else if (BlendMask[Mask[i] % Size] != Mask[i])
7003 return SDValue(); // Can't blend in the needed input!
7005 PermuteMask[i] = Mask[i] % Size;
7008 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7009 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7012 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7013 /// blends and permutes.
7015 /// This matches the extremely common pattern for handling combined
7016 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7017 /// operations. It will try to pick the best arrangement of shuffles and
7019 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7023 SelectionDAG &DAG) {
7024 // Shuffle the input elements into the desired positions in V1 and V2 and
7025 // blend them together.
7026 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7027 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7028 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7029 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7030 if (Mask[i] >= 0 && Mask[i] < Size) {
7031 V1Mask[i] = Mask[i];
7033 } else if (Mask[i] >= Size) {
7034 V2Mask[i] = Mask[i] - Size;
7035 BlendMask[i] = i + Size;
7038 // Try to lower with the simpler initial blend strategy unless one of the
7039 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7040 // shuffle may be able to fold with a load or other benefit. However, when
7041 // we'll have to do 2x as many shuffles in order to achieve this, blending
7042 // first is a better strategy.
7043 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7044 if (SDValue BlendPerm =
7045 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7048 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7049 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7050 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7053 /// \brief Try to lower a vector shuffle as a byte rotation.
7055 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7056 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7057 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7058 /// try to generically lower a vector shuffle through such an pattern. It
7059 /// does not check for the profitability of lowering either as PALIGNR or
7060 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7061 /// This matches shuffle vectors that look like:
7063 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7065 /// Essentially it concatenates V1 and V2, shifts right by some number of
7066 /// elements, and takes the low elements as the result. Note that while this is
7067 /// specified as a *right shift* because x86 is little-endian, it is a *left
7068 /// rotate* of the vector lanes.
7069 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7072 const X86Subtarget *Subtarget,
7073 SelectionDAG &DAG) {
7074 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7076 int NumElts = Mask.size();
7077 int NumLanes = VT.getSizeInBits() / 128;
7078 int NumLaneElts = NumElts / NumLanes;
7080 // We need to detect various ways of spelling a rotation:
7081 // [11, 12, 13, 14, 15, 0, 1, 2]
7082 // [-1, 12, 13, 14, -1, -1, 1, -1]
7083 // [-1, -1, -1, -1, -1, -1, 1, 2]
7084 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7085 // [-1, 4, 5, 6, -1, -1, 9, -1]
7086 // [-1, 4, 5, 6, -1, -1, -1, -1]
7089 for (int l = 0; l < NumElts; l += NumLaneElts) {
7090 for (int i = 0; i < NumLaneElts; ++i) {
7091 if (Mask[l + i] == -1)
7093 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7095 // Get the mod-Size index and lane correct it.
7096 int LaneIdx = (Mask[l + i] % NumElts) - l;
7097 // Make sure it was in this lane.
7098 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7101 // Determine where a rotated vector would have started.
7102 int StartIdx = i - LaneIdx;
7104 // The identity rotation isn't interesting, stop.
7107 // If we found the tail of a vector the rotation must be the missing
7108 // front. If we found the head of a vector, it must be how much of the
7110 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7113 Rotation = CandidateRotation;
7114 else if (Rotation != CandidateRotation)
7115 // The rotations don't match, so we can't match this mask.
7118 // Compute which value this mask is pointing at.
7119 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7121 // Compute which of the two target values this index should be assigned
7122 // to. This reflects whether the high elements are remaining or the low
7123 // elements are remaining.
7124 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7126 // Either set up this value if we've not encountered it before, or check
7127 // that it remains consistent.
7130 else if (TargetV != MaskV)
7131 // This may be a rotation, but it pulls from the inputs in some
7132 // unsupported interleaving.
7137 // Check that we successfully analyzed the mask, and normalize the results.
7138 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7139 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7145 // The actual rotate instruction rotates bytes, so we need to scale the
7146 // rotation based on how many bytes are in the vector lane.
7147 int Scale = 16 / NumLaneElts;
7149 // SSSE3 targets can use the palignr instruction.
7150 if (Subtarget->hasSSSE3()) {
7151 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7152 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7153 Lo = DAG.getBitcast(AlignVT, Lo);
7154 Hi = DAG.getBitcast(AlignVT, Hi);
7156 return DAG.getBitcast(
7157 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7158 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7161 assert(VT.getSizeInBits() == 128 &&
7162 "Rotate-based lowering only supports 128-bit lowering!");
7163 assert(Mask.size() <= 16 &&
7164 "Can shuffle at most 16 bytes in a 128-bit vector!");
7166 // Default SSE2 implementation
7167 int LoByteShift = 16 - Rotation * Scale;
7168 int HiByteShift = Rotation * Scale;
7170 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7171 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7172 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7174 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7175 DAG.getConstant(LoByteShift, DL, MVT::i8));
7176 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7177 DAG.getConstant(HiByteShift, DL, MVT::i8));
7178 return DAG.getBitcast(VT,
7179 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7182 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7184 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7185 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7186 /// matches elements from one of the input vectors shuffled to the left or
7187 /// right with zeroable elements 'shifted in'. It handles both the strictly
7188 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7191 /// PSHL : (little-endian) left bit shift.
7192 /// [ zz, 0, zz, 2 ]
7193 /// [ -1, 4, zz, -1 ]
7194 /// PSRL : (little-endian) right bit shift.
7196 /// [ -1, -1, 7, zz]
7197 /// PSLLDQ : (little-endian) left byte shift
7198 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7199 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7200 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7201 /// PSRLDQ : (little-endian) right byte shift
7202 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7203 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7204 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7205 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7206 SDValue V2, ArrayRef<int> Mask,
7207 SelectionDAG &DAG) {
7208 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7210 int Size = Mask.size();
7211 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7213 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7214 for (int i = 0; i < Size; i += Scale)
7215 for (int j = 0; j < Shift; ++j)
7216 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7222 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7223 for (int i = 0; i != Size; i += Scale) {
7224 unsigned Pos = Left ? i + Shift : i;
7225 unsigned Low = Left ? i : i + Shift;
7226 unsigned Len = Scale - Shift;
7227 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7228 Low + (V == V1 ? 0 : Size)))
7232 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7233 bool ByteShift = ShiftEltBits > 64;
7234 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7235 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7236 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7238 // Normalize the scale for byte shifts to still produce an i64 element
7240 Scale = ByteShift ? Scale / 2 : Scale;
7242 // We need to round trip through the appropriate type for the shift.
7243 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7244 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7245 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7246 "Illegal integer vector type");
7247 V = DAG.getBitcast(ShiftVT, V);
7249 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7250 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7251 return DAG.getBitcast(VT, V);
7254 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7255 // keep doubling the size of the integer elements up to that. We can
7256 // then shift the elements of the integer vector by whole multiples of
7257 // their width within the elements of the larger integer vector. Test each
7258 // multiple to see if we can find a match with the moved element indices
7259 // and that the shifted in elements are all zeroable.
7260 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7261 for (int Shift = 1; Shift != Scale; ++Shift)
7262 for (bool Left : {true, false})
7263 if (CheckZeros(Shift, Scale, Left))
7264 for (SDValue V : {V1, V2})
7265 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7272 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7273 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7274 SDValue V2, ArrayRef<int> Mask,
7275 SelectionDAG &DAG) {
7276 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7277 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7279 int Size = Mask.size();
7280 int HalfSize = Size / 2;
7281 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7283 // Upper half must be undefined.
7284 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7287 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7288 // Remainder of lower half result is zero and upper half is all undef.
7289 auto LowerAsEXTRQ = [&]() {
7290 // Determine the extraction length from the part of the
7291 // lower half that isn't zeroable.
7293 for (; Len >= 0; --Len)
7294 if (!Zeroable[Len - 1])
7296 assert(Len > 0 && "Zeroable shuffle mask");
7298 // Attempt to match first Len sequential elements from the lower half.
7301 for (int i = 0; i != Len; ++i) {
7305 SDValue &V = (M < Size ? V1 : V2);
7308 // All mask elements must be in the lower half.
7312 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7323 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7324 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7325 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7326 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7327 DAG.getConstant(BitLen, DL, MVT::i8),
7328 DAG.getConstant(BitIdx, DL, MVT::i8));
7331 if (SDValue ExtrQ = LowerAsEXTRQ())
7334 // INSERTQ: Extract lowest Len elements from lower half of second source and
7335 // insert over first source, starting at Idx.
7336 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7337 auto LowerAsInsertQ = [&]() {
7338 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7341 // Attempt to match first source from mask before insertion point.
7342 if (isUndefInRange(Mask, 0, Idx)) {
7344 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7346 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7352 // Extend the extraction length looking to match both the insertion of
7353 // the second source and the remaining elements of the first.
7354 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7359 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7361 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7367 // Match the remaining elements of the lower half.
7368 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7370 } else if ((!Base || (Base == V1)) &&
7371 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7373 } else if ((!Base || (Base == V2)) &&
7374 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7381 // We may not have a base (first source) - this can safely be undefined.
7383 Base = DAG.getUNDEF(VT);
7385 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7386 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7387 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7388 DAG.getConstant(BitLen, DL, MVT::i8),
7389 DAG.getConstant(BitIdx, DL, MVT::i8));
7396 if (SDValue InsertQ = LowerAsInsertQ())
7402 /// \brief Lower a vector shuffle as a zero or any extension.
7404 /// Given a specific number of elements, element bit width, and extension
7405 /// stride, produce either a zero or any extension based on the available
7406 /// features of the subtarget. The extended elements are consecutive and
7407 /// begin and can start from an offseted element index in the input; to
7408 /// avoid excess shuffling the offset must either being in the bottom lane
7409 /// or at the start of a higher lane. All extended elements must be from
7411 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7412 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7413 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7414 assert(Scale > 1 && "Need a scale to extend.");
7415 int EltBits = VT.getScalarSizeInBits();
7416 int NumElements = VT.getVectorNumElements();
7417 int NumEltsPerLane = 128 / EltBits;
7418 int OffsetLane = Offset / NumEltsPerLane;
7419 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7420 "Only 8, 16, and 32 bit elements can be extended.");
7421 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7422 assert(0 <= Offset && "Extension offset must be positive.");
7423 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7424 "Extension offset must be in the first lane or start an upper lane.");
7426 // Check that an index is in same lane as the base offset.
7427 auto SafeOffset = [&](int Idx) {
7428 return OffsetLane == (Idx / NumEltsPerLane);
7431 // Shift along an input so that the offset base moves to the first element.
7432 auto ShuffleOffset = [&](SDValue V) {
7436 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7437 for (int i = 0; i * Scale < NumElements; ++i) {
7438 int SrcIdx = i + Offset;
7439 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7441 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7444 // Found a valid zext mask! Try various lowering strategies based on the
7445 // input type and available ISA extensions.
7446 if (Subtarget->hasSSE41()) {
7447 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7448 // PUNPCK will catch this in a later shuffle match.
7449 if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7451 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7452 NumElements / Scale);
7453 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7454 return DAG.getBitcast(VT, InputV);
7457 assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7459 // For any extends we can cheat for larger element sizes and use shuffle
7460 // instructions that can fold with a load and/or copy.
7461 if (AnyExt && EltBits == 32) {
7462 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7464 return DAG.getBitcast(
7465 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7466 DAG.getBitcast(MVT::v4i32, InputV),
7467 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7469 if (AnyExt && EltBits == 16 && Scale > 2) {
7470 int PSHUFDMask[4] = {Offset / 2, -1,
7471 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7472 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7473 DAG.getBitcast(MVT::v4i32, InputV),
7474 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7475 int PSHUFWMask[4] = {1, -1, -1, -1};
7476 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7477 return DAG.getBitcast(
7478 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7479 DAG.getBitcast(MVT::v8i16, InputV),
7480 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7483 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7485 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7486 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7487 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7489 int LoIdx = Offset * EltBits;
7490 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7491 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7492 DAG.getConstant(EltBits, DL, MVT::i8),
7493 DAG.getConstant(LoIdx, DL, MVT::i8)));
7495 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7496 !SafeOffset(Offset + 1))
7497 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7499 int HiIdx = (Offset + 1) * EltBits;
7500 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7501 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7502 DAG.getConstant(EltBits, DL, MVT::i8),
7503 DAG.getConstant(HiIdx, DL, MVT::i8)));
7504 return DAG.getNode(ISD::BITCAST, DL, VT,
7505 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7508 // If this would require more than 2 unpack instructions to expand, use
7509 // pshufb when available. We can only use more than 2 unpack instructions
7510 // when zero extending i8 elements which also makes it easier to use pshufb.
7511 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7512 assert(NumElements == 16 && "Unexpected byte vector width!");
7513 SDValue PSHUFBMask[16];
7514 for (int i = 0; i < 16; ++i) {
7515 int Idx = Offset + (i / Scale);
7516 PSHUFBMask[i] = DAG.getConstant(
7517 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7519 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7520 return DAG.getBitcast(VT,
7521 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7522 DAG.getNode(ISD::BUILD_VECTOR, DL,
7523 MVT::v16i8, PSHUFBMask)));
7526 // If we are extending from an offset, ensure we start on a boundary that
7527 // we can unpack from.
7528 int AlignToUnpack = Offset % (NumElements / Scale);
7529 if (AlignToUnpack) {
7530 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7531 for (int i = AlignToUnpack; i < NumElements; ++i)
7532 ShMask[i - AlignToUnpack] = i;
7533 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7534 Offset -= AlignToUnpack;
7537 // Otherwise emit a sequence of unpacks.
7539 unsigned UnpackLoHi = X86ISD::UNPCKL;
7540 if (Offset >= (NumElements / 2)) {
7541 UnpackLoHi = X86ISD::UNPCKH;
7542 Offset -= (NumElements / 2);
7545 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7546 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7547 : getZeroVector(InputVT, Subtarget, DAG, DL);
7548 InputV = DAG.getBitcast(InputVT, InputV);
7549 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7553 } while (Scale > 1);
7554 return DAG.getBitcast(VT, InputV);
7557 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7559 /// This routine will try to do everything in its power to cleverly lower
7560 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7561 /// check for the profitability of this lowering, it tries to aggressively
7562 /// match this pattern. It will use all of the micro-architectural details it
7563 /// can to emit an efficient lowering. It handles both blends with all-zero
7564 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7565 /// masking out later).
7567 /// The reason we have dedicated lowering for zext-style shuffles is that they
7568 /// are both incredibly common and often quite performance sensitive.
7569 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7570 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7571 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7572 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7574 int Bits = VT.getSizeInBits();
7575 int NumLanes = Bits / 128;
7576 int NumElements = VT.getVectorNumElements();
7577 int NumEltsPerLane = NumElements / NumLanes;
7578 assert(VT.getScalarSizeInBits() <= 32 &&
7579 "Exceeds 32-bit integer zero extension limit");
7580 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7582 // Define a helper function to check a particular ext-scale and lower to it if
7584 auto Lower = [&](int Scale) -> SDValue {
7589 for (int i = 0; i < NumElements; ++i) {
7592 continue; // Valid anywhere but doesn't tell us anything.
7593 if (i % Scale != 0) {
7594 // Each of the extended elements need to be zeroable.
7598 // We no longer are in the anyext case.
7603 // Each of the base elements needs to be consecutive indices into the
7604 // same input vector.
7605 SDValue V = M < NumElements ? V1 : V2;
7606 M = M % NumElements;
7609 Offset = M - (i / Scale);
7610 } else if (InputV != V)
7611 return SDValue(); // Flip-flopping inputs.
7613 // Offset must start in the lowest 128-bit lane or at the start of an
7615 // FIXME: Is it ever worth allowing a negative base offset?
7616 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7617 (Offset % NumEltsPerLane) == 0))
7620 // If we are offsetting, all referenced entries must come from the same
7622 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7625 if ((M % NumElements) != (Offset + (i / Scale)))
7626 return SDValue(); // Non-consecutive strided elements.
7630 // If we fail to find an input, we have a zero-shuffle which should always
7631 // have already been handled.
7632 // FIXME: Maybe handle this here in case during blending we end up with one?
7636 // If we are offsetting, don't extend if we only match a single input, we
7637 // can always do better by using a basic PSHUF or PUNPCK.
7638 if (Offset != 0 && Matches < 2)
7641 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7642 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7645 // The widest scale possible for extending is to a 64-bit integer.
7646 assert(Bits % 64 == 0 &&
7647 "The number of bits in a vector must be divisible by 64 on x86!");
7648 int NumExtElements = Bits / 64;
7650 // Each iteration, try extending the elements half as much, but into twice as
7652 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7653 assert(NumElements % NumExtElements == 0 &&
7654 "The input vector size must be divisible by the extended size.");
7655 if (SDValue V = Lower(NumElements / NumExtElements))
7659 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7663 // Returns one of the source operands if the shuffle can be reduced to a
7664 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7665 auto CanZExtLowHalf = [&]() {
7666 for (int i = NumElements / 2; i != NumElements; ++i)
7669 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7671 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7676 if (SDValue V = CanZExtLowHalf()) {
7677 V = DAG.getBitcast(MVT::v2i64, V);
7678 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7679 return DAG.getBitcast(VT, V);
7682 // No viable ext lowering found.
7686 /// \brief Try to get a scalar value for a specific element of a vector.
7688 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7689 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7690 SelectionDAG &DAG) {
7691 MVT VT = V.getSimpleValueType();
7692 MVT EltVT = VT.getVectorElementType();
7693 while (V.getOpcode() == ISD::BITCAST)
7694 V = V.getOperand(0);
7695 // If the bitcasts shift the element size, we can't extract an equivalent
7697 MVT NewVT = V.getSimpleValueType();
7698 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7701 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7702 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7703 // Ensure the scalar operand is the same size as the destination.
7704 // FIXME: Add support for scalar truncation where possible.
7705 SDValue S = V.getOperand(Idx);
7706 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7707 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7713 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7715 /// This is particularly important because the set of instructions varies
7716 /// significantly based on whether the operand is a load or not.
7717 static bool isShuffleFoldableLoad(SDValue V) {
7718 while (V.getOpcode() == ISD::BITCAST)
7719 V = V.getOperand(0);
7721 return ISD::isNON_EXTLoad(V.getNode());
7724 /// \brief Try to lower insertion of a single element into a zero vector.
7726 /// This is a common pattern that we have especially efficient patterns to lower
7727 /// across all subtarget feature sets.
7728 static SDValue lowerVectorShuffleAsElementInsertion(
7729 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7730 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7731 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7733 MVT EltVT = VT.getVectorElementType();
7735 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7736 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7738 bool IsV1Zeroable = true;
7739 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7740 if (i != V2Index && !Zeroable[i]) {
7741 IsV1Zeroable = false;
7745 // Check for a single input from a SCALAR_TO_VECTOR node.
7746 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7747 // all the smarts here sunk into that routine. However, the current
7748 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7749 // vector shuffle lowering is dead.
7750 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7752 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7753 // We need to zext the scalar if it is smaller than an i32.
7754 V2S = DAG.getBitcast(EltVT, V2S);
7755 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7756 // Using zext to expand a narrow element won't work for non-zero
7761 // Zero-extend directly to i32.
7763 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7765 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7766 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7767 EltVT == MVT::i16) {
7768 // Either not inserting from the low element of the input or the input
7769 // element size is too small to use VZEXT_MOVL to clear the high bits.
7773 if (!IsV1Zeroable) {
7774 // If V1 can't be treated as a zero vector we have fewer options to lower
7775 // this. We can't support integer vectors or non-zero targets cheaply, and
7776 // the V1 elements can't be permuted in any way.
7777 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7778 if (!VT.isFloatingPoint() || V2Index != 0)
7780 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7781 V1Mask[V2Index] = -1;
7782 if (!isNoopShuffleMask(V1Mask))
7784 // This is essentially a special case blend operation, but if we have
7785 // general purpose blend operations, they are always faster. Bail and let
7786 // the rest of the lowering handle these as blends.
7787 if (Subtarget->hasSSE41())
7790 // Otherwise, use MOVSD or MOVSS.
7791 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7792 "Only two types of floating point element types to handle!");
7793 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7797 // This lowering only works for the low element with floating point vectors.
7798 if (VT.isFloatingPoint() && V2Index != 0)
7801 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7803 V2 = DAG.getBitcast(VT, V2);
7806 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7807 // the desired position. Otherwise it is more efficient to do a vector
7808 // shift left. We know that we can do a vector shift left because all
7809 // the inputs are zero.
7810 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7811 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7812 V2Shuffle[V2Index] = 0;
7813 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7815 V2 = DAG.getBitcast(MVT::v2i64, V2);
7817 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7818 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7819 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7820 DAG.getDataLayout(), VT)));
7821 V2 = DAG.getBitcast(VT, V2);
7827 /// \brief Try to lower broadcast of a single element.
7829 /// For convenience, this code also bundles all of the subtarget feature set
7830 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7831 /// a convenient way to factor it out.
7832 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7834 const X86Subtarget *Subtarget,
7835 SelectionDAG &DAG) {
7836 if (!Subtarget->hasAVX())
7838 if (VT.isInteger() && !Subtarget->hasAVX2())
7841 // Check that the mask is a broadcast.
7842 int BroadcastIdx = -1;
7844 if (M >= 0 && BroadcastIdx == -1)
7846 else if (M >= 0 && M != BroadcastIdx)
7849 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7850 "a sorted mask where the broadcast "
7853 // Go up the chain of (vector) values to find a scalar load that we can
7854 // combine with the broadcast.
7856 switch (V.getOpcode()) {
7857 case ISD::CONCAT_VECTORS: {
7858 int OperandSize = Mask.size() / V.getNumOperands();
7859 V = V.getOperand(BroadcastIdx / OperandSize);
7860 BroadcastIdx %= OperandSize;
7864 case ISD::INSERT_SUBVECTOR: {
7865 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7866 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7870 int BeginIdx = (int)ConstantIdx->getZExtValue();
7872 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7873 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7874 BroadcastIdx -= BeginIdx;
7885 // Check if this is a broadcast of a scalar. We special case lowering
7886 // for scalars so that we can more effectively fold with loads.
7887 // First, look through bitcast: if the original value has a larger element
7888 // type than the shuffle, the broadcast element is in essence truncated.
7889 // Make that explicit to ease folding.
7890 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7891 EVT EltVT = VT.getVectorElementType();
7892 SDValue V0 = V.getOperand(0);
7893 EVT V0VT = V0.getValueType();
7895 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7896 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7897 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7898 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7903 // Also check the simpler case, where we can directly reuse the scalar.
7904 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7905 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7906 V = V.getOperand(BroadcastIdx);
7908 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7909 // Only AVX2 has register broadcasts.
7910 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7912 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7913 // We can't broadcast from a vector register without AVX2, and we can only
7914 // broadcast from the zero-element of a vector register.
7918 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7921 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7922 // INSERTPS when the V1 elements are already in the correct locations
7923 // because otherwise we can just always use two SHUFPS instructions which
7924 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7925 // perform INSERTPS if a single V1 element is out of place and all V2
7926 // elements are zeroable.
7927 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7929 SelectionDAG &DAG) {
7930 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7931 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7932 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7933 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7935 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7938 int V1DstIndex = -1;
7939 int V2DstIndex = -1;
7940 bool V1UsedInPlace = false;
7942 for (int i = 0; i < 4; ++i) {
7943 // Synthesize a zero mask from the zeroable elements (includes undefs).
7949 // Flag if we use any V1 inputs in place.
7951 V1UsedInPlace = true;
7955 // We can only insert a single non-zeroable element.
7956 if (V1DstIndex != -1 || V2DstIndex != -1)
7960 // V1 input out of place for insertion.
7963 // V2 input for insertion.
7968 // Don't bother if we have no (non-zeroable) element for insertion.
7969 if (V1DstIndex == -1 && V2DstIndex == -1)
7972 // Determine element insertion src/dst indices. The src index is from the
7973 // start of the inserted vector, not the start of the concatenated vector.
7974 unsigned V2SrcIndex = 0;
7975 if (V1DstIndex != -1) {
7976 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7977 // and don't use the original V2 at all.
7978 V2SrcIndex = Mask[V1DstIndex];
7979 V2DstIndex = V1DstIndex;
7982 V2SrcIndex = Mask[V2DstIndex] - 4;
7985 // If no V1 inputs are used in place, then the result is created only from
7986 // the zero mask and the V2 insertion - so remove V1 dependency.
7988 V1 = DAG.getUNDEF(MVT::v4f32);
7990 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7991 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7993 // Insert the V2 element into the desired position.
7995 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7996 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7999 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8000 /// UNPCK instruction.
8002 /// This specifically targets cases where we end up with alternating between
8003 /// the two inputs, and so can permute them into something that feeds a single
8004 /// UNPCK instruction. Note that this routine only targets integer vectors
8005 /// because for floating point vectors we have a generalized SHUFPS lowering
8006 /// strategy that handles everything that doesn't *exactly* match an unpack,
8007 /// making this clever lowering unnecessary.
8008 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8009 SDValue V1, SDValue V2,
8011 SelectionDAG &DAG) {
8012 assert(!VT.isFloatingPoint() &&
8013 "This routine only supports integer vectors.");
8014 assert(!isSingleInputShuffleMask(Mask) &&
8015 "This routine should only be used when blending two inputs.");
8016 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8018 int Size = Mask.size();
8020 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8021 return M >= 0 && M % Size < Size / 2;
8023 int NumHiInputs = std::count_if(
8024 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8026 bool UnpackLo = NumLoInputs >= NumHiInputs;
8028 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8029 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8030 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8032 for (int i = 0; i < Size; ++i) {
8036 // Each element of the unpack contains Scale elements from this mask.
8037 int UnpackIdx = i / Scale;
8039 // We only handle the case where V1 feeds the first slots of the unpack.
8040 // We rely on canonicalization to ensure this is the case.
8041 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8044 // Setup the mask for this input. The indexing is tricky as we have to
8045 // handle the unpack stride.
8046 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8047 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8051 // If we will have to shuffle both inputs to use the unpack, check whether
8052 // we can just unpack first and shuffle the result. If so, skip this unpack.
8053 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8054 !isNoopShuffleMask(V2Mask))
8057 // Shuffle the inputs into place.
8058 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8059 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8061 // Cast the inputs to the type we will use to unpack them.
8062 V1 = DAG.getBitcast(UnpackVT, V1);
8063 V2 = DAG.getBitcast(UnpackVT, V2);
8065 // Unpack the inputs and cast the result back to the desired type.
8066 return DAG.getBitcast(
8067 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8071 // We try each unpack from the largest to the smallest to try and find one
8072 // that fits this mask.
8073 int OrigNumElements = VT.getVectorNumElements();
8074 int OrigScalarSize = VT.getScalarSizeInBits();
8075 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8076 int Scale = ScalarSize / OrigScalarSize;
8077 int NumElements = OrigNumElements / Scale;
8078 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8079 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8083 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8085 if (NumLoInputs == 0 || NumHiInputs == 0) {
8086 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8087 "We have to have *some* inputs!");
8088 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8090 // FIXME: We could consider the total complexity of the permute of each
8091 // possible unpacking. Or at the least we should consider how many
8092 // half-crossings are created.
8093 // FIXME: We could consider commuting the unpacks.
8095 SmallVector<int, 32> PermMask;
8096 PermMask.assign(Size, -1);
8097 for (int i = 0; i < Size; ++i) {
8101 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8104 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8106 return DAG.getVectorShuffle(
8107 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8109 DAG.getUNDEF(VT), PermMask);
8115 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8117 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8118 /// support for floating point shuffles but not integer shuffles. These
8119 /// instructions will incur a domain crossing penalty on some chips though so
8120 /// it is better to avoid lowering through this for integer vectors where
8122 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8123 const X86Subtarget *Subtarget,
8124 SelectionDAG &DAG) {
8126 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8127 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8128 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8129 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8130 ArrayRef<int> Mask = SVOp->getMask();
8131 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8133 if (isSingleInputShuffleMask(Mask)) {
8134 // Use low duplicate instructions for masks that match their pattern.
8135 if (Subtarget->hasSSE3())
8136 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8137 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8139 // Straight shuffle of a single input vector. Simulate this by using the
8140 // single input as both of the "inputs" to this instruction..
8141 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8143 if (Subtarget->hasAVX()) {
8144 // If we have AVX, we can use VPERMILPS which will allow folding a load
8145 // into the shuffle.
8146 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8147 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8150 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8151 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8153 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8154 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8156 // If we have a single input, insert that into V1 if we can do so cheaply.
8157 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8158 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8159 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8161 // Try inverting the insertion since for v2 masks it is easy to do and we
8162 // can't reliably sort the mask one way or the other.
8163 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8164 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8165 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8166 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8170 // Try to use one of the special instruction patterns to handle two common
8171 // blend patterns if a zero-blend above didn't work.
8172 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8173 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8174 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8175 // We can either use a special instruction to load over the low double or
8176 // to move just the low double.
8178 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8180 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8182 if (Subtarget->hasSSE41())
8183 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8187 // Use dedicated unpack instructions for masks that match their pattern.
8188 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8189 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8190 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8191 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8193 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8194 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8195 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8198 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8200 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8201 /// the integer unit to minimize domain crossing penalties. However, for blends
8202 /// it falls back to the floating point shuffle operation with appropriate bit
8204 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8205 const X86Subtarget *Subtarget,
8206 SelectionDAG &DAG) {
8208 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8209 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8210 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8211 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8212 ArrayRef<int> Mask = SVOp->getMask();
8213 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8215 if (isSingleInputShuffleMask(Mask)) {
8216 // Check for being able to broadcast a single element.
8217 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8218 Mask, Subtarget, DAG))
8221 // Straight shuffle of a single input vector. For everything from SSE2
8222 // onward this has a single fast instruction with no scary immediates.
8223 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8224 V1 = DAG.getBitcast(MVT::v4i32, V1);
8225 int WidenedMask[4] = {
8226 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8227 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8228 return DAG.getBitcast(
8230 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8231 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8233 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8234 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8235 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8236 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8238 // If we have a blend of two PACKUS operations an the blend aligns with the
8239 // low and half halves, we can just merge the PACKUS operations. This is
8240 // particularly important as it lets us merge shuffles that this routine itself
8242 auto GetPackNode = [](SDValue V) {
8243 while (V.getOpcode() == ISD::BITCAST)
8244 V = V.getOperand(0);
8246 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8248 if (SDValue V1Pack = GetPackNode(V1))
8249 if (SDValue V2Pack = GetPackNode(V2))
8250 return DAG.getBitcast(MVT::v2i64,
8251 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8252 Mask[0] == 0 ? V1Pack.getOperand(0)
8253 : V1Pack.getOperand(1),
8254 Mask[1] == 2 ? V2Pack.getOperand(0)
8255 : V2Pack.getOperand(1)));
8257 // Try to use shift instructions.
8259 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8262 // When loading a scalar and then shuffling it into a vector we can often do
8263 // the insertion cheaply.
8264 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8265 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8267 // Try inverting the insertion since for v2 masks it is easy to do and we
8268 // can't reliably sort the mask one way or the other.
8269 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8270 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8271 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8274 // We have different paths for blend lowering, but they all must use the
8275 // *exact* same predicate.
8276 bool IsBlendSupported = Subtarget->hasSSE41();
8277 if (IsBlendSupported)
8278 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8282 // Use dedicated unpack instructions for masks that match their pattern.
8283 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8284 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8285 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8286 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8288 // Try to use byte rotation instructions.
8289 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8290 if (Subtarget->hasSSSE3())
8291 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8292 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8295 // If we have direct support for blends, we should lower by decomposing into
8296 // a permute. That will be faster than the domain cross.
8297 if (IsBlendSupported)
8298 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8301 // We implement this with SHUFPD which is pretty lame because it will likely
8302 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8303 // However, all the alternatives are still more cycles and newer chips don't
8304 // have this problem. It would be really nice if x86 had better shuffles here.
8305 V1 = DAG.getBitcast(MVT::v2f64, V1);
8306 V2 = DAG.getBitcast(MVT::v2f64, V2);
8307 return DAG.getBitcast(MVT::v2i64,
8308 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8311 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8313 /// This is used to disable more specialized lowerings when the shufps lowering
8314 /// will happen to be efficient.
8315 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8316 // This routine only handles 128-bit shufps.
8317 assert(Mask.size() == 4 && "Unsupported mask size!");
8319 // To lower with a single SHUFPS we need to have the low half and high half
8320 // each requiring a single input.
8321 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8323 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8329 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8331 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8332 /// It makes no assumptions about whether this is the *best* lowering, it simply
8334 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8335 ArrayRef<int> Mask, SDValue V1,
8336 SDValue V2, SelectionDAG &DAG) {
8337 SDValue LowV = V1, HighV = V2;
8338 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8341 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8343 if (NumV2Elements == 1) {
8345 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8348 // Compute the index adjacent to V2Index and in the same half by toggling
8350 int V2AdjIndex = V2Index ^ 1;
8352 if (Mask[V2AdjIndex] == -1) {
8353 // Handles all the cases where we have a single V2 element and an undef.
8354 // This will only ever happen in the high lanes because we commute the
8355 // vector otherwise.
8357 std::swap(LowV, HighV);
8358 NewMask[V2Index] -= 4;
8360 // Handle the case where the V2 element ends up adjacent to a V1 element.
8361 // To make this work, blend them together as the first step.
8362 int V1Index = V2AdjIndex;
8363 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8364 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8365 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8367 // Now proceed to reconstruct the final blend as we have the necessary
8368 // high or low half formed.
8375 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8376 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8378 } else if (NumV2Elements == 2) {
8379 if (Mask[0] < 4 && Mask[1] < 4) {
8380 // Handle the easy case where we have V1 in the low lanes and V2 in the
8384 } else if (Mask[2] < 4 && Mask[3] < 4) {
8385 // We also handle the reversed case because this utility may get called
8386 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8387 // arrange things in the right direction.
8393 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8394 // trying to place elements directly, just blend them and set up the final
8395 // shuffle to place them.
8397 // The first two blend mask elements are for V1, the second two are for
8399 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8400 Mask[2] < 4 ? Mask[2] : Mask[3],
8401 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8402 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8403 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8404 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8406 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8409 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8410 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8411 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8412 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8415 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8416 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8419 /// \brief Lower 4-lane 32-bit floating point shuffles.
8421 /// Uses instructions exclusively from the floating point unit to minimize
8422 /// domain crossing penalties, as these are sufficient to implement all v4f32
8424 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8425 const X86Subtarget *Subtarget,
8426 SelectionDAG &DAG) {
8428 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8429 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8430 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8431 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8432 ArrayRef<int> Mask = SVOp->getMask();
8433 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8436 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8438 if (NumV2Elements == 0) {
8439 // Check for being able to broadcast a single element.
8440 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8441 Mask, Subtarget, DAG))
8444 // Use even/odd duplicate instructions for masks that match their pattern.
8445 if (Subtarget->hasSSE3()) {
8446 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8447 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8448 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8449 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8452 if (Subtarget->hasAVX()) {
8453 // If we have AVX, we can use VPERMILPS which will allow folding a load
8454 // into the shuffle.
8455 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8456 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8459 // Otherwise, use a straight shuffle of a single input vector. We pass the
8460 // input vector to both operands to simulate this with a SHUFPS.
8461 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8462 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8465 // There are special ways we can lower some single-element blends. However, we
8466 // have custom ways we can lower more complex single-element blends below that
8467 // we defer to if both this and BLENDPS fail to match, so restrict this to
8468 // when the V2 input is targeting element 0 of the mask -- that is the fast
8470 if (NumV2Elements == 1 && Mask[0] >= 4)
8471 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8472 Mask, Subtarget, DAG))
8475 if (Subtarget->hasSSE41()) {
8476 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8480 // Use INSERTPS if we can complete the shuffle efficiently.
8481 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8484 if (!isSingleSHUFPSMask(Mask))
8485 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8486 DL, MVT::v4f32, V1, V2, Mask, DAG))
8490 // Use dedicated unpack instructions for masks that match their pattern.
8491 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8492 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8493 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8494 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8495 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8496 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8497 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8498 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8500 // Otherwise fall back to a SHUFPS lowering strategy.
8501 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8504 /// \brief Lower 4-lane i32 vector shuffles.
8506 /// We try to handle these with integer-domain shuffles where we can, but for
8507 /// blends we use the floating point domain blend instructions.
8508 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8509 const X86Subtarget *Subtarget,
8510 SelectionDAG &DAG) {
8512 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8513 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8514 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8515 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8516 ArrayRef<int> Mask = SVOp->getMask();
8517 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8519 // Whenever we can lower this as a zext, that instruction is strictly faster
8520 // than any alternative. It also allows us to fold memory operands into the
8521 // shuffle in many cases.
8522 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8523 Mask, Subtarget, DAG))
8527 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8529 if (NumV2Elements == 0) {
8530 // Check for being able to broadcast a single element.
8531 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8532 Mask, Subtarget, DAG))
8535 // Straight shuffle of a single input vector. For everything from SSE2
8536 // onward this has a single fast instruction with no scary immediates.
8537 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8538 // but we aren't actually going to use the UNPCK instruction because doing
8539 // so prevents folding a load into this instruction or making a copy.
8540 const int UnpackLoMask[] = {0, 0, 1, 1};
8541 const int UnpackHiMask[] = {2, 2, 3, 3};
8542 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8543 Mask = UnpackLoMask;
8544 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8545 Mask = UnpackHiMask;
8547 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8548 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8551 // Try to use shift instructions.
8553 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8556 // There are special ways we can lower some single-element blends.
8557 if (NumV2Elements == 1)
8558 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8559 Mask, Subtarget, DAG))
8562 // We have different paths for blend lowering, but they all must use the
8563 // *exact* same predicate.
8564 bool IsBlendSupported = Subtarget->hasSSE41();
8565 if (IsBlendSupported)
8566 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8570 if (SDValue Masked =
8571 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8574 // Use dedicated unpack instructions for masks that match their pattern.
8575 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8576 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8577 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8578 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8579 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8580 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8581 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8582 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8584 // Try to use byte rotation instructions.
8585 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8586 if (Subtarget->hasSSSE3())
8587 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8588 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8591 // If we have direct support for blends, we should lower by decomposing into
8592 // a permute. That will be faster than the domain cross.
8593 if (IsBlendSupported)
8594 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8597 // Try to lower by permuting the inputs into an unpack instruction.
8598 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8602 // We implement this with SHUFPS because it can blend from two vectors.
8603 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8604 // up the inputs, bypassing domain shift penalties that we would encur if we
8605 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8607 return DAG.getBitcast(
8609 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8610 DAG.getBitcast(MVT::v4f32, V2), Mask));
8613 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8614 /// shuffle lowering, and the most complex part.
8616 /// The lowering strategy is to try to form pairs of input lanes which are
8617 /// targeted at the same half of the final vector, and then use a dword shuffle
8618 /// to place them onto the right half, and finally unpack the paired lanes into
8619 /// their final position.
8621 /// The exact breakdown of how to form these dword pairs and align them on the
8622 /// correct sides is really tricky. See the comments within the function for
8623 /// more of the details.
8625 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8626 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8627 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8628 /// vector, form the analogous 128-bit 8-element Mask.
8629 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8630 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8631 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8632 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8633 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8635 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8636 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8637 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8639 SmallVector<int, 4> LoInputs;
8640 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8641 [](int M) { return M >= 0; });
8642 std::sort(LoInputs.begin(), LoInputs.end());
8643 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8644 SmallVector<int, 4> HiInputs;
8645 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8646 [](int M) { return M >= 0; });
8647 std::sort(HiInputs.begin(), HiInputs.end());
8648 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8650 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8651 int NumHToL = LoInputs.size() - NumLToL;
8653 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8654 int NumHToH = HiInputs.size() - NumLToH;
8655 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8656 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8657 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8658 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8660 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8661 // such inputs we can swap two of the dwords across the half mark and end up
8662 // with <=2 inputs to each half in each half. Once there, we can fall through
8663 // to the generic code below. For example:
8665 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8666 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8668 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8669 // and an existing 2-into-2 on the other half. In this case we may have to
8670 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8671 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8672 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8673 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8674 // half than the one we target for fixing) will be fixed when we re-enter this
8675 // path. We will also combine away any sequence of PSHUFD instructions that
8676 // result into a single instruction. Here is an example of the tricky case:
8678 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8679 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8681 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8683 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8684 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8686 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8687 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8689 // The result is fine to be handled by the generic logic.
8690 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8691 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8692 int AOffset, int BOffset) {
8693 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8694 "Must call this with A having 3 or 1 inputs from the A half.");
8695 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8696 "Must call this with B having 1 or 3 inputs from the B half.");
8697 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8698 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8700 bool ThreeAInputs = AToAInputs.size() == 3;
8702 // Compute the index of dword with only one word among the three inputs in
8703 // a half by taking the sum of the half with three inputs and subtracting
8704 // the sum of the actual three inputs. The difference is the remaining
8707 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8708 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8709 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8710 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8711 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8712 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8713 int TripleNonInputIdx =
8714 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8715 TripleDWord = TripleNonInputIdx / 2;
8717 // We use xor with one to compute the adjacent DWord to whichever one the
8719 OneInputDWord = (OneInput / 2) ^ 1;
8721 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8722 // and BToA inputs. If there is also such a problem with the BToB and AToB
8723 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8724 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8725 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8726 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8727 // Compute how many inputs will be flipped by swapping these DWords. We
8729 // to balance this to ensure we don't form a 3-1 shuffle in the other
8731 int NumFlippedAToBInputs =
8732 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8733 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8734 int NumFlippedBToBInputs =
8735 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8736 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8737 if ((NumFlippedAToBInputs == 1 &&
8738 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8739 (NumFlippedBToBInputs == 1 &&
8740 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8741 // We choose whether to fix the A half or B half based on whether that
8742 // half has zero flipped inputs. At zero, we may not be able to fix it
8743 // with that half. We also bias towards fixing the B half because that
8744 // will more commonly be the high half, and we have to bias one way.
8745 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8746 ArrayRef<int> Inputs) {
8747 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8748 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8749 PinnedIdx ^ 1) != Inputs.end();
8750 // Determine whether the free index is in the flipped dword or the
8751 // unflipped dword based on where the pinned index is. We use this bit
8752 // in an xor to conditionally select the adjacent dword.
8753 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8754 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8755 FixFreeIdx) != Inputs.end();
8756 if (IsFixIdxInput == IsFixFreeIdxInput)
8758 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8759 FixFreeIdx) != Inputs.end();
8760 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8761 "We need to be changing the number of flipped inputs!");
8762 int PSHUFHalfMask[] = {0, 1, 2, 3};
8763 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8764 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8766 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8769 if (M != -1 && M == FixIdx)
8771 else if (M != -1 && M == FixFreeIdx)
8774 if (NumFlippedBToBInputs != 0) {
8776 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8777 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8779 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8780 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8781 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8786 int PSHUFDMask[] = {0, 1, 2, 3};
8787 PSHUFDMask[ADWord] = BDWord;
8788 PSHUFDMask[BDWord] = ADWord;
8791 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8792 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8794 // Adjust the mask to match the new locations of A and B.
8796 if (M != -1 && M/2 == ADWord)
8797 M = 2 * BDWord + M % 2;
8798 else if (M != -1 && M/2 == BDWord)
8799 M = 2 * ADWord + M % 2;
8801 // Recurse back into this routine to re-compute state now that this isn't
8802 // a 3 and 1 problem.
8803 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8806 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8807 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8808 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8809 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8811 // At this point there are at most two inputs to the low and high halves from
8812 // each half. That means the inputs can always be grouped into dwords and
8813 // those dwords can then be moved to the correct half with a dword shuffle.
8814 // We use at most one low and one high word shuffle to collect these paired
8815 // inputs into dwords, and finally a dword shuffle to place them.
8816 int PSHUFLMask[4] = {-1, -1, -1, -1};
8817 int PSHUFHMask[4] = {-1, -1, -1, -1};
8818 int PSHUFDMask[4] = {-1, -1, -1, -1};
8820 // First fix the masks for all the inputs that are staying in their
8821 // original halves. This will then dictate the targets of the cross-half
8823 auto fixInPlaceInputs =
8824 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8825 MutableArrayRef<int> SourceHalfMask,
8826 MutableArrayRef<int> HalfMask, int HalfOffset) {
8827 if (InPlaceInputs.empty())
8829 if (InPlaceInputs.size() == 1) {
8830 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8831 InPlaceInputs[0] - HalfOffset;
8832 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8835 if (IncomingInputs.empty()) {
8836 // Just fix all of the in place inputs.
8837 for (int Input : InPlaceInputs) {
8838 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8839 PSHUFDMask[Input / 2] = Input / 2;
8844 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8845 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8846 InPlaceInputs[0] - HalfOffset;
8847 // Put the second input next to the first so that they are packed into
8848 // a dword. We find the adjacent index by toggling the low bit.
8849 int AdjIndex = InPlaceInputs[0] ^ 1;
8850 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8851 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8852 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8854 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8855 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8857 // Now gather the cross-half inputs and place them into a free dword of
8858 // their target half.
8859 // FIXME: This operation could almost certainly be simplified dramatically to
8860 // look more like the 3-1 fixing operation.
8861 auto moveInputsToRightHalf = [&PSHUFDMask](
8862 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8863 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8864 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8866 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8867 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8869 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8871 int LowWord = Word & ~1;
8872 int HighWord = Word | 1;
8873 return isWordClobbered(SourceHalfMask, LowWord) ||
8874 isWordClobbered(SourceHalfMask, HighWord);
8877 if (IncomingInputs.empty())
8880 if (ExistingInputs.empty()) {
8881 // Map any dwords with inputs from them into the right half.
8882 for (int Input : IncomingInputs) {
8883 // If the source half mask maps over the inputs, turn those into
8884 // swaps and use the swapped lane.
8885 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8886 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8887 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8888 Input - SourceOffset;
8889 // We have to swap the uses in our half mask in one sweep.
8890 for (int &M : HalfMask)
8891 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8893 else if (M == Input)
8894 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8896 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8897 Input - SourceOffset &&
8898 "Previous placement doesn't match!");
8900 // Note that this correctly re-maps both when we do a swap and when
8901 // we observe the other side of the swap above. We rely on that to
8902 // avoid swapping the members of the input list directly.
8903 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8906 // Map the input's dword into the correct half.
8907 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8908 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8910 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8912 "Previous placement doesn't match!");
8915 // And just directly shift any other-half mask elements to be same-half
8916 // as we will have mirrored the dword containing the element into the
8917 // same position within that half.
8918 for (int &M : HalfMask)
8919 if (M >= SourceOffset && M < SourceOffset + 4) {
8920 M = M - SourceOffset + DestOffset;
8921 assert(M >= 0 && "This should never wrap below zero!");
8926 // Ensure we have the input in a viable dword of its current half. This
8927 // is particularly tricky because the original position may be clobbered
8928 // by inputs being moved and *staying* in that half.
8929 if (IncomingInputs.size() == 1) {
8930 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8931 int InputFixed = std::find(std::begin(SourceHalfMask),
8932 std::end(SourceHalfMask), -1) -
8933 std::begin(SourceHalfMask) + SourceOffset;
8934 SourceHalfMask[InputFixed - SourceOffset] =
8935 IncomingInputs[0] - SourceOffset;
8936 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8938 IncomingInputs[0] = InputFixed;
8940 } else if (IncomingInputs.size() == 2) {
8941 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8942 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8943 // We have two non-adjacent or clobbered inputs we need to extract from
8944 // the source half. To do this, we need to map them into some adjacent
8945 // dword slot in the source mask.
8946 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8947 IncomingInputs[1] - SourceOffset};
8949 // If there is a free slot in the source half mask adjacent to one of
8950 // the inputs, place the other input in it. We use (Index XOR 1) to
8951 // compute an adjacent index.
8952 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8953 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8954 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8955 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8956 InputsFixed[1] = InputsFixed[0] ^ 1;
8957 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8958 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8959 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8960 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8961 InputsFixed[0] = InputsFixed[1] ^ 1;
8962 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8963 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8964 // The two inputs are in the same DWord but it is clobbered and the
8965 // adjacent DWord isn't used at all. Move both inputs to the free
8967 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8968 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8969 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8970 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8972 // The only way we hit this point is if there is no clobbering
8973 // (because there are no off-half inputs to this half) and there is no
8974 // free slot adjacent to one of the inputs. In this case, we have to
8975 // swap an input with a non-input.
8976 for (int i = 0; i < 4; ++i)
8977 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8978 "We can't handle any clobbers here!");
8979 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8980 "Cannot have adjacent inputs here!");
8982 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8983 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8985 // We also have to update the final source mask in this case because
8986 // it may need to undo the above swap.
8987 for (int &M : FinalSourceHalfMask)
8988 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8989 M = InputsFixed[1] + SourceOffset;
8990 else if (M == InputsFixed[1] + SourceOffset)
8991 M = (InputsFixed[0] ^ 1) + SourceOffset;
8993 InputsFixed[1] = InputsFixed[0] ^ 1;
8996 // Point everything at the fixed inputs.
8997 for (int &M : HalfMask)
8998 if (M == IncomingInputs[0])
8999 M = InputsFixed[0] + SourceOffset;
9000 else if (M == IncomingInputs[1])
9001 M = InputsFixed[1] + SourceOffset;
9003 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9004 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9007 llvm_unreachable("Unhandled input size!");
9010 // Now hoist the DWord down to the right half.
9011 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9012 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9013 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9014 for (int &M : HalfMask)
9015 for (int Input : IncomingInputs)
9017 M = FreeDWord * 2 + Input % 2;
9019 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9020 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9021 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9022 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9024 // Now enact all the shuffles we've computed to move the inputs into their
9026 if (!isNoopShuffleMask(PSHUFLMask))
9027 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9028 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9029 if (!isNoopShuffleMask(PSHUFHMask))
9030 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9031 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9032 if (!isNoopShuffleMask(PSHUFDMask))
9035 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9036 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9038 // At this point, each half should contain all its inputs, and we can then
9039 // just shuffle them into their final position.
9040 assert(std::count_if(LoMask.begin(), LoMask.end(),
9041 [](int M) { return M >= 4; }) == 0 &&
9042 "Failed to lift all the high half inputs to the low mask!");
9043 assert(std::count_if(HiMask.begin(), HiMask.end(),
9044 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9045 "Failed to lift all the low half inputs to the high mask!");
9047 // Do a half shuffle for the low mask.
9048 if (!isNoopShuffleMask(LoMask))
9049 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9050 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9052 // Do a half shuffle with the high mask after shifting its values down.
9053 for (int &M : HiMask)
9056 if (!isNoopShuffleMask(HiMask))
9057 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9058 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9063 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9064 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9065 SDValue V2, ArrayRef<int> Mask,
9066 SelectionDAG &DAG, bool &V1InUse,
9068 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9074 int Size = Mask.size();
9075 int Scale = 16 / Size;
9076 for (int i = 0; i < 16; ++i) {
9077 if (Mask[i / Scale] == -1) {
9078 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9080 const int ZeroMask = 0x80;
9081 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9083 int V2Idx = Mask[i / Scale] < Size
9085 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9086 if (Zeroable[i / Scale])
9087 V1Idx = V2Idx = ZeroMask;
9088 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9089 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9090 V1InUse |= (ZeroMask != V1Idx);
9091 V2InUse |= (ZeroMask != V2Idx);
9096 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9097 DAG.getBitcast(MVT::v16i8, V1),
9098 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9100 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9101 DAG.getBitcast(MVT::v16i8, V2),
9102 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9104 // If we need shuffled inputs from both, blend the two.
9106 if (V1InUse && V2InUse)
9107 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9109 V = V1InUse ? V1 : V2;
9111 // Cast the result back to the correct type.
9112 return DAG.getBitcast(VT, V);
9115 /// \brief Generic lowering of 8-lane i16 shuffles.
9117 /// This handles both single-input shuffles and combined shuffle/blends with
9118 /// two inputs. The single input shuffles are immediately delegated to
9119 /// a dedicated lowering routine.
9121 /// The blends are lowered in one of three fundamental ways. If there are few
9122 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9123 /// of the input is significantly cheaper when lowered as an interleaving of
9124 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9125 /// halves of the inputs separately (making them have relatively few inputs)
9126 /// and then concatenate them.
9127 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9128 const X86Subtarget *Subtarget,
9129 SelectionDAG &DAG) {
9131 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9132 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9133 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9135 ArrayRef<int> OrigMask = SVOp->getMask();
9136 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9137 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9138 MutableArrayRef<int> Mask(MaskStorage);
9140 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9142 // Whenever we can lower this as a zext, that instruction is strictly faster
9143 // than any alternative.
9144 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9145 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9148 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9150 auto isV2 = [](int M) { return M >= 8; };
9152 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9154 if (NumV2Inputs == 0) {
9155 // Check for being able to broadcast a single element.
9156 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9157 Mask, Subtarget, DAG))
9160 // Try to use shift instructions.
9162 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9165 // Use dedicated unpack instructions for masks that match their pattern.
9166 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9167 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9168 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9169 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9171 // Try to use byte rotation instructions.
9172 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9173 Mask, Subtarget, DAG))
9176 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9180 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9181 "All single-input shuffles should be canonicalized to be V1-input "
9184 // Try to use shift instructions.
9186 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9189 // See if we can use SSE4A Extraction / Insertion.
9190 if (Subtarget->hasSSE4A())
9191 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9194 // There are special ways we can lower some single-element blends.
9195 if (NumV2Inputs == 1)
9196 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9197 Mask, Subtarget, DAG))
9200 // We have different paths for blend lowering, but they all must use the
9201 // *exact* same predicate.
9202 bool IsBlendSupported = Subtarget->hasSSE41();
9203 if (IsBlendSupported)
9204 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9208 if (SDValue Masked =
9209 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9212 // Use dedicated unpack instructions for masks that match their pattern.
9213 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9214 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9215 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9216 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9218 // Try to use byte rotation instructions.
9219 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9220 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9223 if (SDValue BitBlend =
9224 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9227 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9231 // If we can't directly blend but can use PSHUFB, that will be better as it
9232 // can both shuffle and set up the inefficient blend.
9233 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9234 bool V1InUse, V2InUse;
9235 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9239 // We can always bit-blend if we have to so the fallback strategy is to
9240 // decompose into single-input permutes and blends.
9241 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9245 /// \brief Check whether a compaction lowering can be done by dropping even
9246 /// elements and compute how many times even elements must be dropped.
9248 /// This handles shuffles which take every Nth element where N is a power of
9249 /// two. Example shuffle masks:
9251 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9252 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9253 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9254 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9255 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9256 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9258 /// Any of these lanes can of course be undef.
9260 /// This routine only supports N <= 3.
9261 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9264 /// \returns N above, or the number of times even elements must be dropped if
9265 /// there is such a number. Otherwise returns zero.
9266 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9267 // Figure out whether we're looping over two inputs or just one.
9268 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9270 // The modulus for the shuffle vector entries is based on whether this is
9271 // a single input or not.
9272 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9273 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9274 "We should only be called with masks with a power-of-2 size!");
9276 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9278 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9279 // and 2^3 simultaneously. This is because we may have ambiguity with
9280 // partially undef inputs.
9281 bool ViableForN[3] = {true, true, true};
9283 for (int i = 0, e = Mask.size(); i < e; ++i) {
9284 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9289 bool IsAnyViable = false;
9290 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9291 if (ViableForN[j]) {
9294 // The shuffle mask must be equal to (i * 2^N) % M.
9295 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9298 ViableForN[j] = false;
9300 // Early exit if we exhaust the possible powers of two.
9305 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9309 // Return 0 as there is no viable power of two.
9313 /// \brief Generic lowering of v16i8 shuffles.
9315 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9316 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9317 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9318 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9320 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9321 const X86Subtarget *Subtarget,
9322 SelectionDAG &DAG) {
9324 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9325 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9326 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9327 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9328 ArrayRef<int> Mask = SVOp->getMask();
9329 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9331 // Try to use shift instructions.
9333 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9336 // Try to use byte rotation instructions.
9337 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9338 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9341 // Try to use a zext lowering.
9342 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9343 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9346 // See if we can use SSE4A Extraction / Insertion.
9347 if (Subtarget->hasSSE4A())
9348 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9352 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9354 // For single-input shuffles, there are some nicer lowering tricks we can use.
9355 if (NumV2Elements == 0) {
9356 // Check for being able to broadcast a single element.
9357 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9358 Mask, Subtarget, DAG))
9361 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9362 // Notably, this handles splat and partial-splat shuffles more efficiently.
9363 // However, it only makes sense if the pre-duplication shuffle simplifies
9364 // things significantly. Currently, this means we need to be able to
9365 // express the pre-duplication shuffle as an i16 shuffle.
9367 // FIXME: We should check for other patterns which can be widened into an
9368 // i16 shuffle as well.
9369 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9370 for (int i = 0; i < 16; i += 2)
9371 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9376 auto tryToWidenViaDuplication = [&]() -> SDValue {
9377 if (!canWidenViaDuplication(Mask))
9379 SmallVector<int, 4> LoInputs;
9380 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9381 [](int M) { return M >= 0 && M < 8; });
9382 std::sort(LoInputs.begin(), LoInputs.end());
9383 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9385 SmallVector<int, 4> HiInputs;
9386 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9387 [](int M) { return M >= 8; });
9388 std::sort(HiInputs.begin(), HiInputs.end());
9389 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9392 bool TargetLo = LoInputs.size() >= HiInputs.size();
9393 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9394 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9396 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9397 SmallDenseMap<int, int, 8> LaneMap;
9398 for (int I : InPlaceInputs) {
9399 PreDupI16Shuffle[I/2] = I/2;
9402 int j = TargetLo ? 0 : 4, je = j + 4;
9403 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9404 // Check if j is already a shuffle of this input. This happens when
9405 // there are two adjacent bytes after we move the low one.
9406 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9407 // If we haven't yet mapped the input, search for a slot into which
9409 while (j < je && PreDupI16Shuffle[j] != -1)
9413 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9416 // Map this input with the i16 shuffle.
9417 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9420 // Update the lane map based on the mapping we ended up with.
9421 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9423 V1 = DAG.getBitcast(
9425 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9426 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9428 // Unpack the bytes to form the i16s that will be shuffled into place.
9429 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9430 MVT::v16i8, V1, V1);
9432 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9433 for (int i = 0; i < 16; ++i)
9434 if (Mask[i] != -1) {
9435 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9436 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9437 if (PostDupI16Shuffle[i / 2] == -1)
9438 PostDupI16Shuffle[i / 2] = MappedMask;
9440 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9441 "Conflicting entrties in the original shuffle!");
9443 return DAG.getBitcast(
9445 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9446 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9448 if (SDValue V = tryToWidenViaDuplication())
9452 if (SDValue Masked =
9453 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9456 // Use dedicated unpack instructions for masks that match their pattern.
9457 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9458 0, 16, 1, 17, 2, 18, 3, 19,
9460 4, 20, 5, 21, 6, 22, 7, 23}))
9461 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9462 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9463 8, 24, 9, 25, 10, 26, 11, 27,
9465 12, 28, 13, 29, 14, 30, 15, 31}))
9466 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9468 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9469 // with PSHUFB. It is important to do this before we attempt to generate any
9470 // blends but after all of the single-input lowerings. If the single input
9471 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9472 // want to preserve that and we can DAG combine any longer sequences into
9473 // a PSHUFB in the end. But once we start blending from multiple inputs,
9474 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9475 // and there are *very* few patterns that would actually be faster than the
9476 // PSHUFB approach because of its ability to zero lanes.
9478 // FIXME: The only exceptions to the above are blends which are exact
9479 // interleavings with direct instructions supporting them. We currently don't
9480 // handle those well here.
9481 if (Subtarget->hasSSSE3()) {
9482 bool V1InUse = false;
9483 bool V2InUse = false;
9485 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9486 DAG, V1InUse, V2InUse);
9488 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9489 // do so. This avoids using them to handle blends-with-zero which is
9490 // important as a single pshufb is significantly faster for that.
9491 if (V1InUse && V2InUse) {
9492 if (Subtarget->hasSSE41())
9493 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9494 Mask, Subtarget, DAG))
9497 // We can use an unpack to do the blending rather than an or in some
9498 // cases. Even though the or may be (very minorly) more efficient, we
9499 // preference this lowering because there are common cases where part of
9500 // the complexity of the shuffles goes away when we do the final blend as
9502 // FIXME: It might be worth trying to detect if the unpack-feeding
9503 // shuffles will both be pshufb, in which case we shouldn't bother with
9505 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9506 DL, MVT::v16i8, V1, V2, Mask, DAG))
9513 // There are special ways we can lower some single-element blends.
9514 if (NumV2Elements == 1)
9515 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9516 Mask, Subtarget, DAG))
9519 if (SDValue BitBlend =
9520 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9523 // Check whether a compaction lowering can be done. This handles shuffles
9524 // which take every Nth element for some even N. See the helper function for
9527 // We special case these as they can be particularly efficiently handled with
9528 // the PACKUSB instruction on x86 and they show up in common patterns of
9529 // rearranging bytes to truncate wide elements.
9530 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9531 // NumEvenDrops is the power of two stride of the elements. Another way of
9532 // thinking about it is that we need to drop the even elements this many
9533 // times to get the original input.
9534 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9536 // First we need to zero all the dropped bytes.
9537 assert(NumEvenDrops <= 3 &&
9538 "No support for dropping even elements more than 3 times.");
9539 // We use the mask type to pick which bytes are preserved based on how many
9540 // elements are dropped.
9541 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9542 SDValue ByteClearMask = DAG.getBitcast(
9543 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9544 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9546 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9548 // Now pack things back together.
9549 V1 = DAG.getBitcast(MVT::v8i16, V1);
9550 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9551 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9552 for (int i = 1; i < NumEvenDrops; ++i) {
9553 Result = DAG.getBitcast(MVT::v8i16, Result);
9554 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9560 // Handle multi-input cases by blending single-input shuffles.
9561 if (NumV2Elements > 0)
9562 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9565 // The fallback path for single-input shuffles widens this into two v8i16
9566 // vectors with unpacks, shuffles those, and then pulls them back together
9570 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9571 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9572 for (int i = 0; i < 16; ++i)
9574 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9576 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9578 SDValue VLoHalf, VHiHalf;
9579 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9580 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9582 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9583 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9584 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9585 [](int M) { return M >= 0 && M % 2 == 1; })) {
9586 // Use a mask to drop the high bytes.
9587 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9588 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9589 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9591 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9592 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9594 // Squash the masks to point directly into VLoHalf.
9595 for (int &M : LoBlendMask)
9598 for (int &M : HiBlendMask)
9602 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9603 // VHiHalf so that we can blend them as i16s.
9604 VLoHalf = DAG.getBitcast(
9605 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9606 VHiHalf = DAG.getBitcast(
9607 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9610 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9611 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9613 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9616 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9618 /// This routine breaks down the specific type of 128-bit shuffle and
9619 /// dispatches to the lowering routines accordingly.
9620 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9621 MVT VT, const X86Subtarget *Subtarget,
9622 SelectionDAG &DAG) {
9623 switch (VT.SimpleTy) {
9625 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9627 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9629 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9631 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9633 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9635 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9638 llvm_unreachable("Unimplemented!");
9642 /// \brief Helper function to test whether a shuffle mask could be
9643 /// simplified by widening the elements being shuffled.
9645 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9646 /// leaves it in an unspecified state.
9648 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9649 /// shuffle masks. The latter have the special property of a '-2' representing
9650 /// a zero-ed lane of a vector.
9651 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9652 SmallVectorImpl<int> &WidenedMask) {
9653 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9654 // If both elements are undef, its trivial.
9655 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9656 WidenedMask.push_back(SM_SentinelUndef);
9660 // Check for an undef mask and a mask value properly aligned to fit with
9661 // a pair of values. If we find such a case, use the non-undef mask's value.
9662 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9663 WidenedMask.push_back(Mask[i + 1] / 2);
9666 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9667 WidenedMask.push_back(Mask[i] / 2);
9671 // When zeroing, we need to spread the zeroing across both lanes to widen.
9672 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9673 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9674 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9675 WidenedMask.push_back(SM_SentinelZero);
9681 // Finally check if the two mask values are adjacent and aligned with
9683 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9684 WidenedMask.push_back(Mask[i] / 2);
9688 // Otherwise we can't safely widen the elements used in this shuffle.
9691 assert(WidenedMask.size() == Mask.size() / 2 &&
9692 "Incorrect size of mask after widening the elements!");
9697 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9699 /// This routine just extracts two subvectors, shuffles them independently, and
9700 /// then concatenates them back together. This should work effectively with all
9701 /// AVX vector shuffle types.
9702 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9703 SDValue V2, ArrayRef<int> Mask,
9704 SelectionDAG &DAG) {
9705 assert(VT.getSizeInBits() >= 256 &&
9706 "Only for 256-bit or wider vector shuffles!");
9707 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9708 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9710 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9711 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9713 int NumElements = VT.getVectorNumElements();
9714 int SplitNumElements = NumElements / 2;
9715 MVT ScalarVT = VT.getScalarType();
9716 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9718 // Rather than splitting build-vectors, just build two narrower build
9719 // vectors. This helps shuffling with splats and zeros.
9720 auto SplitVector = [&](SDValue V) {
9721 while (V.getOpcode() == ISD::BITCAST)
9722 V = V->getOperand(0);
9724 MVT OrigVT = V.getSimpleValueType();
9725 int OrigNumElements = OrigVT.getVectorNumElements();
9726 int OrigSplitNumElements = OrigNumElements / 2;
9727 MVT OrigScalarVT = OrigVT.getScalarType();
9728 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9732 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9734 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9735 DAG.getIntPtrConstant(0, DL));
9736 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9737 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9740 SmallVector<SDValue, 16> LoOps, HiOps;
9741 for (int i = 0; i < OrigSplitNumElements; ++i) {
9742 LoOps.push_back(BV->getOperand(i));
9743 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9745 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9746 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9748 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9749 DAG.getBitcast(SplitVT, HiV));
9752 SDValue LoV1, HiV1, LoV2, HiV2;
9753 std::tie(LoV1, HiV1) = SplitVector(V1);
9754 std::tie(LoV2, HiV2) = SplitVector(V2);
9756 // Now create two 4-way blends of these half-width vectors.
9757 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9758 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9759 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9760 for (int i = 0; i < SplitNumElements; ++i) {
9761 int M = HalfMask[i];
9762 if (M >= NumElements) {
9763 if (M >= NumElements + SplitNumElements)
9767 V2BlendMask.push_back(M - NumElements);
9768 V1BlendMask.push_back(-1);
9769 BlendMask.push_back(SplitNumElements + i);
9770 } else if (M >= 0) {
9771 if (M >= SplitNumElements)
9775 V2BlendMask.push_back(-1);
9776 V1BlendMask.push_back(M);
9777 BlendMask.push_back(i);
9779 V2BlendMask.push_back(-1);
9780 V1BlendMask.push_back(-1);
9781 BlendMask.push_back(-1);
9785 // Because the lowering happens after all combining takes place, we need to
9786 // manually combine these blend masks as much as possible so that we create
9787 // a minimal number of high-level vector shuffle nodes.
9789 // First try just blending the halves of V1 or V2.
9790 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9791 return DAG.getUNDEF(SplitVT);
9792 if (!UseLoV2 && !UseHiV2)
9793 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9794 if (!UseLoV1 && !UseHiV1)
9795 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9797 SDValue V1Blend, V2Blend;
9798 if (UseLoV1 && UseHiV1) {
9800 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9802 // We only use half of V1 so map the usage down into the final blend mask.
9803 V1Blend = UseLoV1 ? LoV1 : HiV1;
9804 for (int i = 0; i < SplitNumElements; ++i)
9805 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9806 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9808 if (UseLoV2 && UseHiV2) {
9810 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9812 // We only use half of V2 so map the usage down into the final blend mask.
9813 V2Blend = UseLoV2 ? LoV2 : HiV2;
9814 for (int i = 0; i < SplitNumElements; ++i)
9815 if (BlendMask[i] >= SplitNumElements)
9816 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9818 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9820 SDValue Lo = HalfBlend(LoMask);
9821 SDValue Hi = HalfBlend(HiMask);
9822 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9825 /// \brief Either split a vector in halves or decompose the shuffles and the
9828 /// This is provided as a good fallback for many lowerings of non-single-input
9829 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9830 /// between splitting the shuffle into 128-bit components and stitching those
9831 /// back together vs. extracting the single-input shuffles and blending those
9833 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9834 SDValue V2, ArrayRef<int> Mask,
9835 SelectionDAG &DAG) {
9836 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9837 "lower single-input shuffles as it "
9838 "could then recurse on itself.");
9839 int Size = Mask.size();
9841 // If this can be modeled as a broadcast of two elements followed by a blend,
9842 // prefer that lowering. This is especially important because broadcasts can
9843 // often fold with memory operands.
9844 auto DoBothBroadcast = [&] {
9845 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9848 if (V2BroadcastIdx == -1)
9849 V2BroadcastIdx = M - Size;
9850 else if (M - Size != V2BroadcastIdx)
9852 } else if (M >= 0) {
9853 if (V1BroadcastIdx == -1)
9855 else if (M != V1BroadcastIdx)
9860 if (DoBothBroadcast())
9861 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9864 // If the inputs all stem from a single 128-bit lane of each input, then we
9865 // split them rather than blending because the split will decompose to
9866 // unusually few instructions.
9867 int LaneCount = VT.getSizeInBits() / 128;
9868 int LaneSize = Size / LaneCount;
9869 SmallBitVector LaneInputs[2];
9870 LaneInputs[0].resize(LaneCount, false);
9871 LaneInputs[1].resize(LaneCount, false);
9872 for (int i = 0; i < Size; ++i)
9874 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9875 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9876 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9878 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9879 // that the decomposed single-input shuffles don't end up here.
9880 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9883 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9884 /// a permutation and blend of those lanes.
9886 /// This essentially blends the out-of-lane inputs to each lane into the lane
9887 /// from a permuted copy of the vector. This lowering strategy results in four
9888 /// instructions in the worst case for a single-input cross lane shuffle which
9889 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9890 /// of. Special cases for each particular shuffle pattern should be handled
9891 /// prior to trying this lowering.
9892 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9893 SDValue V1, SDValue V2,
9895 SelectionDAG &DAG) {
9896 // FIXME: This should probably be generalized for 512-bit vectors as well.
9897 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9898 int LaneSize = Mask.size() / 2;
9900 // If there are only inputs from one 128-bit lane, splitting will in fact be
9901 // less expensive. The flags track whether the given lane contains an element
9902 // that crosses to another lane.
9903 bool LaneCrossing[2] = {false, false};
9904 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9905 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9906 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9907 if (!LaneCrossing[0] || !LaneCrossing[1])
9908 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9910 if (isSingleInputShuffleMask(Mask)) {
9911 SmallVector<int, 32> FlippedBlendMask;
9912 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9913 FlippedBlendMask.push_back(
9914 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9916 : Mask[i] % LaneSize +
9917 (i / LaneSize) * LaneSize + Size));
9919 // Flip the vector, and blend the results which should now be in-lane. The
9920 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9921 // 5 for the high source. The value 3 selects the high half of source 2 and
9922 // the value 2 selects the low half of source 2. We only use source 2 to
9923 // allow folding it into a memory operand.
9924 unsigned PERMMask = 3 | 2 << 4;
9925 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9926 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9927 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9930 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9931 // will be handled by the above logic and a blend of the results, much like
9932 // other patterns in AVX.
9933 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9936 /// \brief Handle lowering 2-lane 128-bit shuffles.
9937 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9938 SDValue V2, ArrayRef<int> Mask,
9939 const X86Subtarget *Subtarget,
9940 SelectionDAG &DAG) {
9941 // TODO: If minimizing size and one of the inputs is a zero vector and the
9942 // the zero vector has only one use, we could use a VPERM2X128 to save the
9943 // instruction bytes needed to explicitly generate the zero vector.
9945 // Blends are faster and handle all the non-lane-crossing cases.
9946 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9950 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9951 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9953 // If either input operand is a zero vector, use VPERM2X128 because its mask
9954 // allows us to replace the zero input with an implicit zero.
9955 if (!IsV1Zero && !IsV2Zero) {
9956 // Check for patterns which can be matched with a single insert of a 128-bit
9958 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9959 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9960 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9961 VT.getVectorNumElements() / 2);
9962 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9963 DAG.getIntPtrConstant(0, DL));
9964 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9965 OnlyUsesV1 ? V1 : V2,
9966 DAG.getIntPtrConstant(0, DL));
9967 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9971 // Otherwise form a 128-bit permutation. After accounting for undefs,
9972 // convert the 64-bit shuffle mask selection values into 128-bit
9973 // selection bits by dividing the indexes by 2 and shifting into positions
9974 // defined by a vperm2*128 instruction's immediate control byte.
9976 // The immediate permute control byte looks like this:
9977 // [1:0] - select 128 bits from sources for low half of destination
9979 // [3] - zero low half of destination
9980 // [5:4] - select 128 bits from sources for high half of destination
9982 // [7] - zero high half of destination
9984 int MaskLO = Mask[0];
9985 if (MaskLO == SM_SentinelUndef)
9986 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9988 int MaskHI = Mask[2];
9989 if (MaskHI == SM_SentinelUndef)
9990 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9992 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9994 // If either input is a zero vector, replace it with an undef input.
9995 // Shuffle mask values < 4 are selecting elements of V1.
9996 // Shuffle mask values >= 4 are selecting elements of V2.
9997 // Adjust each half of the permute mask by clearing the half that was
9998 // selecting the zero vector and setting the zero mask bit.
10000 V1 = DAG.getUNDEF(VT);
10002 PermMask = (PermMask & 0xf0) | 0x08;
10004 PermMask = (PermMask & 0x0f) | 0x80;
10007 V2 = DAG.getUNDEF(VT);
10009 PermMask = (PermMask & 0xf0) | 0x08;
10011 PermMask = (PermMask & 0x0f) | 0x80;
10014 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10015 DAG.getConstant(PermMask, DL, MVT::i8));
10018 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10019 /// shuffling each lane.
10021 /// This will only succeed when the result of fixing the 128-bit lanes results
10022 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10023 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10024 /// the lane crosses early and then use simpler shuffles within each lane.
10026 /// FIXME: It might be worthwhile at some point to support this without
10027 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10028 /// in x86 only floating point has interesting non-repeating shuffles, and even
10029 /// those are still *marginally* more expensive.
10030 static SDValue lowerVectorShuffleByMerging128BitLanes(
10031 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10032 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10033 assert(!isSingleInputShuffleMask(Mask) &&
10034 "This is only useful with multiple inputs.");
10036 int Size = Mask.size();
10037 int LaneSize = 128 / VT.getScalarSizeInBits();
10038 int NumLanes = Size / LaneSize;
10039 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10041 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10042 // check whether the in-128-bit lane shuffles share a repeating pattern.
10043 SmallVector<int, 4> Lanes;
10044 Lanes.resize(NumLanes, -1);
10045 SmallVector<int, 4> InLaneMask;
10046 InLaneMask.resize(LaneSize, -1);
10047 for (int i = 0; i < Size; ++i) {
10051 int j = i / LaneSize;
10053 if (Lanes[j] < 0) {
10054 // First entry we've seen for this lane.
10055 Lanes[j] = Mask[i] / LaneSize;
10056 } else if (Lanes[j] != Mask[i] / LaneSize) {
10057 // This doesn't match the lane selected previously!
10061 // Check that within each lane we have a consistent shuffle mask.
10062 int k = i % LaneSize;
10063 if (InLaneMask[k] < 0) {
10064 InLaneMask[k] = Mask[i] % LaneSize;
10065 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10066 // This doesn't fit a repeating in-lane mask.
10071 // First shuffle the lanes into place.
10072 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10073 VT.getSizeInBits() / 64);
10074 SmallVector<int, 8> LaneMask;
10075 LaneMask.resize(NumLanes * 2, -1);
10076 for (int i = 0; i < NumLanes; ++i)
10077 if (Lanes[i] >= 0) {
10078 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10079 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10082 V1 = DAG.getBitcast(LaneVT, V1);
10083 V2 = DAG.getBitcast(LaneVT, V2);
10084 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10086 // Cast it back to the type we actually want.
10087 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10089 // Now do a simple shuffle that isn't lane crossing.
10090 SmallVector<int, 8> NewMask;
10091 NewMask.resize(Size, -1);
10092 for (int i = 0; i < Size; ++i)
10094 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10095 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10096 "Must not introduce lane crosses at this point!");
10098 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10101 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10104 /// This returns true if the elements from a particular input are already in the
10105 /// slot required by the given mask and require no permutation.
10106 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10107 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10108 int Size = Mask.size();
10109 for (int i = 0; i < Size; ++i)
10110 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10116 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10117 ArrayRef<int> Mask, SDValue V1,
10118 SDValue V2, SelectionDAG &DAG) {
10120 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10121 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10122 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10123 int NumElts = VT.getVectorNumElements();
10124 bool ShufpdMask = true;
10125 bool CommutableMask = true;
10126 unsigned Immediate = 0;
10127 for (int i = 0; i < NumElts; ++i) {
10130 int Val = (i & 6) + NumElts * (i & 1);
10131 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10132 if (Mask[i] < Val || Mask[i] > Val + 1)
10133 ShufpdMask = false;
10134 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10135 CommutableMask = false;
10136 Immediate |= (Mask[i] % 2) << i;
10139 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10140 DAG.getConstant(Immediate, DL, MVT::i8));
10141 if (CommutableMask)
10142 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10143 DAG.getConstant(Immediate, DL, MVT::i8));
10147 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10149 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10150 /// isn't available.
10151 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10152 const X86Subtarget *Subtarget,
10153 SelectionDAG &DAG) {
10155 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10156 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10157 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10158 ArrayRef<int> Mask = SVOp->getMask();
10159 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10161 SmallVector<int, 4> WidenedMask;
10162 if (canWidenShuffleElements(Mask, WidenedMask))
10163 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10166 if (isSingleInputShuffleMask(Mask)) {
10167 // Check for being able to broadcast a single element.
10168 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10169 Mask, Subtarget, DAG))
10172 // Use low duplicate instructions for masks that match their pattern.
10173 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10174 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10176 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10177 // Non-half-crossing single input shuffles can be lowerid with an
10178 // interleaved permutation.
10179 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10180 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10181 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10182 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10185 // With AVX2 we have direct support for this permutation.
10186 if (Subtarget->hasAVX2())
10187 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10188 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10190 // Otherwise, fall back.
10191 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10195 // X86 has dedicated unpack instructions that can handle specific blend
10196 // operations: UNPCKH and UNPCKL.
10197 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10198 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10199 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10200 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10201 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10202 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10203 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10204 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10206 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10210 // Check if the blend happens to exactly fit that of SHUFPD.
10212 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10215 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10216 // shuffle. However, if we have AVX2 and either inputs are already in place,
10217 // we will be able to shuffle even across lanes the other input in a single
10218 // instruction so skip this pattern.
10219 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10220 isShuffleMaskInputInPlace(1, Mask))))
10221 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10222 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10225 // If we have AVX2 then we always want to lower with a blend because an v4 we
10226 // can fully permute the elements.
10227 if (Subtarget->hasAVX2())
10228 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10231 // Otherwise fall back on generic lowering.
10232 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10235 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10237 /// This routine is only called when we have AVX2 and thus a reasonable
10238 /// instruction set for v4i64 shuffling..
10239 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10240 const X86Subtarget *Subtarget,
10241 SelectionDAG &DAG) {
10243 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10244 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10245 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10246 ArrayRef<int> Mask = SVOp->getMask();
10247 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10248 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10250 SmallVector<int, 4> WidenedMask;
10251 if (canWidenShuffleElements(Mask, WidenedMask))
10252 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10255 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10259 // Check for being able to broadcast a single element.
10260 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10261 Mask, Subtarget, DAG))
10264 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10265 // use lower latency instructions that will operate on both 128-bit lanes.
10266 SmallVector<int, 2> RepeatedMask;
10267 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10268 if (isSingleInputShuffleMask(Mask)) {
10269 int PSHUFDMask[] = {-1, -1, -1, -1};
10270 for (int i = 0; i < 2; ++i)
10271 if (RepeatedMask[i] >= 0) {
10272 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10273 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10275 return DAG.getBitcast(
10277 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10278 DAG.getBitcast(MVT::v8i32, V1),
10279 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10283 // AVX2 provides a direct instruction for permuting a single input across
10285 if (isSingleInputShuffleMask(Mask))
10286 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10287 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10289 // Try to use shift instructions.
10290 if (SDValue Shift =
10291 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10294 // Use dedicated unpack instructions for masks that match their pattern.
10295 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10296 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10297 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10298 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10299 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10300 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10301 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10302 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10304 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10305 // shuffle. However, if we have AVX2 and either inputs are already in place,
10306 // we will be able to shuffle even across lanes the other input in a single
10307 // instruction so skip this pattern.
10308 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10309 isShuffleMaskInputInPlace(1, Mask))))
10310 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10311 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10314 // Otherwise fall back on generic blend lowering.
10315 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10319 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10321 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10322 /// isn't available.
10323 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10324 const X86Subtarget *Subtarget,
10325 SelectionDAG &DAG) {
10327 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10328 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10329 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10330 ArrayRef<int> Mask = SVOp->getMask();
10331 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10333 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10337 // Check for being able to broadcast a single element.
10338 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10339 Mask, Subtarget, DAG))
10342 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10343 // options to efficiently lower the shuffle.
10344 SmallVector<int, 4> RepeatedMask;
10345 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10346 assert(RepeatedMask.size() == 4 &&
10347 "Repeated masks must be half the mask width!");
10349 // Use even/odd duplicate instructions for masks that match their pattern.
10350 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10351 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10352 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10353 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10355 if (isSingleInputShuffleMask(Mask))
10356 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10357 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10359 // Use dedicated unpack instructions for masks that match their pattern.
10360 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10361 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10362 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10363 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10364 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10365 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10366 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10367 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10369 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10370 // have already handled any direct blends. We also need to squash the
10371 // repeated mask into a simulated v4f32 mask.
10372 for (int i = 0; i < 4; ++i)
10373 if (RepeatedMask[i] >= 8)
10374 RepeatedMask[i] -= 4;
10375 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10378 // If we have a single input shuffle with different shuffle patterns in the
10379 // two 128-bit lanes use the variable mask to VPERMILPS.
10380 if (isSingleInputShuffleMask(Mask)) {
10381 SDValue VPermMask[8];
10382 for (int i = 0; i < 8; ++i)
10383 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10384 : DAG.getConstant(Mask[i], DL, MVT::i32);
10385 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10386 return DAG.getNode(
10387 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10388 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10390 if (Subtarget->hasAVX2())
10391 return DAG.getNode(
10392 X86ISD::VPERMV, DL, MVT::v8f32,
10393 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10394 MVT::v8i32, VPermMask)),
10397 // Otherwise, fall back.
10398 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10402 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10404 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10405 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10408 // If we have AVX2 then we always want to lower with a blend because at v8 we
10409 // can fully permute the elements.
10410 if (Subtarget->hasAVX2())
10411 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10414 // Otherwise fall back on generic lowering.
10415 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10418 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10420 /// This routine is only called when we have AVX2 and thus a reasonable
10421 /// instruction set for v8i32 shuffling..
10422 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10423 const X86Subtarget *Subtarget,
10424 SelectionDAG &DAG) {
10426 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10427 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10428 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10429 ArrayRef<int> Mask = SVOp->getMask();
10430 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10431 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10433 // Whenever we can lower this as a zext, that instruction is strictly faster
10434 // than any alternative. It also allows us to fold memory operands into the
10435 // shuffle in many cases.
10436 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10437 Mask, Subtarget, DAG))
10440 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10444 // Check for being able to broadcast a single element.
10445 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10446 Mask, Subtarget, DAG))
10449 // If the shuffle mask is repeated in each 128-bit lane we can use more
10450 // efficient instructions that mirror the shuffles across the two 128-bit
10452 SmallVector<int, 4> RepeatedMask;
10453 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10454 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10455 if (isSingleInputShuffleMask(Mask))
10456 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10457 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10459 // Use dedicated unpack instructions for masks that match their pattern.
10460 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10461 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10462 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10463 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10464 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10465 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10466 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10467 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10470 // Try to use shift instructions.
10471 if (SDValue Shift =
10472 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10475 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10476 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10479 // If the shuffle patterns aren't repeated but it is a single input, directly
10480 // generate a cross-lane VPERMD instruction.
10481 if (isSingleInputShuffleMask(Mask)) {
10482 SDValue VPermMask[8];
10483 for (int i = 0; i < 8; ++i)
10484 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10485 : DAG.getConstant(Mask[i], DL, MVT::i32);
10486 return DAG.getNode(
10487 X86ISD::VPERMV, DL, MVT::v8i32,
10488 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10491 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10493 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10494 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10497 // Otherwise fall back on generic blend lowering.
10498 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10502 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10504 /// This routine is only called when we have AVX2 and thus a reasonable
10505 /// instruction set for v16i16 shuffling..
10506 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10507 const X86Subtarget *Subtarget,
10508 SelectionDAG &DAG) {
10510 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10511 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10512 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10513 ArrayRef<int> Mask = SVOp->getMask();
10514 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10515 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10517 // Whenever we can lower this as a zext, that instruction is strictly faster
10518 // than any alternative. It also allows us to fold memory operands into the
10519 // shuffle in many cases.
10520 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10521 Mask, Subtarget, DAG))
10524 // Check for being able to broadcast a single element.
10525 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10526 Mask, Subtarget, DAG))
10529 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10533 // Use dedicated unpack instructions for masks that match their pattern.
10534 if (isShuffleEquivalent(V1, V2, Mask,
10535 {// First 128-bit lane:
10536 0, 16, 1, 17, 2, 18, 3, 19,
10537 // Second 128-bit lane:
10538 8, 24, 9, 25, 10, 26, 11, 27}))
10539 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10540 if (isShuffleEquivalent(V1, V2, Mask,
10541 {// First 128-bit lane:
10542 4, 20, 5, 21, 6, 22, 7, 23,
10543 // Second 128-bit lane:
10544 12, 28, 13, 29, 14, 30, 15, 31}))
10545 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10547 // Try to use shift instructions.
10548 if (SDValue Shift =
10549 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10552 // Try to use byte rotation instructions.
10553 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10554 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10557 if (isSingleInputShuffleMask(Mask)) {
10558 // There are no generalized cross-lane shuffle operations available on i16
10560 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10561 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10564 SmallVector<int, 8> RepeatedMask;
10565 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10566 // As this is a single-input shuffle, the repeated mask should be
10567 // a strictly valid v8i16 mask that we can pass through to the v8i16
10568 // lowering to handle even the v16 case.
10569 return lowerV8I16GeneralSingleInputVectorShuffle(
10570 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10573 SDValue PSHUFBMask[32];
10574 for (int i = 0; i < 16; ++i) {
10575 if (Mask[i] == -1) {
10576 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10580 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10581 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10582 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10583 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10585 return DAG.getBitcast(MVT::v16i16,
10586 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10587 DAG.getBitcast(MVT::v32i8, V1),
10588 DAG.getNode(ISD::BUILD_VECTOR, DL,
10589 MVT::v32i8, PSHUFBMask)));
10592 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10594 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10595 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10598 // Otherwise fall back on generic lowering.
10599 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10602 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10604 /// This routine is only called when we have AVX2 and thus a reasonable
10605 /// instruction set for v32i8 shuffling..
10606 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10607 const X86Subtarget *Subtarget,
10608 SelectionDAG &DAG) {
10610 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10611 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10612 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10613 ArrayRef<int> Mask = SVOp->getMask();
10614 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10615 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10617 // Whenever we can lower this as a zext, that instruction is strictly faster
10618 // than any alternative. It also allows us to fold memory operands into the
10619 // shuffle in many cases.
10620 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10621 Mask, Subtarget, DAG))
10624 // Check for being able to broadcast a single element.
10625 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10626 Mask, Subtarget, DAG))
10629 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10633 // Use dedicated unpack instructions for masks that match their pattern.
10634 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10636 if (isShuffleEquivalent(
10638 {// First 128-bit lane:
10639 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10640 // Second 128-bit lane:
10641 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10642 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10643 if (isShuffleEquivalent(
10645 {// First 128-bit lane:
10646 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10647 // Second 128-bit lane:
10648 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10649 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10651 // Try to use shift instructions.
10652 if (SDValue Shift =
10653 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10656 // Try to use byte rotation instructions.
10657 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10658 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10661 if (isSingleInputShuffleMask(Mask)) {
10662 // There are no generalized cross-lane shuffle operations available on i8
10664 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10665 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10668 SDValue PSHUFBMask[32];
10669 for (int i = 0; i < 32; ++i)
10672 ? DAG.getUNDEF(MVT::i8)
10673 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10676 return DAG.getNode(
10677 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10678 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10681 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10683 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10684 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10687 // Otherwise fall back on generic lowering.
10688 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10691 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10693 /// This routine either breaks down the specific type of a 256-bit x86 vector
10694 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10695 /// together based on the available instructions.
10696 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10697 MVT VT, const X86Subtarget *Subtarget,
10698 SelectionDAG &DAG) {
10700 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10701 ArrayRef<int> Mask = SVOp->getMask();
10703 // If we have a single input to the zero element, insert that into V1 if we
10704 // can do so cheaply.
10705 int NumElts = VT.getVectorNumElements();
10706 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10707 return M >= NumElts;
10710 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10711 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10712 DL, VT, V1, V2, Mask, Subtarget, DAG))
10715 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10716 // can check for those subtargets here and avoid much of the subtarget
10717 // querying in the per-vector-type lowering routines. With AVX1 we have
10718 // essentially *zero* ability to manipulate a 256-bit vector with integer
10719 // types. Since we'll use floating point types there eventually, just
10720 // immediately cast everything to a float and operate entirely in that domain.
10721 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10722 int ElementBits = VT.getScalarSizeInBits();
10723 if (ElementBits < 32)
10724 // No floating point type available, decompose into 128-bit vectors.
10725 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10727 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10728 VT.getVectorNumElements());
10729 V1 = DAG.getBitcast(FpVT, V1);
10730 V2 = DAG.getBitcast(FpVT, V2);
10731 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10734 switch (VT.SimpleTy) {
10736 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10738 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10740 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10742 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10744 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10746 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10749 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10753 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10754 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10755 ArrayRef<int> Mask,
10756 SDValue V1, SDValue V2,
10757 SelectionDAG &DAG) {
10758 assert(VT.getScalarSizeInBits() == 64 &&
10759 "Unexpected element type size for 128bit shuffle.");
10761 // To handle 256 bit vector requires VLX and most probably
10762 // function lowerV2X128VectorShuffle() is better solution.
10763 assert(VT.getSizeInBits() == 512 &&
10764 "Unexpected vector size for 128bit shuffle.");
10766 SmallVector<int, 4> WidenedMask;
10767 if (!canWidenShuffleElements(Mask, WidenedMask))
10770 // Form a 128-bit permutation.
10771 // Convert the 64-bit shuffle mask selection values into 128-bit selection
10772 // bits defined by a vshuf64x2 instruction's immediate control byte.
10773 unsigned PermMask = 0, Imm = 0;
10774 unsigned ControlBitsNum = WidenedMask.size() / 2;
10776 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10777 if (WidenedMask[i] == SM_SentinelZero)
10780 // Use first element in place of undef mask.
10781 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10782 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10785 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10786 DAG.getConstant(PermMask, DL, MVT::i8));
10789 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10790 ArrayRef<int> Mask, SDValue V1,
10791 SDValue V2, SelectionDAG &DAG) {
10793 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10795 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10796 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10798 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10799 if (isSingleInputShuffleMask(Mask))
10800 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10802 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10805 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10806 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10807 const X86Subtarget *Subtarget,
10808 SelectionDAG &DAG) {
10810 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10811 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10812 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10813 ArrayRef<int> Mask = SVOp->getMask();
10814 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10816 if (SDValue Shuf128 =
10817 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10820 if (SDValue Unpck =
10821 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10824 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10827 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10828 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10829 const X86Subtarget *Subtarget,
10830 SelectionDAG &DAG) {
10832 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10833 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10834 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10835 ArrayRef<int> Mask = SVOp->getMask();
10836 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10838 if (SDValue Unpck =
10839 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10842 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10845 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10846 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10847 const X86Subtarget *Subtarget,
10848 SelectionDAG &DAG) {
10850 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10851 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10852 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10853 ArrayRef<int> Mask = SVOp->getMask();
10854 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10856 if (SDValue Shuf128 =
10857 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10860 if (SDValue Unpck =
10861 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10864 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10867 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10868 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10869 const X86Subtarget *Subtarget,
10870 SelectionDAG &DAG) {
10872 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10873 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10874 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10875 ArrayRef<int> Mask = SVOp->getMask();
10876 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10878 if (SDValue Unpck =
10879 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10882 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10885 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10886 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10887 const X86Subtarget *Subtarget,
10888 SelectionDAG &DAG) {
10890 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10891 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10893 ArrayRef<int> Mask = SVOp->getMask();
10894 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10895 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10897 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10900 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10901 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10902 const X86Subtarget *Subtarget,
10903 SelectionDAG &DAG) {
10905 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10906 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10907 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10908 ArrayRef<int> Mask = SVOp->getMask();
10909 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10910 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10912 // FIXME: Implement direct support for this type!
10913 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10916 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10918 /// This routine either breaks down the specific type of a 512-bit x86 vector
10919 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10920 /// together based on the available instructions.
10921 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10922 MVT VT, const X86Subtarget *Subtarget,
10923 SelectionDAG &DAG) {
10925 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10926 ArrayRef<int> Mask = SVOp->getMask();
10927 assert(Subtarget->hasAVX512() &&
10928 "Cannot lower 512-bit vectors w/ basic ISA!");
10930 // Check for being able to broadcast a single element.
10931 if (SDValue Broadcast =
10932 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10935 // Dispatch to each element type for lowering. If we don't have supprot for
10936 // specific element type shuffles at 512 bits, immediately split them and
10937 // lower them. Each lowering routine of a given type is allowed to assume that
10938 // the requisite ISA extensions for that element type are available.
10939 switch (VT.SimpleTy) {
10941 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10943 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10945 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10947 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10949 if (Subtarget->hasBWI())
10950 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10953 if (Subtarget->hasBWI())
10954 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10958 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10961 // Otherwise fall back on splitting.
10962 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10965 // Lower vXi1 vector shuffles.
10966 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10967 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10968 // vector, shuffle and then truncate it back.
10969 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10970 MVT VT, const X86Subtarget *Subtarget,
10971 SelectionDAG &DAG) {
10973 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10974 ArrayRef<int> Mask = SVOp->getMask();
10975 assert(Subtarget->hasAVX512() &&
10976 "Cannot lower 512-bit vectors w/o basic ISA!");
10978 switch (VT.SimpleTy) {
10980 assert(false && "Expected a vector of i1 elements");
10983 ExtVT = MVT::v2i64;
10986 ExtVT = MVT::v4i32;
10989 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10992 ExtVT = MVT::v16i32;
10995 ExtVT = MVT::v32i16;
10998 ExtVT = MVT::v64i8;
11002 if (ISD::isBuildVectorAllZeros(V1.getNode()))
11003 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11004 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11005 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11007 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11010 V2 = DAG.getUNDEF(ExtVT);
11011 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11012 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11013 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11014 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11016 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11017 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11018 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11020 /// \brief Top-level lowering for x86 vector shuffles.
11022 /// This handles decomposition, canonicalization, and lowering of all x86
11023 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11024 /// above in helper routines. The canonicalization attempts to widen shuffles
11025 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11026 /// s.t. only one of the two inputs needs to be tested, etc.
11027 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11028 SelectionDAG &DAG) {
11029 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11030 ArrayRef<int> Mask = SVOp->getMask();
11031 SDValue V1 = Op.getOperand(0);
11032 SDValue V2 = Op.getOperand(1);
11033 MVT VT = Op.getSimpleValueType();
11034 int NumElements = VT.getVectorNumElements();
11036 bool Is1BitVector = (VT.getScalarType() == MVT::i1);
11038 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11039 "Can't lower MMX shuffles");
11041 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11042 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11043 if (V1IsUndef && V2IsUndef)
11044 return DAG.getUNDEF(VT);
11046 // When we create a shuffle node we put the UNDEF node to second operand,
11047 // but in some cases the first operand may be transformed to UNDEF.
11048 // In this case we should just commute the node.
11050 return DAG.getCommutedVectorShuffle(*SVOp);
11052 // Check for non-undef masks pointing at an undef vector and make the masks
11053 // undef as well. This makes it easier to match the shuffle based solely on
11057 if (M >= NumElements) {
11058 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11059 for (int &M : NewMask)
11060 if (M >= NumElements)
11062 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11065 // We actually see shuffles that are entirely re-arrangements of a set of
11066 // zero inputs. This mostly happens while decomposing complex shuffles into
11067 // simple ones. Directly lower these as a buildvector of zeros.
11068 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11069 if (Zeroable.all())
11070 return getZeroVector(VT, Subtarget, DAG, dl);
11072 // Try to collapse shuffles into using a vector type with fewer elements but
11073 // wider element types. We cap this to not form integers or floating point
11074 // elements wider than 64 bits, but it might be interesting to form i128
11075 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11076 SmallVector<int, 16> WidenedMask;
11077 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11078 canWidenShuffleElements(Mask, WidenedMask)) {
11079 MVT NewEltVT = VT.isFloatingPoint()
11080 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11081 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11082 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11083 // Make sure that the new vector type is legal. For example, v2f64 isn't
11085 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11086 V1 = DAG.getBitcast(NewVT, V1);
11087 V2 = DAG.getBitcast(NewVT, V2);
11088 return DAG.getBitcast(
11089 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11093 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11094 for (int M : SVOp->getMask())
11096 ++NumUndefElements;
11097 else if (M < NumElements)
11102 // Commute the shuffle as needed such that more elements come from V1 than
11103 // V2. This allows us to match the shuffle pattern strictly on how many
11104 // elements come from V1 without handling the symmetric cases.
11105 if (NumV2Elements > NumV1Elements)
11106 return DAG.getCommutedVectorShuffle(*SVOp);
11108 // When the number of V1 and V2 elements are the same, try to minimize the
11109 // number of uses of V2 in the low half of the vector. When that is tied,
11110 // ensure that the sum of indices for V1 is equal to or lower than the sum
11111 // indices for V2. When those are equal, try to ensure that the number of odd
11112 // indices for V1 is lower than the number of odd indices for V2.
11113 if (NumV1Elements == NumV2Elements) {
11114 int LowV1Elements = 0, LowV2Elements = 0;
11115 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11116 if (M >= NumElements)
11120 if (LowV2Elements > LowV1Elements) {
11121 return DAG.getCommutedVectorShuffle(*SVOp);
11122 } else if (LowV2Elements == LowV1Elements) {
11123 int SumV1Indices = 0, SumV2Indices = 0;
11124 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11125 if (SVOp->getMask()[i] >= NumElements)
11127 else if (SVOp->getMask()[i] >= 0)
11129 if (SumV2Indices < SumV1Indices) {
11130 return DAG.getCommutedVectorShuffle(*SVOp);
11131 } else if (SumV2Indices == SumV1Indices) {
11132 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11133 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11134 if (SVOp->getMask()[i] >= NumElements)
11135 NumV2OddIndices += i % 2;
11136 else if (SVOp->getMask()[i] >= 0)
11137 NumV1OddIndices += i % 2;
11138 if (NumV2OddIndices < NumV1OddIndices)
11139 return DAG.getCommutedVectorShuffle(*SVOp);
11144 // For each vector width, delegate to a specialized lowering routine.
11145 if (VT.getSizeInBits() == 128)
11146 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11148 if (VT.getSizeInBits() == 256)
11149 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11151 if (VT.getSizeInBits() == 512)
11152 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11155 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11156 llvm_unreachable("Unimplemented!");
11159 // This function assumes its argument is a BUILD_VECTOR of constants or
11160 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11162 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11163 unsigned &MaskValue) {
11165 unsigned NumElems = BuildVector->getNumOperands();
11167 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11168 // We don't handle the >2 lanes case right now.
11169 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11173 unsigned NumElemsInLane = NumElems / NumLanes;
11175 // Blend for v16i16 should be symmetric for the both lanes.
11176 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11177 SDValue EltCond = BuildVector->getOperand(i);
11178 SDValue SndLaneEltCond =
11179 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11181 int Lane1Cond = -1, Lane2Cond = -1;
11182 if (isa<ConstantSDNode>(EltCond))
11183 Lane1Cond = !isZero(EltCond);
11184 if (isa<ConstantSDNode>(SndLaneEltCond))
11185 Lane2Cond = !isZero(SndLaneEltCond);
11187 unsigned LaneMask = 0;
11188 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11189 // Lane1Cond != 0, means we want the first argument.
11190 // Lane1Cond == 0, means we want the second argument.
11191 // The encoding of this argument is 0 for the first argument, 1
11192 // for the second. Therefore, invert the condition.
11193 LaneMask = !Lane1Cond << i;
11194 else if (Lane1Cond < 0)
11195 LaneMask = !Lane2Cond << i;
11199 MaskValue |= LaneMask;
11201 MaskValue |= LaneMask << NumElemsInLane;
11206 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11207 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11208 const X86Subtarget *Subtarget,
11209 SelectionDAG &DAG) {
11210 SDValue Cond = Op.getOperand(0);
11211 SDValue LHS = Op.getOperand(1);
11212 SDValue RHS = Op.getOperand(2);
11214 MVT VT = Op.getSimpleValueType();
11216 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11218 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11220 // Only non-legal VSELECTs reach this lowering, convert those into generic
11221 // shuffles and re-use the shuffle lowering path for blends.
11222 SmallVector<int, 32> Mask;
11223 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11224 SDValue CondElt = CondBV->getOperand(i);
11226 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11228 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11231 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11232 // A vselect where all conditions and data are constants can be optimized into
11233 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11234 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11235 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11236 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11239 // Try to lower this to a blend-style vector shuffle. This can handle all
11240 // constant condition cases.
11241 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11244 // Variable blends are only legal from SSE4.1 onward.
11245 if (!Subtarget->hasSSE41())
11248 // Only some types will be legal on some subtargets. If we can emit a legal
11249 // VSELECT-matching blend, return Op, and but if we need to expand, return
11251 switch (Op.getSimpleValueType().SimpleTy) {
11253 // Most of the vector types have blends past SSE4.1.
11257 // The byte blends for AVX vectors were introduced only in AVX2.
11258 if (Subtarget->hasAVX2())
11265 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11266 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11269 // FIXME: We should custom lower this by fixing the condition and using i8
11275 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11276 MVT VT = Op.getSimpleValueType();
11279 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11282 if (VT.getSizeInBits() == 8) {
11283 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11284 Op.getOperand(0), Op.getOperand(1));
11285 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11286 DAG.getValueType(VT));
11287 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11290 if (VT.getSizeInBits() == 16) {
11291 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11292 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11294 return DAG.getNode(
11295 ISD::TRUNCATE, dl, MVT::i16,
11296 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11297 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11298 Op.getOperand(1)));
11299 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11300 Op.getOperand(0), Op.getOperand(1));
11301 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11302 DAG.getValueType(VT));
11303 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11306 if (VT == MVT::f32) {
11307 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11308 // the result back to FR32 register. It's only worth matching if the
11309 // result has a single use which is a store or a bitcast to i32. And in
11310 // the case of a store, it's not worth it if the index is a constant 0,
11311 // because a MOVSSmr can be used instead, which is smaller and faster.
11312 if (!Op.hasOneUse())
11314 SDNode *User = *Op.getNode()->use_begin();
11315 if ((User->getOpcode() != ISD::STORE ||
11316 (isa<ConstantSDNode>(Op.getOperand(1)) &&
11317 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11318 (User->getOpcode() != ISD::BITCAST ||
11319 User->getValueType(0) != MVT::i32))
11321 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11322 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11324 return DAG.getBitcast(MVT::f32, Extract);
11327 if (VT == MVT::i32 || VT == MVT::i64) {
11328 // ExtractPS/pextrq works with constant index.
11329 if (isa<ConstantSDNode>(Op.getOperand(1)))
11335 /// Extract one bit from mask vector, like v16i1 or v8i1.
11336 /// AVX-512 feature.
11338 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11339 SDValue Vec = Op.getOperand(0);
11341 MVT VecVT = Vec.getSimpleValueType();
11342 SDValue Idx = Op.getOperand(1);
11343 MVT EltVT = Op.getSimpleValueType();
11345 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11346 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11347 "Unexpected vector type in ExtractBitFromMaskVector");
11349 // variable index can't be handled in mask registers,
11350 // extend vector to VR512
11351 if (!isa<ConstantSDNode>(Idx)) {
11352 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11353 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11354 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11355 ExtVT.getVectorElementType(), Ext, Idx);
11356 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11359 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11360 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11361 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11362 rc = getRegClassFor(MVT::v16i1);
11363 unsigned MaxSift = rc->getSize()*8 - 1;
11364 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11365 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11366 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11367 DAG.getConstant(MaxSift, dl, MVT::i8));
11368 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11369 DAG.getIntPtrConstant(0, dl));
11373 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11374 SelectionDAG &DAG) const {
11376 SDValue Vec = Op.getOperand(0);
11377 MVT VecVT = Vec.getSimpleValueType();
11378 SDValue Idx = Op.getOperand(1);
11380 if (Op.getSimpleValueType() == MVT::i1)
11381 return ExtractBitFromMaskVector(Op, DAG);
11383 if (!isa<ConstantSDNode>(Idx)) {
11384 if (VecVT.is512BitVector() ||
11385 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11386 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11389 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11390 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11391 MaskEltVT.getSizeInBits());
11393 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11394 auto PtrVT = getPointerTy(DAG.getDataLayout());
11395 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11396 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11397 DAG.getConstant(0, dl, PtrVT));
11398 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11399 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11400 DAG.getConstant(0, dl, PtrVT));
11405 // If this is a 256-bit vector result, first extract the 128-bit vector and
11406 // then extract the element from the 128-bit vector.
11407 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11409 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11410 // Get the 128-bit vector.
11411 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11412 MVT EltVT = VecVT.getVectorElementType();
11414 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11416 //if (IdxVal >= NumElems/2)
11417 // IdxVal -= NumElems/2;
11418 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11419 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11420 DAG.getConstant(IdxVal, dl, MVT::i32));
11423 assert(VecVT.is128BitVector() && "Unexpected vector length");
11425 if (Subtarget->hasSSE41())
11426 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11429 MVT VT = Op.getSimpleValueType();
11430 // TODO: handle v16i8.
11431 if (VT.getSizeInBits() == 16) {
11432 SDValue Vec = Op.getOperand(0);
11433 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11435 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11436 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11437 DAG.getBitcast(MVT::v4i32, Vec),
11438 Op.getOperand(1)));
11439 // Transform it so it match pextrw which produces a 32-bit result.
11440 MVT EltVT = MVT::i32;
11441 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11442 Op.getOperand(0), Op.getOperand(1));
11443 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11444 DAG.getValueType(VT));
11445 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11448 if (VT.getSizeInBits() == 32) {
11449 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11453 // SHUFPS the element to the lowest double word, then movss.
11454 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11455 MVT VVT = Op.getOperand(0).getSimpleValueType();
11456 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11457 DAG.getUNDEF(VVT), Mask);
11458 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11459 DAG.getIntPtrConstant(0, dl));
11462 if (VT.getSizeInBits() == 64) {
11463 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11464 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11465 // to match extract_elt for f64.
11466 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11470 // UNPCKHPD the element to the lowest double word, then movsd.
11471 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11472 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11473 int Mask[2] = { 1, -1 };
11474 MVT VVT = Op.getOperand(0).getSimpleValueType();
11475 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11476 DAG.getUNDEF(VVT), Mask);
11477 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11478 DAG.getIntPtrConstant(0, dl));
11484 /// Insert one bit to mask vector, like v16i1 or v8i1.
11485 /// AVX-512 feature.
11487 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11489 SDValue Vec = Op.getOperand(0);
11490 SDValue Elt = Op.getOperand(1);
11491 SDValue Idx = Op.getOperand(2);
11492 MVT VecVT = Vec.getSimpleValueType();
11494 if (!isa<ConstantSDNode>(Idx)) {
11495 // Non constant index. Extend source and destination,
11496 // insert element and then truncate the result.
11497 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11498 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11499 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11500 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11501 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11502 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11505 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11506 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11508 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11509 DAG.getConstant(IdxVal, dl, MVT::i8));
11510 if (Vec.getOpcode() == ISD::UNDEF)
11512 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11515 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11516 SelectionDAG &DAG) const {
11517 MVT VT = Op.getSimpleValueType();
11518 MVT EltVT = VT.getVectorElementType();
11520 if (EltVT == MVT::i1)
11521 return InsertBitToMaskVector(Op, DAG);
11524 SDValue N0 = Op.getOperand(0);
11525 SDValue N1 = Op.getOperand(1);
11526 SDValue N2 = Op.getOperand(2);
11527 if (!isa<ConstantSDNode>(N2))
11529 auto *N2C = cast<ConstantSDNode>(N2);
11530 unsigned IdxVal = N2C->getZExtValue();
11532 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11533 // into that, and then insert the subvector back into the result.
11534 if (VT.is256BitVector() || VT.is512BitVector()) {
11535 // With a 256-bit vector, we can insert into the zero element efficiently
11536 // using a blend if we have AVX or AVX2 and the right data type.
11537 if (VT.is256BitVector() && IdxVal == 0) {
11538 // TODO: It is worthwhile to cast integer to floating point and back
11539 // and incur a domain crossing penalty if that's what we'll end up
11540 // doing anyway after extracting to a 128-bit vector.
11541 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11542 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11543 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11544 N2 = DAG.getIntPtrConstant(1, dl);
11545 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11549 // Get the desired 128-bit vector chunk.
11550 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11552 // Insert the element into the desired chunk.
11553 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11554 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11556 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11557 DAG.getConstant(IdxIn128, dl, MVT::i32));
11559 // Insert the changed part back into the bigger vector
11560 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11562 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11564 if (Subtarget->hasSSE41()) {
11565 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11567 if (VT == MVT::v8i16) {
11568 Opc = X86ISD::PINSRW;
11570 assert(VT == MVT::v16i8);
11571 Opc = X86ISD::PINSRB;
11574 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11576 if (N1.getValueType() != MVT::i32)
11577 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11578 if (N2.getValueType() != MVT::i32)
11579 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11580 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11583 if (EltVT == MVT::f32) {
11584 // Bits [7:6] of the constant are the source select. This will always be
11585 // zero here. The DAG Combiner may combine an extract_elt index into
11586 // these bits. For example (insert (extract, 3), 2) could be matched by
11587 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11588 // Bits [5:4] of the constant are the destination select. This is the
11589 // value of the incoming immediate.
11590 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11591 // combine either bitwise AND or insert of float 0.0 to set these bits.
11593 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11594 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11595 // If this is an insertion of 32-bits into the low 32-bits of
11596 // a vector, we prefer to generate a blend with immediate rather
11597 // than an insertps. Blends are simpler operations in hardware and so
11598 // will always have equal or better performance than insertps.
11599 // But if optimizing for size and there's a load folding opportunity,
11600 // generate insertps because blendps does not have a 32-bit memory
11602 N2 = DAG.getIntPtrConstant(1, dl);
11603 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11604 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11606 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11607 // Create this as a scalar to vector..
11608 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11609 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11612 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11613 // PINSR* works with constant index.
11618 if (EltVT == MVT::i8)
11621 if (EltVT.getSizeInBits() == 16) {
11622 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11623 // as its second argument.
11624 if (N1.getValueType() != MVT::i32)
11625 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11626 if (N2.getValueType() != MVT::i32)
11627 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11628 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11633 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11635 MVT OpVT = Op.getSimpleValueType();
11637 // If this is a 256-bit vector result, first insert into a 128-bit
11638 // vector and then insert into the 256-bit vector.
11639 if (!OpVT.is128BitVector()) {
11640 // Insert into a 128-bit vector.
11641 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11642 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11643 OpVT.getVectorNumElements() / SizeFactor);
11645 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11647 // Insert the 128-bit vector.
11648 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11651 if (OpVT == MVT::v1i64 &&
11652 Op.getOperand(0).getValueType() == MVT::i64)
11653 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11655 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11656 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11657 return DAG.getBitcast(
11658 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11661 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11662 // a simple subregister reference or explicit instructions to grab
11663 // upper bits of a vector.
11664 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11665 SelectionDAG &DAG) {
11667 SDValue In = Op.getOperand(0);
11668 SDValue Idx = Op.getOperand(1);
11669 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11670 MVT ResVT = Op.getSimpleValueType();
11671 MVT InVT = In.getSimpleValueType();
11673 if (Subtarget->hasFp256()) {
11674 if (ResVT.is128BitVector() &&
11675 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11676 isa<ConstantSDNode>(Idx)) {
11677 return Extract128BitVector(In, IdxVal, DAG, dl);
11679 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11680 isa<ConstantSDNode>(Idx)) {
11681 return Extract256BitVector(In, IdxVal, DAG, dl);
11687 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11688 // simple superregister reference or explicit instructions to insert
11689 // the upper bits of a vector.
11690 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11691 SelectionDAG &DAG) {
11692 if (!Subtarget->hasAVX())
11696 SDValue Vec = Op.getOperand(0);
11697 SDValue SubVec = Op.getOperand(1);
11698 SDValue Idx = Op.getOperand(2);
11700 if (!isa<ConstantSDNode>(Idx))
11703 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11704 MVT OpVT = Op.getSimpleValueType();
11705 MVT SubVecVT = SubVec.getSimpleValueType();
11707 // Fold two 16-byte subvector loads into one 32-byte load:
11708 // (insert_subvector (insert_subvector undef, (load addr), 0),
11709 // (load addr + 16), Elts/2)
11711 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11712 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11713 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11714 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11715 if (Idx2 && Idx2->getZExtValue() == 0) {
11716 SDValue SubVec2 = Vec.getOperand(1);
11717 // If needed, look through a bitcast to get to the load.
11718 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11719 SubVec2 = SubVec2.getOperand(0);
11721 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11723 unsigned Alignment = FirstLd->getAlignment();
11724 unsigned AS = FirstLd->getAddressSpace();
11725 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11726 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11727 OpVT, AS, Alignment, &Fast) && Fast) {
11728 SDValue Ops[] = { SubVec2, SubVec };
11729 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11736 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11737 SubVecVT.is128BitVector())
11738 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11740 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11741 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11743 if (OpVT.getVectorElementType() == MVT::i1) {
11744 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11746 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11747 SDValue Undef = DAG.getUNDEF(OpVT);
11748 unsigned NumElems = OpVT.getVectorNumElements();
11749 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11751 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11752 // Zero upper bits of the Vec
11753 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11754 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11756 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11758 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11759 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11762 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11764 // Zero upper bits of the Vec2
11765 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11766 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11767 // Zero lower bits of the Vec
11768 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11769 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11770 // Merge them together
11771 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11777 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11778 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11779 // one of the above mentioned nodes. It has to be wrapped because otherwise
11780 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11781 // be used to form addressing mode. These wrapped nodes will be selected
11784 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11785 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11787 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11788 // global base reg.
11789 unsigned char OpFlag = 0;
11790 unsigned WrapperKind = X86ISD::Wrapper;
11791 CodeModel::Model M = DAG.getTarget().getCodeModel();
11793 if (Subtarget->isPICStyleRIPRel() &&
11794 (M == CodeModel::Small || M == CodeModel::Kernel))
11795 WrapperKind = X86ISD::WrapperRIP;
11796 else if (Subtarget->isPICStyleGOT())
11797 OpFlag = X86II::MO_GOTOFF;
11798 else if (Subtarget->isPICStyleStubPIC())
11799 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11801 auto PtrVT = getPointerTy(DAG.getDataLayout());
11802 SDValue Result = DAG.getTargetConstantPool(
11803 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11805 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11806 // With PIC, the address is actually $g + Offset.
11809 DAG.getNode(ISD::ADD, DL, PtrVT,
11810 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11816 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11817 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11819 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11820 // global base reg.
11821 unsigned char OpFlag = 0;
11822 unsigned WrapperKind = X86ISD::Wrapper;
11823 CodeModel::Model M = DAG.getTarget().getCodeModel();
11825 if (Subtarget->isPICStyleRIPRel() &&
11826 (M == CodeModel::Small || M == CodeModel::Kernel))
11827 WrapperKind = X86ISD::WrapperRIP;
11828 else if (Subtarget->isPICStyleGOT())
11829 OpFlag = X86II::MO_GOTOFF;
11830 else if (Subtarget->isPICStyleStubPIC())
11831 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11833 auto PtrVT = getPointerTy(DAG.getDataLayout());
11834 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11836 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11838 // With PIC, the address is actually $g + Offset.
11841 DAG.getNode(ISD::ADD, DL, PtrVT,
11842 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11848 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11849 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11851 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11852 // global base reg.
11853 unsigned char OpFlag = 0;
11854 unsigned WrapperKind = X86ISD::Wrapper;
11855 CodeModel::Model M = DAG.getTarget().getCodeModel();
11857 if (Subtarget->isPICStyleRIPRel() &&
11858 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11859 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11860 OpFlag = X86II::MO_GOTPCREL;
11861 WrapperKind = X86ISD::WrapperRIP;
11862 } else if (Subtarget->isPICStyleGOT()) {
11863 OpFlag = X86II::MO_GOT;
11864 } else if (Subtarget->isPICStyleStubPIC()) {
11865 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11866 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11867 OpFlag = X86II::MO_DARWIN_NONLAZY;
11870 auto PtrVT = getPointerTy(DAG.getDataLayout());
11871 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11874 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11876 // With PIC, the address is actually $g + Offset.
11877 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11878 !Subtarget->is64Bit()) {
11880 DAG.getNode(ISD::ADD, DL, PtrVT,
11881 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11884 // For symbols that require a load from a stub to get the address, emit the
11886 if (isGlobalStubReference(OpFlag))
11887 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11888 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11889 false, false, false, 0);
11895 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11896 // Create the TargetBlockAddressAddress node.
11897 unsigned char OpFlags =
11898 Subtarget->ClassifyBlockAddressReference();
11899 CodeModel::Model M = DAG.getTarget().getCodeModel();
11900 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11901 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11903 auto PtrVT = getPointerTy(DAG.getDataLayout());
11904 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11906 if (Subtarget->isPICStyleRIPRel() &&
11907 (M == CodeModel::Small || M == CodeModel::Kernel))
11908 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11910 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11912 // With PIC, the address is actually $g + Offset.
11913 if (isGlobalRelativeToPICBase(OpFlags)) {
11914 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11915 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11922 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11923 int64_t Offset, SelectionDAG &DAG) const {
11924 // Create the TargetGlobalAddress node, folding in the constant
11925 // offset if it is legal.
11926 unsigned char OpFlags =
11927 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11928 CodeModel::Model M = DAG.getTarget().getCodeModel();
11929 auto PtrVT = getPointerTy(DAG.getDataLayout());
11931 if (OpFlags == X86II::MO_NO_FLAG &&
11932 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11933 // A direct static reference to a global.
11934 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11937 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11940 if (Subtarget->isPICStyleRIPRel() &&
11941 (M == CodeModel::Small || M == CodeModel::Kernel))
11942 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11944 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11946 // With PIC, the address is actually $g + Offset.
11947 if (isGlobalRelativeToPICBase(OpFlags)) {
11948 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11949 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11952 // For globals that require a load from a stub to get the address, emit the
11954 if (isGlobalStubReference(OpFlags))
11955 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11956 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11957 false, false, false, 0);
11959 // If there was a non-zero offset that we didn't fold, create an explicit
11960 // addition for it.
11962 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11963 DAG.getConstant(Offset, dl, PtrVT));
11969 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11970 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11971 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11972 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11976 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11977 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11978 unsigned char OperandFlags, bool LocalDynamic = false) {
11979 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11980 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11982 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11983 GA->getValueType(0),
11987 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11991 SDValue Ops[] = { Chain, TGA, *InFlag };
11992 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11994 SDValue Ops[] = { Chain, TGA };
11995 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11998 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11999 MFI->setAdjustsStack(true);
12000 MFI->setHasCalls(true);
12002 SDValue Flag = Chain.getValue(1);
12003 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12006 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12008 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12011 SDLoc dl(GA); // ? function entry point might be better
12012 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12013 DAG.getNode(X86ISD::GlobalBaseReg,
12014 SDLoc(), PtrVT), InFlag);
12015 InFlag = Chain.getValue(1);
12017 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12020 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12022 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12024 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12025 X86::RAX, X86II::MO_TLSGD);
12028 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12034 // Get the start address of the TLS block for this module.
12035 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12036 .getInfo<X86MachineFunctionInfo>();
12037 MFI->incNumLocalDynamicTLSAccesses();
12041 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12042 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12045 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12046 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12047 InFlag = Chain.getValue(1);
12048 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12049 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12052 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12056 unsigned char OperandFlags = X86II::MO_DTPOFF;
12057 unsigned WrapperKind = X86ISD::Wrapper;
12058 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12059 GA->getValueType(0),
12060 GA->getOffset(), OperandFlags);
12061 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12063 // Add x@dtpoff with the base.
12064 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12067 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12068 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12069 const EVT PtrVT, TLSModel::Model model,
12070 bool is64Bit, bool isPIC) {
12073 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12074 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12075 is64Bit ? 257 : 256));
12077 SDValue ThreadPointer =
12078 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12079 MachinePointerInfo(Ptr), false, false, false, 0);
12081 unsigned char OperandFlags = 0;
12082 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12084 unsigned WrapperKind = X86ISD::Wrapper;
12085 if (model == TLSModel::LocalExec) {
12086 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12087 } else if (model == TLSModel::InitialExec) {
12089 OperandFlags = X86II::MO_GOTTPOFF;
12090 WrapperKind = X86ISD::WrapperRIP;
12092 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12095 llvm_unreachable("Unexpected model");
12098 // emit "addl x@ntpoff,%eax" (local exec)
12099 // or "addl x@indntpoff,%eax" (initial exec)
12100 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12102 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12103 GA->getOffset(), OperandFlags);
12104 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12106 if (model == TLSModel::InitialExec) {
12107 if (isPIC && !is64Bit) {
12108 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12109 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12113 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12114 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12115 false, false, false, 0);
12118 // The address of the thread local variable is the add of the thread
12119 // pointer with the offset of the variable.
12120 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12124 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12126 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12127 const GlobalValue *GV = GA->getGlobal();
12128 auto PtrVT = getPointerTy(DAG.getDataLayout());
12130 if (Subtarget->isTargetELF()) {
12131 if (DAG.getTarget().Options.EmulatedTLS)
12132 return LowerToTLSEmulatedModel(GA, DAG);
12133 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12135 case TLSModel::GeneralDynamic:
12136 if (Subtarget->is64Bit())
12137 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12138 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12139 case TLSModel::LocalDynamic:
12140 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12141 Subtarget->is64Bit());
12142 case TLSModel::InitialExec:
12143 case TLSModel::LocalExec:
12144 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12145 DAG.getTarget().getRelocationModel() ==
12148 llvm_unreachable("Unknown TLS model.");
12151 if (Subtarget->isTargetDarwin()) {
12152 // Darwin only has one model of TLS. Lower to that.
12153 unsigned char OpFlag = 0;
12154 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12155 X86ISD::WrapperRIP : X86ISD::Wrapper;
12157 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12158 // global base reg.
12159 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12160 !Subtarget->is64Bit();
12162 OpFlag = X86II::MO_TLVP_PIC_BASE;
12164 OpFlag = X86II::MO_TLVP;
12166 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12167 GA->getValueType(0),
12168 GA->getOffset(), OpFlag);
12169 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12171 // With PIC32, the address is actually $g + Offset.
12173 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12174 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12177 // Lowering the machine isd will make sure everything is in the right
12179 SDValue Chain = DAG.getEntryNode();
12180 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12181 SDValue Args[] = { Chain, Offset };
12182 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12184 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12185 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12186 MFI->setAdjustsStack(true);
12188 // And our return value (tls address) is in the standard call return value
12190 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12191 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12194 if (Subtarget->isTargetKnownWindowsMSVC() ||
12195 Subtarget->isTargetWindowsGNU()) {
12196 // Just use the implicit TLS architecture
12197 // Need to generate someting similar to:
12198 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12200 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12201 // mov rcx, qword [rdx+rcx*8]
12202 // mov eax, .tls$:tlsvar
12203 // [rax+rcx] contains the address
12204 // Windows 64bit: gs:0x58
12205 // Windows 32bit: fs:__tls_array
12208 SDValue Chain = DAG.getEntryNode();
12210 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12211 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12212 // use its literal value of 0x2C.
12213 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12214 ? Type::getInt8PtrTy(*DAG.getContext(),
12216 : Type::getInt32PtrTy(*DAG.getContext(),
12219 SDValue TlsArray = Subtarget->is64Bit()
12220 ? DAG.getIntPtrConstant(0x58, dl)
12221 : (Subtarget->isTargetWindowsGNU()
12222 ? DAG.getIntPtrConstant(0x2C, dl)
12223 : DAG.getExternalSymbol("_tls_array", PtrVT));
12225 SDValue ThreadPointer =
12226 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12230 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12231 res = ThreadPointer;
12233 // Load the _tls_index variable
12234 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12235 if (Subtarget->is64Bit())
12236 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12237 MachinePointerInfo(), MVT::i32, false, false,
12240 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12243 auto &DL = DAG.getDataLayout();
12245 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12246 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12248 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12251 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12254 // Get the offset of start of .tls section
12255 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12256 GA->getValueType(0),
12257 GA->getOffset(), X86II::MO_SECREL);
12258 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12260 // The address of the thread local variable is the add of the thread
12261 // pointer with the offset of the variable.
12262 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12265 llvm_unreachable("TLS not implemented for this target.");
12268 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12269 /// and take a 2 x i32 value to shift plus a shift amount.
12270 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12271 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12272 MVT VT = Op.getSimpleValueType();
12273 unsigned VTBits = VT.getSizeInBits();
12275 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12276 SDValue ShOpLo = Op.getOperand(0);
12277 SDValue ShOpHi = Op.getOperand(1);
12278 SDValue ShAmt = Op.getOperand(2);
12279 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12280 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12282 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12283 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12284 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12285 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12286 : DAG.getConstant(0, dl, VT);
12288 SDValue Tmp2, Tmp3;
12289 if (Op.getOpcode() == ISD::SHL_PARTS) {
12290 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12291 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12293 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12294 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12297 // If the shift amount is larger or equal than the width of a part we can't
12298 // rely on the results of shld/shrd. Insert a test and select the appropriate
12299 // values for large shift amounts.
12300 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12301 DAG.getConstant(VTBits, dl, MVT::i8));
12302 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12303 AndNode, DAG.getConstant(0, dl, MVT::i8));
12306 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12307 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12308 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12310 if (Op.getOpcode() == ISD::SHL_PARTS) {
12311 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12312 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12314 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12315 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12318 SDValue Ops[2] = { Lo, Hi };
12319 return DAG.getMergeValues(Ops, dl);
12322 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12323 SelectionDAG &DAG) const {
12324 SDValue Src = Op.getOperand(0);
12325 MVT SrcVT = Src.getSimpleValueType();
12326 MVT VT = Op.getSimpleValueType();
12329 if (SrcVT.isVector()) {
12330 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12331 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12332 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12333 DAG.getUNDEF(SrcVT)));
12335 if (SrcVT.getVectorElementType() == MVT::i1) {
12336 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12337 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12338 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12343 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12344 "Unknown SINT_TO_FP to lower!");
12346 // These are really Legal; return the operand so the caller accepts it as
12348 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12350 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12351 Subtarget->is64Bit()) {
12355 unsigned Size = SrcVT.getSizeInBits()/8;
12356 MachineFunction &MF = DAG.getMachineFunction();
12357 auto PtrVT = getPointerTy(MF.getDataLayout());
12358 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12359 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12360 SDValue Chain = DAG.getStore(
12361 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12362 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12364 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12367 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12369 SelectionDAG &DAG) const {
12373 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12375 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12377 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12379 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12381 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12382 MachineMemOperand *MMO;
12384 int SSFI = FI->getIndex();
12385 MMO = DAG.getMachineFunction().getMachineMemOperand(
12386 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12387 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12389 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12390 StackSlot = StackSlot.getOperand(1);
12392 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12393 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12395 Tys, Ops, SrcVT, MMO);
12398 Chain = Result.getValue(1);
12399 SDValue InFlag = Result.getValue(2);
12401 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12402 // shouldn't be necessary except that RFP cannot be live across
12403 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12404 MachineFunction &MF = DAG.getMachineFunction();
12405 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12406 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12407 auto PtrVT = getPointerTy(MF.getDataLayout());
12408 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12409 Tys = DAG.getVTList(MVT::Other);
12411 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12413 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12414 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12415 MachineMemOperand::MOStore, SSFISize, SSFISize);
12417 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12418 Ops, Op.getValueType(), MMO);
12419 Result = DAG.getLoad(
12420 Op.getValueType(), DL, Chain, StackSlot,
12421 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12422 false, false, false, 0);
12428 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12429 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12430 SelectionDAG &DAG) const {
12431 // This algorithm is not obvious. Here it is what we're trying to output:
12434 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12435 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12437 haddpd %xmm0, %xmm0
12439 pshufd $0x4e, %xmm0, %xmm1
12445 LLVMContext *Context = DAG.getContext();
12447 // Build some magic constants.
12448 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12449 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12450 auto PtrVT = getPointerTy(DAG.getDataLayout());
12451 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12453 SmallVector<Constant*,2> CV1;
12455 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12456 APInt(64, 0x4330000000000000ULL))));
12458 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12459 APInt(64, 0x4530000000000000ULL))));
12460 Constant *C1 = ConstantVector::get(CV1);
12461 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12463 // Load the 64-bit value into an XMM register.
12464 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12467 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12468 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12469 false, false, false, 16);
12471 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12474 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12475 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12476 false, false, false, 16);
12477 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12478 // TODO: Are there any fast-math-flags to propagate here?
12479 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12482 if (Subtarget->hasSSE3()) {
12483 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12484 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12486 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12487 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12489 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12490 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12493 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12494 DAG.getIntPtrConstant(0, dl));
12497 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12498 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12499 SelectionDAG &DAG) const {
12501 // FP constant to bias correct the final result.
12502 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12505 // Load the 32-bit value into an XMM register.
12506 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12509 // Zero out the upper parts of the register.
12510 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12512 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12513 DAG.getBitcast(MVT::v2f64, Load),
12514 DAG.getIntPtrConstant(0, dl));
12516 // Or the load with the bias.
12517 SDValue Or = DAG.getNode(
12518 ISD::OR, dl, MVT::v2i64,
12519 DAG.getBitcast(MVT::v2i64,
12520 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12521 DAG.getBitcast(MVT::v2i64,
12522 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12524 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12525 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12527 // Subtract the bias.
12528 // TODO: Are there any fast-math-flags to propagate here?
12529 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12531 // Handle final rounding.
12532 EVT DestVT = Op.getValueType();
12534 if (DestVT.bitsLT(MVT::f64))
12535 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12536 DAG.getIntPtrConstant(0, dl));
12537 if (DestVT.bitsGT(MVT::f64))
12538 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12540 // Handle final rounding.
12544 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12545 const X86Subtarget &Subtarget) {
12546 // The algorithm is the following:
12547 // #ifdef __SSE4_1__
12548 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12549 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12550 // (uint4) 0x53000000, 0xaa);
12552 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12553 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12555 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12556 // return (float4) lo + fhi;
12558 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12559 // reassociate the two FADDs, and if we do that, the algorithm fails
12560 // spectacularly (PR24512).
12561 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12562 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12563 // there's also the MachineCombiner reassociations happening on Machine IR.
12564 if (DAG.getTarget().Options.UnsafeFPMath)
12568 SDValue V = Op->getOperand(0);
12569 EVT VecIntVT = V.getValueType();
12570 bool Is128 = VecIntVT == MVT::v4i32;
12571 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12572 // If we convert to something else than the supported type, e.g., to v4f64,
12574 if (VecFloatVT != Op->getValueType(0))
12577 unsigned NumElts = VecIntVT.getVectorNumElements();
12578 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12579 "Unsupported custom type");
12580 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12582 // In the #idef/#else code, we have in common:
12583 // - The vector of constants:
12589 // Create the splat vector for 0x4b000000.
12590 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12591 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12592 CstLow, CstLow, CstLow, CstLow};
12593 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12594 makeArrayRef(&CstLowArray[0], NumElts));
12595 // Create the splat vector for 0x53000000.
12596 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12597 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12598 CstHigh, CstHigh, CstHigh, CstHigh};
12599 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12600 makeArrayRef(&CstHighArray[0], NumElts));
12602 // Create the right shift.
12603 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12604 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12605 CstShift, CstShift, CstShift, CstShift};
12606 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12607 makeArrayRef(&CstShiftArray[0], NumElts));
12608 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12611 if (Subtarget.hasSSE41()) {
12612 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12613 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12614 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12615 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12616 // Low will be bitcasted right away, so do not bother bitcasting back to its
12618 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12619 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12620 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12621 // (uint4) 0x53000000, 0xaa);
12622 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12623 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12624 // High will be bitcasted right away, so do not bother bitcasting back to
12625 // its original type.
12626 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12627 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12629 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12630 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12631 CstMask, CstMask, CstMask);
12632 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12633 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12634 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12636 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12637 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12640 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12641 SDValue CstFAdd = DAG.getConstantFP(
12642 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12643 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12644 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12645 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12646 makeArrayRef(&CstFAddArray[0], NumElts));
12648 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12649 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12650 // TODO: Are there any fast-math-flags to propagate here?
12652 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12653 // return (float4) lo + fhi;
12654 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12655 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12658 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12659 SelectionDAG &DAG) const {
12660 SDValue N0 = Op.getOperand(0);
12661 MVT SVT = N0.getSimpleValueType();
12664 switch (SVT.SimpleTy) {
12666 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12671 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12672 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12673 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12677 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12680 if (Subtarget->hasAVX512())
12681 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12682 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12684 llvm_unreachable(nullptr);
12687 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12688 SelectionDAG &DAG) const {
12689 SDValue N0 = Op.getOperand(0);
12691 auto PtrVT = getPointerTy(DAG.getDataLayout());
12693 if (Op.getValueType().isVector())
12694 return lowerUINT_TO_FP_vec(Op, DAG);
12696 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12697 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12698 // the optimization here.
12699 if (DAG.SignBitIsZero(N0))
12700 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12702 MVT SrcVT = N0.getSimpleValueType();
12703 MVT DstVT = Op.getSimpleValueType();
12705 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12706 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12707 // Conversions from unsigned i32 to f32/f64 are legal,
12708 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
12712 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12713 return LowerUINT_TO_FP_i64(Op, DAG);
12714 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12715 return LowerUINT_TO_FP_i32(Op, DAG);
12716 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12719 // Make a 64-bit buffer, and use it to build an FILD.
12720 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12721 if (SrcVT == MVT::i32) {
12722 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12723 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12724 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12725 StackSlot, MachinePointerInfo(),
12727 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12728 OffsetSlot, MachinePointerInfo(),
12730 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12734 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12735 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12736 StackSlot, MachinePointerInfo(),
12738 // For i64 source, we need to add the appropriate power of 2 if the input
12739 // was negative. This is the same as the optimization in
12740 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12741 // we must be careful to do the computation in x87 extended precision, not
12742 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12743 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12744 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12745 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12746 MachineMemOperand::MOLoad, 8, 8);
12748 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12749 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12750 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12753 APInt FF(32, 0x5F800000ULL);
12755 // Check whether the sign bit is set.
12756 SDValue SignSet = DAG.getSetCC(
12757 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12758 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12760 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12761 SDValue FudgePtr = DAG.getConstantPool(
12762 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12764 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12765 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12766 SDValue Four = DAG.getIntPtrConstant(4, dl);
12767 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12769 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12771 // Load the value out, extending it from f32 to f80.
12772 // FIXME: Avoid the extend by constructing the right constant pool?
12773 SDValue Fudge = DAG.getExtLoad(
12774 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12775 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12776 false, false, false, 4);
12777 // Extend everything to 80 bits to force it to be done on x87.
12778 // TODO: Are there any fast-math-flags to propagate here?
12779 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12780 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12781 DAG.getIntPtrConstant(0, dl));
12784 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12785 // is legal, or has an f16 source (which needs to be promoted to f32),
12786 // just return an <SDValue(), SDValue()> pair.
12787 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12788 // to i16, i32 or i64, and we lower it to a legal sequence.
12789 // If lowered to the final integer result we return a <result, SDValue()> pair.
12790 // Otherwise we lower it to a sequence ending with a FIST, return a
12791 // <FIST, StackSlot> pair, and the caller is responsible for loading
12792 // the final integer result from StackSlot.
12793 std::pair<SDValue,SDValue>
12794 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12795 bool IsSigned, bool IsReplace) const {
12798 EVT DstTy = Op.getValueType();
12799 EVT TheVT = Op.getOperand(0).getValueType();
12800 auto PtrVT = getPointerTy(DAG.getDataLayout());
12802 if (TheVT == MVT::f16)
12803 // We need to promote the f16 to f32 before using the lowering
12804 // in this routine.
12805 return std::make_pair(SDValue(), SDValue());
12807 assert((TheVT == MVT::f32 ||
12808 TheVT == MVT::f64 ||
12809 TheVT == MVT::f80) &&
12810 "Unexpected FP operand type in FP_TO_INTHelper");
12812 // If using FIST to compute an unsigned i64, we'll need some fixup
12813 // to handle values above the maximum signed i64. A FIST is always
12814 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12815 bool UnsignedFixup = !IsSigned &&
12816 DstTy == MVT::i64 &&
12817 (!Subtarget->is64Bit() ||
12818 !isScalarFPTypeInSSEReg(TheVT));
12820 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12821 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12822 // The low 32 bits of the fist result will have the correct uint32 result.
12823 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12827 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12828 DstTy.getSimpleVT() >= MVT::i16 &&
12829 "Unknown FP_TO_INT to lower!");
12831 // These are really Legal.
12832 if (DstTy == MVT::i32 &&
12833 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12834 return std::make_pair(SDValue(), SDValue());
12835 if (Subtarget->is64Bit() &&
12836 DstTy == MVT::i64 &&
12837 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12838 return std::make_pair(SDValue(), SDValue());
12840 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12842 MachineFunction &MF = DAG.getMachineFunction();
12843 unsigned MemSize = DstTy.getSizeInBits()/8;
12844 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12845 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12848 switch (DstTy.getSimpleVT().SimpleTy) {
12849 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12850 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12851 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12852 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12855 SDValue Chain = DAG.getEntryNode();
12856 SDValue Value = Op.getOperand(0);
12857 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12859 if (UnsignedFixup) {
12861 // Conversion to unsigned i64 is implemented with a select,
12862 // depending on whether the source value fits in the range
12863 // of a signed i64. Let Thresh be the FP equivalent of
12864 // 0x8000000000000000ULL.
12866 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12867 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12868 // Fist-to-mem64 FistSrc
12869 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12870 // to XOR'ing the high 32 bits with Adjust.
12872 // Being a power of 2, Thresh is exactly representable in all FP formats.
12873 // For X87 we'd like to use the smallest FP type for this constant, but
12874 // for DAG type consistency we have to match the FP operand type.
12876 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12877 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12878 bool LosesInfo = false;
12879 if (TheVT == MVT::f64)
12880 // The rounding mode is irrelevant as the conversion should be exact.
12881 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12883 else if (TheVT == MVT::f80)
12884 Status = Thresh.convert(APFloat::x87DoubleExtended,
12885 APFloat::rmNearestTiesToEven, &LosesInfo);
12887 assert(Status == APFloat::opOK && !LosesInfo &&
12888 "FP conversion should have been exact");
12890 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12892 SDValue Cmp = DAG.getSetCC(DL,
12893 getSetCCResultType(DAG.getDataLayout(),
12894 *DAG.getContext(), TheVT),
12895 Value, ThreshVal, ISD::SETLT);
12896 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12897 DAG.getConstant(0, DL, MVT::i32),
12898 DAG.getConstant(0x80000000, DL, MVT::i32));
12899 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12900 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12901 *DAG.getContext(), TheVT),
12902 Value, ThreshVal, ISD::SETLT);
12903 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12906 // FIXME This causes a redundant load/store if the SSE-class value is already
12907 // in memory, such as if it is on the callstack.
12908 if (isScalarFPTypeInSSEReg(TheVT)) {
12909 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12910 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12911 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12913 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12915 Chain, StackSlot, DAG.getValueType(TheVT)
12918 MachineMemOperand *MMO =
12919 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12920 MachineMemOperand::MOLoad, MemSize, MemSize);
12921 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12922 Chain = Value.getValue(1);
12923 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12924 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12927 MachineMemOperand *MMO =
12928 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12929 MachineMemOperand::MOStore, MemSize, MemSize);
12931 if (UnsignedFixup) {
12933 // Insert the FIST, load its result as two i32's,
12934 // and XOR the high i32 with Adjust.
12936 SDValue FistOps[] = { Chain, Value, StackSlot };
12937 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12938 FistOps, DstTy, MMO);
12940 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12941 MachinePointerInfo(),
12942 false, false, false, 0);
12943 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12944 DAG.getConstant(4, DL, PtrVT));
12946 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12947 MachinePointerInfo(),
12948 false, false, false, 0);
12949 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12951 if (Subtarget->is64Bit()) {
12952 // Join High32 and Low32 into a 64-bit result.
12953 // (High32 << 32) | Low32
12954 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12955 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12956 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12957 DAG.getConstant(32, DL, MVT::i8));
12958 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12959 return std::make_pair(Result, SDValue());
12962 SDValue ResultOps[] = { Low32, High32 };
12964 SDValue pair = IsReplace
12965 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12966 : DAG.getMergeValues(ResultOps, DL);
12967 return std::make_pair(pair, SDValue());
12969 // Build the FP_TO_INT*_IN_MEM
12970 SDValue Ops[] = { Chain, Value, StackSlot };
12971 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12973 return std::make_pair(FIST, StackSlot);
12977 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12978 const X86Subtarget *Subtarget) {
12979 MVT VT = Op->getSimpleValueType(0);
12980 SDValue In = Op->getOperand(0);
12981 MVT InVT = In.getSimpleValueType();
12984 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12985 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12987 // Optimize vectors in AVX mode:
12990 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12991 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12992 // Concat upper and lower parts.
12995 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12996 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12997 // Concat upper and lower parts.
13000 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13001 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13002 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13005 if (Subtarget->hasInt256())
13006 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13008 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13009 SDValue Undef = DAG.getUNDEF(InVT);
13010 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13011 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13012 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13014 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13015 VT.getVectorNumElements()/2);
13017 OpLo = DAG.getBitcast(HVT, OpLo);
13018 OpHi = DAG.getBitcast(HVT, OpHi);
13020 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13023 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13024 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13025 MVT VT = Op->getSimpleValueType(0);
13026 SDValue In = Op->getOperand(0);
13027 MVT InVT = In.getSimpleValueType();
13029 unsigned int NumElts = VT.getVectorNumElements();
13030 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13033 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13034 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13036 assert(InVT.getVectorElementType() == MVT::i1);
13037 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13039 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13041 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13043 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13044 if (VT.is512BitVector())
13046 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13049 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13050 SelectionDAG &DAG) {
13051 if (Subtarget->hasFp256())
13052 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13058 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13059 SelectionDAG &DAG) {
13061 MVT VT = Op.getSimpleValueType();
13062 SDValue In = Op.getOperand(0);
13063 MVT SVT = In.getSimpleValueType();
13065 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13066 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13068 if (Subtarget->hasFp256())
13069 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13072 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13073 VT.getVectorNumElements() != SVT.getVectorNumElements());
13077 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13079 MVT VT = Op.getSimpleValueType();
13080 SDValue In = Op.getOperand(0);
13081 MVT InVT = In.getSimpleValueType();
13083 if (VT == MVT::i1) {
13084 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13085 "Invalid scalar TRUNCATE operation");
13086 if (InVT.getSizeInBits() >= 32)
13088 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13089 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13091 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13092 "Invalid TRUNCATE operation");
13094 // move vector to mask - truncate solution for SKX
13095 if (VT.getVectorElementType() == MVT::i1) {
13096 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13097 Subtarget->hasBWI())
13098 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13099 if ((InVT.is256BitVector() || InVT.is128BitVector())
13100 && InVT.getScalarSizeInBits() <= 16 &&
13101 Subtarget->hasBWI() && Subtarget->hasVLX())
13102 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13103 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13104 Subtarget->hasDQI())
13105 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13106 if ((InVT.is256BitVector() || InVT.is128BitVector())
13107 && InVT.getScalarSizeInBits() >= 32 &&
13108 Subtarget->hasDQI() && Subtarget->hasVLX())
13109 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13112 if (VT.getVectorElementType() == MVT::i1) {
13113 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13114 unsigned NumElts = InVT.getVectorNumElements();
13115 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13116 if (InVT.getSizeInBits() < 512) {
13117 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13118 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13123 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13124 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13125 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13128 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13129 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13130 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13131 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13133 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13134 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13135 if (Subtarget->hasInt256()) {
13136 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13137 In = DAG.getBitcast(MVT::v8i32, In);
13138 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13140 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13141 DAG.getIntPtrConstant(0, DL));
13144 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13145 DAG.getIntPtrConstant(0, DL));
13146 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13147 DAG.getIntPtrConstant(2, DL));
13148 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13149 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13150 static const int ShufMask[] = {0, 2, 4, 6};
13151 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13154 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13155 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13156 if (Subtarget->hasInt256()) {
13157 In = DAG.getBitcast(MVT::v32i8, In);
13159 SmallVector<SDValue,32> pshufbMask;
13160 for (unsigned i = 0; i < 2; ++i) {
13161 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13162 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13163 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13164 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13165 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13166 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13167 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13168 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13169 for (unsigned j = 0; j < 8; ++j)
13170 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13172 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13173 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13174 In = DAG.getBitcast(MVT::v4i64, In);
13176 static const int ShufMask[] = {0, 2, -1, -1};
13177 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13179 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13180 DAG.getIntPtrConstant(0, DL));
13181 return DAG.getBitcast(VT, In);
13184 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13185 DAG.getIntPtrConstant(0, DL));
13187 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13188 DAG.getIntPtrConstant(4, DL));
13190 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13191 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13193 // The PSHUFB mask:
13194 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13195 -1, -1, -1, -1, -1, -1, -1, -1};
13197 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13198 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13199 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13201 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13202 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13204 // The MOVLHPS Mask:
13205 static const int ShufMask2[] = {0, 1, 4, 5};
13206 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13207 return DAG.getBitcast(MVT::v8i16, res);
13210 // Handle truncation of V256 to V128 using shuffles.
13211 if (!VT.is128BitVector() || !InVT.is256BitVector())
13214 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13216 unsigned NumElems = VT.getVectorNumElements();
13217 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13219 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13220 // Prepare truncation shuffle mask
13221 for (unsigned i = 0; i != NumElems; ++i)
13222 MaskVec[i] = i * 2;
13223 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13224 DAG.getUNDEF(NVT), &MaskVec[0]);
13225 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13226 DAG.getIntPtrConstant(0, DL));
13229 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13230 SelectionDAG &DAG) const {
13231 assert(!Op.getSimpleValueType().isVector());
13233 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13234 /*IsSigned=*/ true, /*IsReplace=*/ false);
13235 SDValue FIST = Vals.first, StackSlot = Vals.second;
13236 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13237 if (!FIST.getNode())
13240 if (StackSlot.getNode())
13241 // Load the result.
13242 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13243 FIST, StackSlot, MachinePointerInfo(),
13244 false, false, false, 0);
13246 // The node is the result.
13250 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13251 SelectionDAG &DAG) const {
13252 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13253 /*IsSigned=*/ false, /*IsReplace=*/ false);
13254 SDValue FIST = Vals.first, StackSlot = Vals.second;
13255 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13256 if (!FIST.getNode())
13259 if (StackSlot.getNode())
13260 // Load the result.
13261 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13262 FIST, StackSlot, MachinePointerInfo(),
13263 false, false, false, 0);
13265 // The node is the result.
13269 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13271 MVT VT = Op.getSimpleValueType();
13272 SDValue In = Op.getOperand(0);
13273 MVT SVT = In.getSimpleValueType();
13275 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13277 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13278 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13279 In, DAG.getUNDEF(SVT)));
13282 /// The only differences between FABS and FNEG are the mask and the logic op.
13283 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13284 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13285 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13286 "Wrong opcode for lowering FABS or FNEG.");
13288 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13290 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13291 // into an FNABS. We'll lower the FABS after that if it is still in use.
13293 for (SDNode *User : Op->uses())
13294 if (User->getOpcode() == ISD::FNEG)
13298 MVT VT = Op.getSimpleValueType();
13300 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13301 // decide if we should generate a 16-byte constant mask when we only need 4 or
13302 // 8 bytes for the scalar case.
13308 if (VT.isVector()) {
13310 EltVT = VT.getVectorElementType();
13311 NumElts = VT.getVectorNumElements();
13313 // There are no scalar bitwise logical SSE/AVX instructions, so we
13314 // generate a 16-byte vector constant and logic op even for the scalar case.
13315 // Using a 16-byte mask allows folding the load of the mask with
13316 // the logic op, so it can save (~4 bytes) on code size.
13317 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13319 NumElts = (VT == MVT::f64) ? 2 : 4;
13322 unsigned EltBits = EltVT.getSizeInBits();
13323 LLVMContext *Context = DAG.getContext();
13324 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13326 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13327 Constant *C = ConstantInt::get(*Context, MaskElt);
13328 C = ConstantVector::getSplat(NumElts, C);
13329 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13330 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13331 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13333 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13334 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13335 false, false, false, Alignment);
13337 SDValue Op0 = Op.getOperand(0);
13338 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13340 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13341 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13344 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13346 // For the scalar case extend to a 128-bit vector, perform the logic op,
13347 // and extract the scalar result back out.
13348 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13349 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13350 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13351 DAG.getIntPtrConstant(0, dl));
13354 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13355 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13356 LLVMContext *Context = DAG.getContext();
13357 SDValue Op0 = Op.getOperand(0);
13358 SDValue Op1 = Op.getOperand(1);
13360 MVT VT = Op.getSimpleValueType();
13361 MVT SrcVT = Op1.getSimpleValueType();
13363 // If second operand is smaller, extend it first.
13364 if (SrcVT.bitsLT(VT)) {
13365 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13368 // And if it is bigger, shrink it first.
13369 if (SrcVT.bitsGT(VT)) {
13370 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13374 // At this point the operands and the result should have the same
13375 // type, and that won't be f80 since that is not custom lowered.
13377 const fltSemantics &Sem =
13378 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13379 const unsigned SizeInBits = VT.getSizeInBits();
13381 SmallVector<Constant *, 4> CV(
13382 VT == MVT::f64 ? 2 : 4,
13383 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13385 // First, clear all bits but the sign bit from the second operand (sign).
13386 CV[0] = ConstantFP::get(*Context,
13387 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13388 Constant *C = ConstantVector::get(CV);
13389 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13390 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13392 // Perform all logic operations as 16-byte vectors because there are no
13393 // scalar FP logic instructions in SSE. This allows load folding of the
13394 // constants into the logic instructions.
13395 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13397 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13398 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13399 false, false, false, 16);
13400 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13401 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13403 // Next, clear the sign bit from the first operand (magnitude).
13404 // If it's a constant, we can clear it here.
13405 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13406 APFloat APF = Op0CN->getValueAPF();
13407 // If the magnitude is a positive zero, the sign bit alone is enough.
13408 if (APF.isPosZero())
13409 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13410 DAG.getIntPtrConstant(0, dl));
13412 CV[0] = ConstantFP::get(*Context, APF);
13414 CV[0] = ConstantFP::get(
13416 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13418 C = ConstantVector::get(CV);
13419 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13421 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13422 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13423 false, false, false, 16);
13424 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13425 if (!isa<ConstantFPSDNode>(Op0)) {
13426 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13427 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13429 // OR the magnitude value with the sign bit.
13430 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13431 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13432 DAG.getIntPtrConstant(0, dl));
13435 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13436 SDValue N0 = Op.getOperand(0);
13438 MVT VT = Op.getSimpleValueType();
13440 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13441 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13442 DAG.getConstant(1, dl, VT));
13443 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13446 // Check whether an OR'd tree is PTEST-able.
13447 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13448 SelectionDAG &DAG) {
13449 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13451 if (!Subtarget->hasSSE41())
13454 if (!Op->hasOneUse())
13457 SDNode *N = Op.getNode();
13460 SmallVector<SDValue, 8> Opnds;
13461 DenseMap<SDValue, unsigned> VecInMap;
13462 SmallVector<SDValue, 8> VecIns;
13463 EVT VT = MVT::Other;
13465 // Recognize a special case where a vector is casted into wide integer to
13467 Opnds.push_back(N->getOperand(0));
13468 Opnds.push_back(N->getOperand(1));
13470 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13471 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13472 // BFS traverse all OR'd operands.
13473 if (I->getOpcode() == ISD::OR) {
13474 Opnds.push_back(I->getOperand(0));
13475 Opnds.push_back(I->getOperand(1));
13476 // Re-evaluate the number of nodes to be traversed.
13477 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13481 // Quit if a non-EXTRACT_VECTOR_ELT
13482 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13485 // Quit if without a constant index.
13486 SDValue Idx = I->getOperand(1);
13487 if (!isa<ConstantSDNode>(Idx))
13490 SDValue ExtractedFromVec = I->getOperand(0);
13491 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13492 if (M == VecInMap.end()) {
13493 VT = ExtractedFromVec.getValueType();
13494 // Quit if not 128/256-bit vector.
13495 if (!VT.is128BitVector() && !VT.is256BitVector())
13497 // Quit if not the same type.
13498 if (VecInMap.begin() != VecInMap.end() &&
13499 VT != VecInMap.begin()->first.getValueType())
13501 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13502 VecIns.push_back(ExtractedFromVec);
13504 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13507 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13508 "Not extracted from 128-/256-bit vector.");
13510 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13512 for (DenseMap<SDValue, unsigned>::const_iterator
13513 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13514 // Quit if not all elements are used.
13515 if (I->second != FullMask)
13519 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13521 // Cast all vectors into TestVT for PTEST.
13522 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13523 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13525 // If more than one full vectors are evaluated, OR them first before PTEST.
13526 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13527 // Each iteration will OR 2 nodes and append the result until there is only
13528 // 1 node left, i.e. the final OR'd value of all vectors.
13529 SDValue LHS = VecIns[Slot];
13530 SDValue RHS = VecIns[Slot + 1];
13531 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13534 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13535 VecIns.back(), VecIns.back());
13538 /// \brief return true if \c Op has a use that doesn't just read flags.
13539 static bool hasNonFlagsUse(SDValue Op) {
13540 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13542 SDNode *User = *UI;
13543 unsigned UOpNo = UI.getOperandNo();
13544 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13545 // Look pass truncate.
13546 UOpNo = User->use_begin().getOperandNo();
13547 User = *User->use_begin();
13550 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13551 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13557 /// Emit nodes that will be selected as "test Op0,Op0", or something
13559 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13560 SelectionDAG &DAG) const {
13561 if (Op.getValueType() == MVT::i1) {
13562 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13563 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13564 DAG.getConstant(0, dl, MVT::i8));
13566 // CF and OF aren't always set the way we want. Determine which
13567 // of these we need.
13568 bool NeedCF = false;
13569 bool NeedOF = false;
13572 case X86::COND_A: case X86::COND_AE:
13573 case X86::COND_B: case X86::COND_BE:
13576 case X86::COND_G: case X86::COND_GE:
13577 case X86::COND_L: case X86::COND_LE:
13578 case X86::COND_O: case X86::COND_NO: {
13579 // Check if we really need to set the
13580 // Overflow flag. If NoSignedWrap is present
13581 // that is not actually needed.
13582 switch (Op->getOpcode()) {
13587 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13588 if (BinNode->Flags.hasNoSignedWrap())
13598 // See if we can use the EFLAGS value from the operand instead of
13599 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13600 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13601 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13602 // Emit a CMP with 0, which is the TEST pattern.
13603 //if (Op.getValueType() == MVT::i1)
13604 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13605 // DAG.getConstant(0, MVT::i1));
13606 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13607 DAG.getConstant(0, dl, Op.getValueType()));
13609 unsigned Opcode = 0;
13610 unsigned NumOperands = 0;
13612 // Truncate operations may prevent the merge of the SETCC instruction
13613 // and the arithmetic instruction before it. Attempt to truncate the operands
13614 // of the arithmetic instruction and use a reduced bit-width instruction.
13615 bool NeedTruncation = false;
13616 SDValue ArithOp = Op;
13617 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13618 SDValue Arith = Op->getOperand(0);
13619 // Both the trunc and the arithmetic op need to have one user each.
13620 if (Arith->hasOneUse())
13621 switch (Arith.getOpcode()) {
13628 NeedTruncation = true;
13634 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13635 // which may be the result of a CAST. We use the variable 'Op', which is the
13636 // non-casted variable when we check for possible users.
13637 switch (ArithOp.getOpcode()) {
13639 // Due to an isel shortcoming, be conservative if this add is likely to be
13640 // selected as part of a load-modify-store instruction. When the root node
13641 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13642 // uses of other nodes in the match, such as the ADD in this case. This
13643 // leads to the ADD being left around and reselected, with the result being
13644 // two adds in the output. Alas, even if none our users are stores, that
13645 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13646 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13647 // climbing the DAG back to the root, and it doesn't seem to be worth the
13649 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13650 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13651 if (UI->getOpcode() != ISD::CopyToReg &&
13652 UI->getOpcode() != ISD::SETCC &&
13653 UI->getOpcode() != ISD::STORE)
13656 if (ConstantSDNode *C =
13657 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13658 // An add of one will be selected as an INC.
13659 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13660 Opcode = X86ISD::INC;
13665 // An add of negative one (subtract of one) will be selected as a DEC.
13666 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13667 Opcode = X86ISD::DEC;
13673 // Otherwise use a regular EFLAGS-setting add.
13674 Opcode = X86ISD::ADD;
13679 // If we have a constant logical shift that's only used in a comparison
13680 // against zero turn it into an equivalent AND. This allows turning it into
13681 // a TEST instruction later.
13682 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13683 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13684 EVT VT = Op.getValueType();
13685 unsigned BitWidth = VT.getSizeInBits();
13686 unsigned ShAmt = Op->getConstantOperandVal(1);
13687 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13689 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13690 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13691 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13692 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13694 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13695 DAG.getConstant(Mask, dl, VT));
13696 DAG.ReplaceAllUsesWith(Op, New);
13702 // If the primary and result isn't used, don't bother using X86ISD::AND,
13703 // because a TEST instruction will be better.
13704 if (!hasNonFlagsUse(Op))
13710 // Due to the ISEL shortcoming noted above, be conservative if this op is
13711 // likely to be selected as part of a load-modify-store instruction.
13712 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13713 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13714 if (UI->getOpcode() == ISD::STORE)
13717 // Otherwise use a regular EFLAGS-setting instruction.
13718 switch (ArithOp.getOpcode()) {
13719 default: llvm_unreachable("unexpected operator!");
13720 case ISD::SUB: Opcode = X86ISD::SUB; break;
13721 case ISD::XOR: Opcode = X86ISD::XOR; break;
13722 case ISD::AND: Opcode = X86ISD::AND; break;
13724 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13725 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13726 if (EFLAGS.getNode())
13729 Opcode = X86ISD::OR;
13743 return SDValue(Op.getNode(), 1);
13749 // If we found that truncation is beneficial, perform the truncation and
13751 if (NeedTruncation) {
13752 EVT VT = Op.getValueType();
13753 SDValue WideVal = Op->getOperand(0);
13754 EVT WideVT = WideVal.getValueType();
13755 unsigned ConvertedOp = 0;
13756 // Use a target machine opcode to prevent further DAGCombine
13757 // optimizations that may separate the arithmetic operations
13758 // from the setcc node.
13759 switch (WideVal.getOpcode()) {
13761 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13762 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13763 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13764 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13765 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13769 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13770 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13771 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13772 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13773 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13779 // Emit a CMP with 0, which is the TEST pattern.
13780 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13781 DAG.getConstant(0, dl, Op.getValueType()));
13783 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13784 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13786 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13787 DAG.ReplaceAllUsesWith(Op, New);
13788 return SDValue(New.getNode(), 1);
13791 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13793 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13794 SDLoc dl, SelectionDAG &DAG) const {
13795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13796 if (C->getAPIntValue() == 0)
13797 return EmitTest(Op0, X86CC, dl, DAG);
13799 if (Op0.getValueType() == MVT::i1)
13800 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13803 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13804 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13805 // Do the comparison at i32 if it's smaller, besides the Atom case.
13806 // This avoids subregister aliasing issues. Keep the smaller reference
13807 // if we're optimizing for size, however, as that'll allow better folding
13808 // of memory operations.
13809 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13810 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13811 !Subtarget->isAtom()) {
13812 unsigned ExtendOp =
13813 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13814 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13815 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13817 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13818 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13819 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13821 return SDValue(Sub.getNode(), 1);
13823 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13826 /// Convert a comparison if required by the subtarget.
13827 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13828 SelectionDAG &DAG) const {
13829 // If the subtarget does not support the FUCOMI instruction, floating-point
13830 // comparisons have to be converted.
13831 if (Subtarget->hasCMov() ||
13832 Cmp.getOpcode() != X86ISD::CMP ||
13833 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13834 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13837 // The instruction selector will select an FUCOM instruction instead of
13838 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13839 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13840 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13842 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13843 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13844 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13845 DAG.getConstant(8, dl, MVT::i8));
13846 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13847 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13850 /// The minimum architected relative accuracy is 2^-12. We need one
13851 /// Newton-Raphson step to have a good float result (24 bits of precision).
13852 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13853 DAGCombinerInfo &DCI,
13854 unsigned &RefinementSteps,
13855 bool &UseOneConstNR) const {
13856 EVT VT = Op.getValueType();
13857 const char *RecipOp;
13859 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13860 // TODO: Add support for AVX512 (v16f32).
13861 // It is likely not profitable to do this for f64 because a double-precision
13862 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13863 // instructions: convert to single, rsqrtss, convert back to double, refine
13864 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13865 // along with FMA, this could be a throughput win.
13866 if (VT == MVT::f32 && Subtarget->hasSSE1())
13868 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13869 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13870 RecipOp = "vec-sqrtf";
13874 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13875 if (!Recips.isEnabled(RecipOp))
13878 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13879 UseOneConstNR = false;
13880 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13883 /// The minimum architected relative accuracy is 2^-12. We need one
13884 /// Newton-Raphson step to have a good float result (24 bits of precision).
13885 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13886 DAGCombinerInfo &DCI,
13887 unsigned &RefinementSteps) const {
13888 EVT VT = Op.getValueType();
13889 const char *RecipOp;
13891 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13892 // TODO: Add support for AVX512 (v16f32).
13893 // It is likely not profitable to do this for f64 because a double-precision
13894 // reciprocal estimate with refinement on x86 prior to FMA requires
13895 // 15 instructions: convert to single, rcpss, convert back to double, refine
13896 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13897 // along with FMA, this could be a throughput win.
13898 if (VT == MVT::f32 && Subtarget->hasSSE1())
13900 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13901 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13902 RecipOp = "vec-divf";
13906 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13907 if (!Recips.isEnabled(RecipOp))
13910 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13911 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13914 /// If we have at least two divisions that use the same divisor, convert to
13915 /// multplication by a reciprocal. This may need to be adjusted for a given
13916 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13917 /// This is because we still need one division to calculate the reciprocal and
13918 /// then we need two multiplies by that reciprocal as replacements for the
13919 /// original divisions.
13920 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13924 static bool isAllOnes(SDValue V) {
13925 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13926 return C && C->isAllOnesValue();
13929 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13930 /// if it's possible.
13931 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13932 SDLoc dl, SelectionDAG &DAG) const {
13933 SDValue Op0 = And.getOperand(0);
13934 SDValue Op1 = And.getOperand(1);
13935 if (Op0.getOpcode() == ISD::TRUNCATE)
13936 Op0 = Op0.getOperand(0);
13937 if (Op1.getOpcode() == ISD::TRUNCATE)
13938 Op1 = Op1.getOperand(0);
13941 if (Op1.getOpcode() == ISD::SHL)
13942 std::swap(Op0, Op1);
13943 if (Op0.getOpcode() == ISD::SHL) {
13944 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13945 if (And00C->getZExtValue() == 1) {
13946 // If we looked past a truncate, check that it's only truncating away
13948 unsigned BitWidth = Op0.getValueSizeInBits();
13949 unsigned AndBitWidth = And.getValueSizeInBits();
13950 if (BitWidth > AndBitWidth) {
13952 DAG.computeKnownBits(Op0, Zeros, Ones);
13953 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13957 RHS = Op0.getOperand(1);
13959 } else if (Op1.getOpcode() == ISD::Constant) {
13960 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13961 uint64_t AndRHSVal = AndRHS->getZExtValue();
13962 SDValue AndLHS = Op0;
13964 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13965 LHS = AndLHS.getOperand(0);
13966 RHS = AndLHS.getOperand(1);
13969 // Use BT if the immediate can't be encoded in a TEST instruction.
13970 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13972 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13976 if (LHS.getNode()) {
13977 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13978 // instruction. Since the shift amount is in-range-or-undefined, we know
13979 // that doing a bittest on the i32 value is ok. We extend to i32 because
13980 // the encoding for the i16 version is larger than the i32 version.
13981 // Also promote i16 to i32 for performance / code size reason.
13982 if (LHS.getValueType() == MVT::i8 ||
13983 LHS.getValueType() == MVT::i16)
13984 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13986 // If the operand types disagree, extend the shift amount to match. Since
13987 // BT ignores high bits (like shifts) we can use anyextend.
13988 if (LHS.getValueType() != RHS.getValueType())
13989 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13991 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13992 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13993 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13994 DAG.getConstant(Cond, dl, MVT::i8), BT);
14000 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14002 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14007 // SSE Condition code mapping:
14016 switch (SetCCOpcode) {
14017 default: llvm_unreachable("Unexpected SETCC condition");
14019 case ISD::SETEQ: SSECC = 0; break;
14021 case ISD::SETGT: Swap = true; // Fallthrough
14023 case ISD::SETOLT: SSECC = 1; break;
14025 case ISD::SETGE: Swap = true; // Fallthrough
14027 case ISD::SETOLE: SSECC = 2; break;
14028 case ISD::SETUO: SSECC = 3; break;
14030 case ISD::SETNE: SSECC = 4; break;
14031 case ISD::SETULE: Swap = true; // Fallthrough
14032 case ISD::SETUGE: SSECC = 5; break;
14033 case ISD::SETULT: Swap = true; // Fallthrough
14034 case ISD::SETUGT: SSECC = 6; break;
14035 case ISD::SETO: SSECC = 7; break;
14037 case ISD::SETONE: SSECC = 8; break;
14040 std::swap(Op0, Op1);
14045 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14046 // ones, and then concatenate the result back.
14047 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14048 MVT VT = Op.getSimpleValueType();
14050 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14051 "Unsupported value type for operation");
14053 unsigned NumElems = VT.getVectorNumElements();
14055 SDValue CC = Op.getOperand(2);
14057 // Extract the LHS vectors
14058 SDValue LHS = Op.getOperand(0);
14059 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14060 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14062 // Extract the RHS vectors
14063 SDValue RHS = Op.getOperand(1);
14064 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14065 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14067 // Issue the operation on the smaller types and concatenate the result back
14068 MVT EltVT = VT.getVectorElementType();
14069 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14070 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14071 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14072 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14075 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14076 SDValue Op0 = Op.getOperand(0);
14077 SDValue Op1 = Op.getOperand(1);
14078 SDValue CC = Op.getOperand(2);
14079 MVT VT = Op.getSimpleValueType();
14082 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
14083 "Unexpected type for boolean compare operation");
14084 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14085 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14086 DAG.getConstant(-1, dl, VT));
14087 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14088 DAG.getConstant(-1, dl, VT));
14089 switch (SetCCOpcode) {
14090 default: llvm_unreachable("Unexpected SETCC condition");
14092 // (x == y) -> ~(x ^ y)
14093 return DAG.getNode(ISD::XOR, dl, VT,
14094 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14095 DAG.getConstant(-1, dl, VT));
14097 // (x != y) -> (x ^ y)
14098 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14101 // (x > y) -> (x & ~y)
14102 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14105 // (x < y) -> (~x & y)
14106 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14109 // (x <= y) -> (~x | y)
14110 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14113 // (x >=y) -> (x | ~y)
14114 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14118 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14119 const X86Subtarget *Subtarget) {
14120 SDValue Op0 = Op.getOperand(0);
14121 SDValue Op1 = Op.getOperand(1);
14122 SDValue CC = Op.getOperand(2);
14123 MVT VT = Op.getSimpleValueType();
14126 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14127 Op.getValueType().getScalarType() == MVT::i1 &&
14128 "Cannot set masked compare for this operation");
14130 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14132 bool Unsigned = false;
14135 switch (SetCCOpcode) {
14136 default: llvm_unreachable("Unexpected SETCC condition");
14137 case ISD::SETNE: SSECC = 4; break;
14138 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14139 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14140 case ISD::SETLT: Swap = true; //fall-through
14141 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14142 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14143 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14144 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14145 case ISD::SETULE: Unsigned = true; //fall-through
14146 case ISD::SETLE: SSECC = 2; break;
14150 std::swap(Op0, Op1);
14152 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14153 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14154 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14155 DAG.getConstant(SSECC, dl, MVT::i8));
14158 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14159 /// operand \p Op1. If non-trivial (for example because it's not constant)
14160 /// return an empty value.
14161 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14163 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14167 MVT VT = Op1.getSimpleValueType();
14168 MVT EVT = VT.getVectorElementType();
14169 unsigned n = VT.getVectorNumElements();
14170 SmallVector<SDValue, 8> ULTOp1;
14172 for (unsigned i = 0; i < n; ++i) {
14173 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14174 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14177 // Avoid underflow.
14178 APInt Val = Elt->getAPIntValue();
14182 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14185 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14188 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14189 SelectionDAG &DAG) {
14190 SDValue Op0 = Op.getOperand(0);
14191 SDValue Op1 = Op.getOperand(1);
14192 SDValue CC = Op.getOperand(2);
14193 MVT VT = Op.getSimpleValueType();
14194 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14195 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14200 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14201 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14204 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14205 unsigned Opc = X86ISD::CMPP;
14206 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14207 assert(VT.getVectorNumElements() <= 16);
14208 Opc = X86ISD::CMPM;
14210 // In the two special cases we can't handle, emit two comparisons.
14213 unsigned CombineOpc;
14214 if (SetCCOpcode == ISD::SETUEQ) {
14215 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14217 assert(SetCCOpcode == ISD::SETONE);
14218 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14221 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14222 DAG.getConstant(CC0, dl, MVT::i8));
14223 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14224 DAG.getConstant(CC1, dl, MVT::i8));
14225 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14227 // Handle all other FP comparisons here.
14228 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14229 DAG.getConstant(SSECC, dl, MVT::i8));
14232 MVT VTOp0 = Op0.getSimpleValueType();
14233 assert(VTOp0 == Op1.getSimpleValueType() &&
14234 "Expected operands with same type!");
14235 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14236 "Invalid number of packed elements for source and destination!");
14238 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14239 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14240 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14241 // legalizer firstly checks if the first operand in input to the setcc has
14242 // a legal type. If so, then it promotes the return type to that same type.
14243 // Otherwise, the return type is promoted to the 'next legal type' which,
14244 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14246 // We reach this code only if the following two conditions are met:
14247 // 1. Both return type and operand type have been promoted to wider types
14248 // by the type legalizer.
14249 // 2. The original operand type has been promoted to a 256-bit vector.
14251 // Note that condition 2. only applies for AVX targets.
14252 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14253 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14256 // The non-AVX512 code below works under the assumption that source and
14257 // destination types are the same.
14258 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14259 "Value types for source and destination must be the same!");
14261 // Break 256-bit integer vector compare into smaller ones.
14262 if (VT.is256BitVector() && !Subtarget->hasInt256())
14263 return Lower256IntVSETCC(Op, DAG);
14265 EVT OpVT = Op1.getValueType();
14266 if (OpVT.getVectorElementType() == MVT::i1)
14267 return LowerBoolVSETCC_AVX512(Op, DAG);
14269 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14270 if (Subtarget->hasAVX512()) {
14271 if (Op1.getValueType().is512BitVector() ||
14272 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14273 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14274 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14276 // In AVX-512 architecture setcc returns mask with i1 elements,
14277 // But there is no compare instruction for i8 and i16 elements in KNL.
14278 // We are not talking about 512-bit operands in this case, these
14279 // types are illegal.
14281 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14282 OpVT.getVectorElementType().getSizeInBits() >= 8))
14283 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14284 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14287 // Lower using XOP integer comparisons.
14288 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14289 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14290 // Translate compare code to XOP PCOM compare mode.
14291 unsigned CmpMode = 0;
14292 switch (SetCCOpcode) {
14293 default: llvm_unreachable("Unexpected SETCC condition");
14295 case ISD::SETLT: CmpMode = 0x00; break;
14297 case ISD::SETLE: CmpMode = 0x01; break;
14299 case ISD::SETGT: CmpMode = 0x02; break;
14301 case ISD::SETGE: CmpMode = 0x03; break;
14302 case ISD::SETEQ: CmpMode = 0x04; break;
14303 case ISD::SETNE: CmpMode = 0x05; break;
14306 // Are we comparing unsigned or signed integers?
14307 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14308 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14310 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14311 DAG.getConstant(CmpMode, dl, MVT::i8));
14314 // We are handling one of the integer comparisons here. Since SSE only has
14315 // GT and EQ comparisons for integer, swapping operands and multiple
14316 // operations may be required for some comparisons.
14318 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14319 bool Subus = false;
14321 switch (SetCCOpcode) {
14322 default: llvm_unreachable("Unexpected SETCC condition");
14323 case ISD::SETNE: Invert = true;
14324 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14325 case ISD::SETLT: Swap = true;
14326 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14327 case ISD::SETGE: Swap = true;
14328 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14329 Invert = true; break;
14330 case ISD::SETULT: Swap = true;
14331 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14332 FlipSigns = true; break;
14333 case ISD::SETUGE: Swap = true;
14334 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14335 FlipSigns = true; Invert = true; break;
14338 // Special case: Use min/max operations for SETULE/SETUGE
14339 MVT VET = VT.getVectorElementType();
14341 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14342 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14345 switch (SetCCOpcode) {
14347 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14348 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14351 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14354 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14355 if (!MinMax && hasSubus) {
14356 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14358 // t = psubus Op0, Op1
14359 // pcmpeq t, <0..0>
14360 switch (SetCCOpcode) {
14362 case ISD::SETULT: {
14363 // If the comparison is against a constant we can turn this into a
14364 // setule. With psubus, setule does not require a swap. This is
14365 // beneficial because the constant in the register is no longer
14366 // destructed as the destination so it can be hoisted out of a loop.
14367 // Only do this pre-AVX since vpcmp* is no longer destructive.
14368 if (Subtarget->hasAVX())
14370 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14371 if (ULEOp1.getNode()) {
14373 Subus = true; Invert = false; Swap = false;
14377 // Psubus is better than flip-sign because it requires no inversion.
14378 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14379 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14383 Opc = X86ISD::SUBUS;
14389 std::swap(Op0, Op1);
14391 // Check that the operation in question is available (most are plain SSE2,
14392 // but PCMPGTQ and PCMPEQQ have different requirements).
14393 if (VT == MVT::v2i64) {
14394 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14395 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14397 // First cast everything to the right type.
14398 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14399 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14401 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14402 // bits of the inputs before performing those operations. The lower
14403 // compare is always unsigned.
14406 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14408 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14409 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14410 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14411 Sign, Zero, Sign, Zero);
14413 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14414 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14416 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14417 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14418 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14420 // Create masks for only the low parts/high parts of the 64 bit integers.
14421 static const int MaskHi[] = { 1, 1, 3, 3 };
14422 static const int MaskLo[] = { 0, 0, 2, 2 };
14423 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14424 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14425 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14427 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14428 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14431 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14433 return DAG.getBitcast(VT, Result);
14436 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14437 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14438 // pcmpeqd + pshufd + pand.
14439 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14441 // First cast everything to the right type.
14442 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14443 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14446 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14448 // Make sure the lower and upper halves are both all-ones.
14449 static const int Mask[] = { 1, 0, 3, 2 };
14450 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14451 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14454 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14456 return DAG.getBitcast(VT, Result);
14460 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14461 // bits of the inputs before performing those operations.
14463 EVT EltVT = VT.getVectorElementType();
14464 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14466 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14467 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14470 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14472 // If the logical-not of the result is required, perform that now.
14474 Result = DAG.getNOT(dl, Result, VT);
14477 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14480 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14481 getZeroVector(VT, Subtarget, DAG, dl));
14486 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14488 MVT VT = Op.getSimpleValueType();
14490 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14492 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14493 && "SetCC type must be 8-bit or 1-bit integer");
14494 SDValue Op0 = Op.getOperand(0);
14495 SDValue Op1 = Op.getOperand(1);
14497 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14499 // Optimize to BT if possible.
14500 // Lower (X & (1 << N)) == 0 to BT(X, N).
14501 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14502 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14503 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14504 Op1.getOpcode() == ISD::Constant &&
14505 cast<ConstantSDNode>(Op1)->isNullValue() &&
14506 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14507 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14508 if (NewSetCC.getNode()) {
14510 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14515 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14517 if (Op1.getOpcode() == ISD::Constant &&
14518 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14519 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14520 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14522 // If the input is a setcc, then reuse the input setcc or use a new one with
14523 // the inverted condition.
14524 if (Op0.getOpcode() == X86ISD::SETCC) {
14525 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14526 bool Invert = (CC == ISD::SETNE) ^
14527 cast<ConstantSDNode>(Op1)->isNullValue();
14531 CCode = X86::GetOppositeBranchCondition(CCode);
14532 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14533 DAG.getConstant(CCode, dl, MVT::i8),
14534 Op0.getOperand(1));
14536 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14540 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14541 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14542 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14544 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14545 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14548 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14549 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14550 if (X86CC == X86::COND_INVALID)
14553 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14554 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14555 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14556 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14558 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14562 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14563 static bool isX86LogicalCmp(SDValue Op) {
14564 unsigned Opc = Op.getNode()->getOpcode();
14565 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14566 Opc == X86ISD::SAHF)
14568 if (Op.getResNo() == 1 &&
14569 (Opc == X86ISD::ADD ||
14570 Opc == X86ISD::SUB ||
14571 Opc == X86ISD::ADC ||
14572 Opc == X86ISD::SBB ||
14573 Opc == X86ISD::SMUL ||
14574 Opc == X86ISD::UMUL ||
14575 Opc == X86ISD::INC ||
14576 Opc == X86ISD::DEC ||
14577 Opc == X86ISD::OR ||
14578 Opc == X86ISD::XOR ||
14579 Opc == X86ISD::AND))
14582 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14588 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14589 if (V.getOpcode() != ISD::TRUNCATE)
14592 SDValue VOp0 = V.getOperand(0);
14593 unsigned InBits = VOp0.getValueSizeInBits();
14594 unsigned Bits = V.getValueSizeInBits();
14595 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14598 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14599 bool addTest = true;
14600 SDValue Cond = Op.getOperand(0);
14601 SDValue Op1 = Op.getOperand(1);
14602 SDValue Op2 = Op.getOperand(2);
14604 EVT VT = Op1.getValueType();
14607 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14608 // are available or VBLENDV if AVX is available.
14609 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14610 if (Cond.getOpcode() == ISD::SETCC &&
14611 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14612 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14613 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14614 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14615 int SSECC = translateX86FSETCC(
14616 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14619 if (Subtarget->hasAVX512()) {
14620 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14621 DAG.getConstant(SSECC, DL, MVT::i8));
14622 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14625 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14626 DAG.getConstant(SSECC, DL, MVT::i8));
14628 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14629 // of 3 logic instructions for size savings and potentially speed.
14630 // Unfortunately, there is no scalar form of VBLENDV.
14632 // If either operand is a constant, don't try this. We can expect to
14633 // optimize away at least one of the logic instructions later in that
14634 // case, so that sequence would be faster than a variable blend.
14636 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14637 // uses XMM0 as the selection register. That may need just as many
14638 // instructions as the AND/ANDN/OR sequence due to register moves, so
14641 if (Subtarget->hasAVX() &&
14642 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14644 // Convert to vectors, do a VSELECT, and convert back to scalar.
14645 // All of the conversions should be optimized away.
14647 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14648 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14649 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14650 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14652 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14653 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14655 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14657 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14658 VSel, DAG.getIntPtrConstant(0, DL));
14660 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14661 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14662 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14666 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14668 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14669 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14670 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14671 Op1Scalar = Op1.getOperand(0);
14673 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14674 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14675 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14676 Op2Scalar = Op2.getOperand(0);
14677 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14678 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14679 Op1Scalar.getValueType(),
14680 Cond, Op1Scalar, Op2Scalar);
14681 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14682 return DAG.getBitcast(VT, newSelect);
14683 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14684 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14685 DAG.getIntPtrConstant(0, DL));
14689 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14690 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14691 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14692 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14693 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14694 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14695 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14697 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14700 if (Cond.getOpcode() == ISD::SETCC) {
14701 SDValue NewCond = LowerSETCC(Cond, DAG);
14702 if (NewCond.getNode())
14706 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14707 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14708 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14709 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14710 if (Cond.getOpcode() == X86ISD::SETCC &&
14711 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14712 isZero(Cond.getOperand(1).getOperand(1))) {
14713 SDValue Cmp = Cond.getOperand(1);
14715 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14717 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14718 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14719 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14721 SDValue CmpOp0 = Cmp.getOperand(0);
14722 // Apply further optimizations for special cases
14723 // (select (x != 0), -1, 0) -> neg & sbb
14724 // (select (x == 0), 0, -1) -> neg & sbb
14725 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14726 if (YC->isNullValue() &&
14727 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14728 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14729 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14730 DAG.getConstant(0, DL,
14731 CmpOp0.getValueType()),
14733 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14734 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14735 SDValue(Neg.getNode(), 1));
14739 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14740 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14741 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14743 SDValue Res = // Res = 0 or -1.
14744 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14745 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14747 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14748 Res = DAG.getNOT(DL, Res, Res.getValueType());
14750 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14751 if (!N2C || !N2C->isNullValue())
14752 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14757 // Look past (and (setcc_carry (cmp ...)), 1).
14758 if (Cond.getOpcode() == ISD::AND &&
14759 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14760 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14761 if (C && C->getAPIntValue() == 1)
14762 Cond = Cond.getOperand(0);
14765 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14766 // setting operand in place of the X86ISD::SETCC.
14767 unsigned CondOpcode = Cond.getOpcode();
14768 if (CondOpcode == X86ISD::SETCC ||
14769 CondOpcode == X86ISD::SETCC_CARRY) {
14770 CC = Cond.getOperand(0);
14772 SDValue Cmp = Cond.getOperand(1);
14773 unsigned Opc = Cmp.getOpcode();
14774 MVT VT = Op.getSimpleValueType();
14776 bool IllegalFPCMov = false;
14777 if (VT.isFloatingPoint() && !VT.isVector() &&
14778 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14779 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14781 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14782 Opc == X86ISD::BT) { // FIXME
14786 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14787 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14788 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14789 Cond.getOperand(0).getValueType() != MVT::i8)) {
14790 SDValue LHS = Cond.getOperand(0);
14791 SDValue RHS = Cond.getOperand(1);
14792 unsigned X86Opcode;
14795 switch (CondOpcode) {
14796 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14797 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14798 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14799 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14800 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14801 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14802 default: llvm_unreachable("unexpected overflowing operator");
14804 if (CondOpcode == ISD::UMULO)
14805 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14808 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14810 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14812 if (CondOpcode == ISD::UMULO)
14813 Cond = X86Op.getValue(2);
14815 Cond = X86Op.getValue(1);
14817 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14822 // Look past the truncate if the high bits are known zero.
14823 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14824 Cond = Cond.getOperand(0);
14826 // We know the result of AND is compared against zero. Try to match
14828 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14829 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14830 if (NewSetCC.getNode()) {
14831 CC = NewSetCC.getOperand(0);
14832 Cond = NewSetCC.getOperand(1);
14839 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14840 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14843 // a < b ? -1 : 0 -> RES = ~setcc_carry
14844 // a < b ? 0 : -1 -> RES = setcc_carry
14845 // a >= b ? -1 : 0 -> RES = setcc_carry
14846 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14847 if (Cond.getOpcode() == X86ISD::SUB) {
14848 Cond = ConvertCmpIfNecessary(Cond, DAG);
14849 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14851 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14852 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14853 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14854 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14856 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14857 return DAG.getNOT(DL, Res, Res.getValueType());
14862 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14863 // widen the cmov and push the truncate through. This avoids introducing a new
14864 // branch during isel and doesn't add any extensions.
14865 if (Op.getValueType() == MVT::i8 &&
14866 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14867 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14868 if (T1.getValueType() == T2.getValueType() &&
14869 // Blacklist CopyFromReg to avoid partial register stalls.
14870 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14871 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14872 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14873 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14877 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14878 // condition is true.
14879 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14880 SDValue Ops[] = { Op2, Op1, CC, Cond };
14881 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14884 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14885 const X86Subtarget *Subtarget,
14886 SelectionDAG &DAG) {
14887 MVT VT = Op->getSimpleValueType(0);
14888 SDValue In = Op->getOperand(0);
14889 MVT InVT = In.getSimpleValueType();
14890 MVT VTElt = VT.getVectorElementType();
14891 MVT InVTElt = InVT.getVectorElementType();
14895 if ((InVTElt == MVT::i1) &&
14896 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14897 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14899 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14900 VTElt.getSizeInBits() <= 16)) ||
14902 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14903 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14905 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14906 VTElt.getSizeInBits() >= 32))))
14907 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14909 unsigned int NumElts = VT.getVectorNumElements();
14911 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14914 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14915 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14916 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14917 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14920 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14921 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14923 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14926 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14928 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14929 if (VT.is512BitVector())
14931 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14934 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14935 const X86Subtarget *Subtarget,
14936 SelectionDAG &DAG) {
14937 SDValue In = Op->getOperand(0);
14938 MVT VT = Op->getSimpleValueType(0);
14939 MVT InVT = In.getSimpleValueType();
14940 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14942 MVT InSVT = InVT.getScalarType();
14943 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14945 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14947 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14952 // SSE41 targets can use the pmovsx* instructions directly.
14953 if (Subtarget->hasSSE41())
14954 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14956 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14960 // As SRAI is only available on i16/i32 types, we expand only up to i32
14961 // and handle i64 separately.
14962 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14963 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14964 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14965 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14966 Curr = DAG.getBitcast(CurrVT, Curr);
14969 SDValue SignExt = Curr;
14970 if (CurrVT != InVT) {
14971 unsigned SignExtShift =
14972 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14973 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14974 DAG.getConstant(SignExtShift, dl, MVT::i8));
14980 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14981 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14982 DAG.getConstant(31, dl, MVT::i8));
14983 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14984 return DAG.getBitcast(VT, Ext);
14990 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14991 SelectionDAG &DAG) {
14992 MVT VT = Op->getSimpleValueType(0);
14993 SDValue In = Op->getOperand(0);
14994 MVT InVT = In.getSimpleValueType();
14997 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14998 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15000 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15001 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15002 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15005 if (Subtarget->hasInt256())
15006 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15008 // Optimize vectors in AVX mode
15009 // Sign extend v8i16 to v8i32 and
15012 // Divide input vector into two parts
15013 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15014 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15015 // concat the vectors to original VT
15017 unsigned NumElems = InVT.getVectorNumElements();
15018 SDValue Undef = DAG.getUNDEF(InVT);
15020 SmallVector<int,8> ShufMask1(NumElems, -1);
15021 for (unsigned i = 0; i != NumElems/2; ++i)
15024 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15026 SmallVector<int,8> ShufMask2(NumElems, -1);
15027 for (unsigned i = 0; i != NumElems/2; ++i)
15028 ShufMask2[i] = i + NumElems/2;
15030 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15032 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15033 VT.getVectorNumElements()/2);
15035 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15036 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15038 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15041 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15042 // may emit an illegal shuffle but the expansion is still better than scalar
15043 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15044 // we'll emit a shuffle and a arithmetic shift.
15045 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15046 // TODO: It is possible to support ZExt by zeroing the undef values during
15047 // the shuffle phase or after the shuffle.
15048 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15049 SelectionDAG &DAG) {
15050 MVT RegVT = Op.getSimpleValueType();
15051 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15052 assert(RegVT.isInteger() &&
15053 "We only custom lower integer vector sext loads.");
15055 // Nothing useful we can do without SSE2 shuffles.
15056 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15058 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15060 EVT MemVT = Ld->getMemoryVT();
15061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15062 unsigned RegSz = RegVT.getSizeInBits();
15064 ISD::LoadExtType Ext = Ld->getExtensionType();
15066 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15067 && "Only anyext and sext are currently implemented.");
15068 assert(MemVT != RegVT && "Cannot extend to the same type");
15069 assert(MemVT.isVector() && "Must load a vector from memory");
15071 unsigned NumElems = RegVT.getVectorNumElements();
15072 unsigned MemSz = MemVT.getSizeInBits();
15073 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15075 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15076 // The only way in which we have a legal 256-bit vector result but not the
15077 // integer 256-bit operations needed to directly lower a sextload is if we
15078 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15079 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15080 // correctly legalized. We do this late to allow the canonical form of
15081 // sextload to persist throughout the rest of the DAG combiner -- it wants
15082 // to fold together any extensions it can, and so will fuse a sign_extend
15083 // of an sextload into a sextload targeting a wider value.
15085 if (MemSz == 128) {
15086 // Just switch this to a normal load.
15087 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15088 "it must be a legal 128-bit vector "
15090 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15091 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15092 Ld->isInvariant(), Ld->getAlignment());
15094 assert(MemSz < 128 &&
15095 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15096 // Do an sext load to a 128-bit vector type. We want to use the same
15097 // number of elements, but elements half as wide. This will end up being
15098 // recursively lowered by this routine, but will succeed as we definitely
15099 // have all the necessary features if we're using AVX1.
15101 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15102 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15104 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15105 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15106 Ld->isNonTemporal(), Ld->isInvariant(),
15107 Ld->getAlignment());
15110 // Replace chain users with the new chain.
15111 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15112 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15114 // Finally, do a normal sign-extend to the desired register.
15115 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15118 // All sizes must be a power of two.
15119 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15120 "Non-power-of-two elements are not custom lowered!");
15122 // Attempt to load the original value using scalar loads.
15123 // Find the largest scalar type that divides the total loaded size.
15124 MVT SclrLoadTy = MVT::i8;
15125 for (MVT Tp : MVT::integer_valuetypes()) {
15126 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15131 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15132 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15134 SclrLoadTy = MVT::f64;
15136 // Calculate the number of scalar loads that we need to perform
15137 // in order to load our vector from memory.
15138 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15140 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15141 "Can only lower sext loads with a single scalar load!");
15143 unsigned loadRegZize = RegSz;
15144 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15147 // Represent our vector as a sequence of elements which are the
15148 // largest scalar that we can load.
15149 EVT LoadUnitVecVT = EVT::getVectorVT(
15150 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15152 // Represent the data using the same element type that is stored in
15153 // memory. In practice, we ''widen'' MemVT.
15155 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15156 loadRegZize / MemVT.getScalarType().getSizeInBits());
15158 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15159 "Invalid vector type");
15161 // We can't shuffle using an illegal type.
15162 assert(TLI.isTypeLegal(WideVecVT) &&
15163 "We only lower types that form legal widened vector types");
15165 SmallVector<SDValue, 8> Chains;
15166 SDValue Ptr = Ld->getBasePtr();
15167 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15168 TLI.getPointerTy(DAG.getDataLayout()));
15169 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15171 for (unsigned i = 0; i < NumLoads; ++i) {
15172 // Perform a single load.
15173 SDValue ScalarLoad =
15174 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15175 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15176 Ld->getAlignment());
15177 Chains.push_back(ScalarLoad.getValue(1));
15178 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15179 // another round of DAGCombining.
15181 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15183 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15184 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15186 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15189 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15191 // Bitcast the loaded value to a vector of the original element type, in
15192 // the size of the target vector type.
15193 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15194 unsigned SizeRatio = RegSz / MemSz;
15196 if (Ext == ISD::SEXTLOAD) {
15197 // If we have SSE4.1, we can directly emit a VSEXT node.
15198 if (Subtarget->hasSSE41()) {
15199 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15200 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15204 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15206 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15207 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15209 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15210 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15214 // Redistribute the loaded elements into the different locations.
15215 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15216 for (unsigned i = 0; i != NumElems; ++i)
15217 ShuffleVec[i * SizeRatio] = i;
15219 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15220 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15222 // Bitcast to the requested type.
15223 Shuff = DAG.getBitcast(RegVT, Shuff);
15224 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15228 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15229 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15230 // from the AND / OR.
15231 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15232 Opc = Op.getOpcode();
15233 if (Opc != ISD::OR && Opc != ISD::AND)
15235 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15236 Op.getOperand(0).hasOneUse() &&
15237 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15238 Op.getOperand(1).hasOneUse());
15241 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15242 // 1 and that the SETCC node has a single use.
15243 static bool isXor1OfSetCC(SDValue Op) {
15244 if (Op.getOpcode() != ISD::XOR)
15246 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15247 if (N1C && N1C->getAPIntValue() == 1) {
15248 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15249 Op.getOperand(0).hasOneUse();
15254 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15255 bool addTest = true;
15256 SDValue Chain = Op.getOperand(0);
15257 SDValue Cond = Op.getOperand(1);
15258 SDValue Dest = Op.getOperand(2);
15261 bool Inverted = false;
15263 if (Cond.getOpcode() == ISD::SETCC) {
15264 // Check for setcc([su]{add,sub,mul}o == 0).
15265 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15266 isa<ConstantSDNode>(Cond.getOperand(1)) &&
15267 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15268 Cond.getOperand(0).getResNo() == 1 &&
15269 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15270 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15271 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15272 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15273 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15274 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15276 Cond = Cond.getOperand(0);
15278 SDValue NewCond = LowerSETCC(Cond, DAG);
15279 if (NewCond.getNode())
15284 // FIXME: LowerXALUO doesn't handle these!!
15285 else if (Cond.getOpcode() == X86ISD::ADD ||
15286 Cond.getOpcode() == X86ISD::SUB ||
15287 Cond.getOpcode() == X86ISD::SMUL ||
15288 Cond.getOpcode() == X86ISD::UMUL)
15289 Cond = LowerXALUO(Cond, DAG);
15292 // Look pass (and (setcc_carry (cmp ...)), 1).
15293 if (Cond.getOpcode() == ISD::AND &&
15294 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15295 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15296 if (C && C->getAPIntValue() == 1)
15297 Cond = Cond.getOperand(0);
15300 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15301 // setting operand in place of the X86ISD::SETCC.
15302 unsigned CondOpcode = Cond.getOpcode();
15303 if (CondOpcode == X86ISD::SETCC ||
15304 CondOpcode == X86ISD::SETCC_CARRY) {
15305 CC = Cond.getOperand(0);
15307 SDValue Cmp = Cond.getOperand(1);
15308 unsigned Opc = Cmp.getOpcode();
15309 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15310 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15314 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15318 // These can only come from an arithmetic instruction with overflow,
15319 // e.g. SADDO, UADDO.
15320 Cond = Cond.getNode()->getOperand(1);
15326 CondOpcode = Cond.getOpcode();
15327 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15328 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15329 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15330 Cond.getOperand(0).getValueType() != MVT::i8)) {
15331 SDValue LHS = Cond.getOperand(0);
15332 SDValue RHS = Cond.getOperand(1);
15333 unsigned X86Opcode;
15336 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15337 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15339 switch (CondOpcode) {
15340 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15342 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15344 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15347 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15348 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15350 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15352 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15355 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15356 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15357 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15358 default: llvm_unreachable("unexpected overflowing operator");
15361 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15362 if (CondOpcode == ISD::UMULO)
15363 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15366 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15368 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15370 if (CondOpcode == ISD::UMULO)
15371 Cond = X86Op.getValue(2);
15373 Cond = X86Op.getValue(1);
15375 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15379 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15380 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15381 if (CondOpc == ISD::OR) {
15382 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15383 // two branches instead of an explicit OR instruction with a
15385 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15386 isX86LogicalCmp(Cmp)) {
15387 CC = Cond.getOperand(0).getOperand(0);
15388 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15389 Chain, Dest, CC, Cmp);
15390 CC = Cond.getOperand(1).getOperand(0);
15394 } else { // ISD::AND
15395 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15396 // two branches instead of an explicit AND instruction with a
15397 // separate test. However, we only do this if this block doesn't
15398 // have a fall-through edge, because this requires an explicit
15399 // jmp when the condition is false.
15400 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15401 isX86LogicalCmp(Cmp) &&
15402 Op.getNode()->hasOneUse()) {
15403 X86::CondCode CCode =
15404 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15405 CCode = X86::GetOppositeBranchCondition(CCode);
15406 CC = DAG.getConstant(CCode, dl, MVT::i8);
15407 SDNode *User = *Op.getNode()->use_begin();
15408 // Look for an unconditional branch following this conditional branch.
15409 // We need this because we need to reverse the successors in order
15410 // to implement FCMP_OEQ.
15411 if (User->getOpcode() == ISD::BR) {
15412 SDValue FalseBB = User->getOperand(1);
15414 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15415 assert(NewBR == User);
15419 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15420 Chain, Dest, CC, Cmp);
15421 X86::CondCode CCode =
15422 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15423 CCode = X86::GetOppositeBranchCondition(CCode);
15424 CC = DAG.getConstant(CCode, dl, MVT::i8);
15430 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15431 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15432 // It should be transformed during dag combiner except when the condition
15433 // is set by a arithmetics with overflow node.
15434 X86::CondCode CCode =
15435 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15436 CCode = X86::GetOppositeBranchCondition(CCode);
15437 CC = DAG.getConstant(CCode, dl, MVT::i8);
15438 Cond = Cond.getOperand(0).getOperand(1);
15440 } else if (Cond.getOpcode() == ISD::SETCC &&
15441 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15442 // For FCMP_OEQ, we can emit
15443 // two branches instead of an explicit AND instruction with a
15444 // separate test. However, we only do this if this block doesn't
15445 // have a fall-through edge, because this requires an explicit
15446 // jmp when the condition is false.
15447 if (Op.getNode()->hasOneUse()) {
15448 SDNode *User = *Op.getNode()->use_begin();
15449 // Look for an unconditional branch following this conditional branch.
15450 // We need this because we need to reverse the successors in order
15451 // to implement FCMP_OEQ.
15452 if (User->getOpcode() == ISD::BR) {
15453 SDValue FalseBB = User->getOperand(1);
15455 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15456 assert(NewBR == User);
15460 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15461 Cond.getOperand(0), Cond.getOperand(1));
15462 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15463 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15464 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15465 Chain, Dest, CC, Cmp);
15466 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15471 } else if (Cond.getOpcode() == ISD::SETCC &&
15472 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15473 // For FCMP_UNE, we can emit
15474 // two branches instead of an explicit AND instruction with a
15475 // separate test. However, we only do this if this block doesn't
15476 // have a fall-through edge, because this requires an explicit
15477 // jmp when the condition is false.
15478 if (Op.getNode()->hasOneUse()) {
15479 SDNode *User = *Op.getNode()->use_begin();
15480 // Look for an unconditional branch following this conditional branch.
15481 // We need this because we need to reverse the successors in order
15482 // to implement FCMP_UNE.
15483 if (User->getOpcode() == ISD::BR) {
15484 SDValue FalseBB = User->getOperand(1);
15486 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15487 assert(NewBR == User);
15490 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15491 Cond.getOperand(0), Cond.getOperand(1));
15492 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15493 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15494 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15495 Chain, Dest, CC, Cmp);
15496 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15506 // Look pass the truncate if the high bits are known zero.
15507 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15508 Cond = Cond.getOperand(0);
15510 // We know the result of AND is compared against zero. Try to match
15512 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15513 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15514 if (NewSetCC.getNode()) {
15515 CC = NewSetCC.getOperand(0);
15516 Cond = NewSetCC.getOperand(1);
15523 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15524 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15525 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15527 Cond = ConvertCmpIfNecessary(Cond, DAG);
15528 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15529 Chain, Dest, CC, Cond);
15532 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15533 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15534 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15535 // that the guard pages used by the OS virtual memory manager are allocated in
15536 // correct sequence.
15538 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15539 SelectionDAG &DAG) const {
15540 MachineFunction &MF = DAG.getMachineFunction();
15541 bool SplitStack = MF.shouldSplitStack();
15542 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15547 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15548 SDNode* Node = Op.getNode();
15550 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15551 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15552 " not tell us which reg is the stack pointer!");
15553 EVT VT = Node->getValueType(0);
15554 SDValue Tmp1 = SDValue(Node, 0);
15555 SDValue Tmp2 = SDValue(Node, 1);
15556 SDValue Tmp3 = Node->getOperand(2);
15557 SDValue Chain = Tmp1.getOperand(0);
15559 // Chain the dynamic stack allocation so that it doesn't modify the stack
15560 // pointer when other instructions are using the stack.
15561 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15564 SDValue Size = Tmp2.getOperand(1);
15565 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15566 Chain = SP.getValue(1);
15567 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15568 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15569 unsigned StackAlign = TFI.getStackAlignment();
15570 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15571 if (Align > StackAlign)
15572 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15573 DAG.getConstant(-(uint64_t)Align, dl, VT));
15574 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15576 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15577 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15580 SDValue Ops[2] = { Tmp1, Tmp2 };
15581 return DAG.getMergeValues(Ops, dl);
15585 SDValue Chain = Op.getOperand(0);
15586 SDValue Size = Op.getOperand(1);
15587 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15588 EVT VT = Op.getNode()->getValueType(0);
15590 bool Is64Bit = Subtarget->is64Bit();
15591 MVT SPTy = getPointerTy(DAG.getDataLayout());
15594 MachineRegisterInfo &MRI = MF.getRegInfo();
15597 // The 64 bit implementation of segmented stacks needs to clobber both r10
15598 // r11. This makes it impossible to use it along with nested parameters.
15599 const Function *F = MF.getFunction();
15601 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15603 if (I->hasNestAttr())
15604 report_fatal_error("Cannot use segmented stacks with functions that "
15605 "have nested arguments.");
15608 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15609 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15610 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15611 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15612 DAG.getRegister(Vreg, SPTy));
15613 SDValue Ops1[2] = { Value, Chain };
15614 return DAG.getMergeValues(Ops1, dl);
15617 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15619 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15620 Flag = Chain.getValue(1);
15621 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15623 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15625 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15626 unsigned SPReg = RegInfo->getStackRegister();
15627 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15628 Chain = SP.getValue(1);
15631 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15632 DAG.getConstant(-(uint64_t)Align, dl, VT));
15633 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15636 SDValue Ops1[2] = { SP, Chain };
15637 return DAG.getMergeValues(Ops1, dl);
15641 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15642 MachineFunction &MF = DAG.getMachineFunction();
15643 auto PtrVT = getPointerTy(MF.getDataLayout());
15644 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15646 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15649 if (!Subtarget->is64Bit() ||
15650 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15651 // vastart just stores the address of the VarArgsFrameIndex slot into the
15652 // memory location argument.
15653 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15654 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15655 MachinePointerInfo(SV), false, false, 0);
15659 // gp_offset (0 - 6 * 8)
15660 // fp_offset (48 - 48 + 8 * 16)
15661 // overflow_arg_area (point to parameters coming in memory).
15663 SmallVector<SDValue, 8> MemOps;
15664 SDValue FIN = Op.getOperand(1);
15666 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15667 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15669 FIN, MachinePointerInfo(SV), false, false, 0);
15670 MemOps.push_back(Store);
15673 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15674 Store = DAG.getStore(Op.getOperand(0), DL,
15675 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15677 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15678 MemOps.push_back(Store);
15680 // Store ptr to overflow_arg_area
15681 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15682 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15683 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15684 MachinePointerInfo(SV, 8),
15686 MemOps.push_back(Store);
15688 // Store ptr to reg_save_area.
15689 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15690 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15691 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15692 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15693 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15694 MemOps.push_back(Store);
15695 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15698 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15699 assert(Subtarget->is64Bit() &&
15700 "LowerVAARG only handles 64-bit va_arg!");
15701 assert(Op.getNode()->getNumOperands() == 4);
15703 MachineFunction &MF = DAG.getMachineFunction();
15704 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15705 // The Win64 ABI uses char* instead of a structure.
15706 return DAG.expandVAArg(Op.getNode());
15708 SDValue Chain = Op.getOperand(0);
15709 SDValue SrcPtr = Op.getOperand(1);
15710 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15711 unsigned Align = Op.getConstantOperandVal(3);
15714 EVT ArgVT = Op.getNode()->getValueType(0);
15715 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15716 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15719 // Decide which area this value should be read from.
15720 // TODO: Implement the AMD64 ABI in its entirety. This simple
15721 // selection mechanism works only for the basic types.
15722 if (ArgVT == MVT::f80) {
15723 llvm_unreachable("va_arg for f80 not yet implemented");
15724 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15725 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15726 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15727 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15729 llvm_unreachable("Unhandled argument type in LowerVAARG");
15732 if (ArgMode == 2) {
15733 // Sanity Check: Make sure using fp_offset makes sense.
15734 assert(!Subtarget->useSoftFloat() &&
15735 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15736 Subtarget->hasSSE1());
15739 // Insert VAARG_64 node into the DAG
15740 // VAARG_64 returns two values: Variable Argument Address, Chain
15741 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15742 DAG.getConstant(ArgMode, dl, MVT::i8),
15743 DAG.getConstant(Align, dl, MVT::i32)};
15744 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15745 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15746 VTs, InstOps, MVT::i64,
15747 MachinePointerInfo(SV),
15749 /*Volatile=*/false,
15751 /*WriteMem=*/true);
15752 Chain = VAARG.getValue(1);
15754 // Load the next argument and return it
15755 return DAG.getLoad(ArgVT, dl,
15758 MachinePointerInfo(),
15759 false, false, false, 0);
15762 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15763 SelectionDAG &DAG) {
15764 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15765 // where a va_list is still an i8*.
15766 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15767 if (Subtarget->isCallingConvWin64(
15768 DAG.getMachineFunction().getFunction()->getCallingConv()))
15769 // Probably a Win64 va_copy.
15770 return DAG.expandVACopy(Op.getNode());
15772 SDValue Chain = Op.getOperand(0);
15773 SDValue DstPtr = Op.getOperand(1);
15774 SDValue SrcPtr = Op.getOperand(2);
15775 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15776 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15779 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15780 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15782 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15785 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15786 // amount is a constant. Takes immediate version of shift as input.
15787 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15788 SDValue SrcOp, uint64_t ShiftAmt,
15789 SelectionDAG &DAG) {
15790 MVT ElementType = VT.getVectorElementType();
15792 // Fold this packed shift into its first operand if ShiftAmt is 0.
15796 // Check for ShiftAmt >= element width
15797 if (ShiftAmt >= ElementType.getSizeInBits()) {
15798 if (Opc == X86ISD::VSRAI)
15799 ShiftAmt = ElementType.getSizeInBits() - 1;
15801 return DAG.getConstant(0, dl, VT);
15804 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15805 && "Unknown target vector shift-by-constant node");
15807 // Fold this packed vector shift into a build vector if SrcOp is a
15808 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15809 if (VT == SrcOp.getSimpleValueType() &&
15810 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15811 SmallVector<SDValue, 8> Elts;
15812 unsigned NumElts = SrcOp->getNumOperands();
15813 ConstantSDNode *ND;
15816 default: llvm_unreachable(nullptr);
15817 case X86ISD::VSHLI:
15818 for (unsigned i=0; i!=NumElts; ++i) {
15819 SDValue CurrentOp = SrcOp->getOperand(i);
15820 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15821 Elts.push_back(CurrentOp);
15824 ND = cast<ConstantSDNode>(CurrentOp);
15825 const APInt &C = ND->getAPIntValue();
15826 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15829 case X86ISD::VSRLI:
15830 for (unsigned i=0; i!=NumElts; ++i) {
15831 SDValue CurrentOp = SrcOp->getOperand(i);
15832 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15833 Elts.push_back(CurrentOp);
15836 ND = cast<ConstantSDNode>(CurrentOp);
15837 const APInt &C = ND->getAPIntValue();
15838 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15841 case X86ISD::VSRAI:
15842 for (unsigned i=0; i!=NumElts; ++i) {
15843 SDValue CurrentOp = SrcOp->getOperand(i);
15844 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15845 Elts.push_back(CurrentOp);
15848 ND = cast<ConstantSDNode>(CurrentOp);
15849 const APInt &C = ND->getAPIntValue();
15850 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15855 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15858 return DAG.getNode(Opc, dl, VT, SrcOp,
15859 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15862 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15863 // may or may not be a constant. Takes immediate version of shift as input.
15864 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15865 SDValue SrcOp, SDValue ShAmt,
15866 SelectionDAG &DAG) {
15867 MVT SVT = ShAmt.getSimpleValueType();
15868 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15870 // Catch shift-by-constant.
15871 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15872 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15873 CShAmt->getZExtValue(), DAG);
15875 // Change opcode to non-immediate version
15877 default: llvm_unreachable("Unknown target vector shift node");
15878 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15879 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15880 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15883 const X86Subtarget &Subtarget =
15884 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15885 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15886 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15887 // Let the shuffle legalizer expand this shift amount node.
15888 SDValue Op0 = ShAmt.getOperand(0);
15889 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15890 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15892 // Need to build a vector containing shift amount.
15893 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15894 SmallVector<SDValue, 4> ShOps;
15895 ShOps.push_back(ShAmt);
15896 if (SVT == MVT::i32) {
15897 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15898 ShOps.push_back(DAG.getUNDEF(SVT));
15900 ShOps.push_back(DAG.getUNDEF(SVT));
15902 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15903 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15906 // The return type has to be a 128-bit type with the same element
15907 // type as the input type.
15908 MVT EltVT = VT.getVectorElementType();
15909 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15911 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15912 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15915 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15916 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15917 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15918 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15919 SDValue PreservedSrc,
15920 const X86Subtarget *Subtarget,
15921 SelectionDAG &DAG) {
15922 EVT VT = Op.getValueType();
15923 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15924 MVT::i1, VT.getVectorNumElements());
15925 SDValue VMask = SDValue();
15926 unsigned OpcodeSelect = ISD::VSELECT;
15929 assert(MaskVT.isSimple() && "invalid mask type");
15931 if (isAllOnes(Mask))
15934 if (MaskVT.bitsGT(Mask.getValueType())) {
15935 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15936 MaskVT.getSizeInBits());
15937 VMask = DAG.getBitcast(MaskVT,
15938 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15940 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15941 Mask.getValueType().getSizeInBits());
15942 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15943 // are extracted by EXTRACT_SUBVECTOR.
15944 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15945 DAG.getBitcast(BitcastVT, Mask),
15946 DAG.getIntPtrConstant(0, dl));
15949 switch (Op.getOpcode()) {
15951 case X86ISD::PCMPEQM:
15952 case X86ISD::PCMPGTM:
15954 case X86ISD::CMPMU:
15955 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15956 case X86ISD::VFPCLASS:
15957 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15958 case X86ISD::VTRUNC:
15959 case X86ISD::VTRUNCS:
15960 case X86ISD::VTRUNCUS:
15961 // We can't use ISD::VSELECT here because it is not always "Legal"
15962 // for the destination type. For example vpmovqb require only AVX512
15963 // and vselect that can operate on byte element type require BWI
15964 OpcodeSelect = X86ISD::SELECT;
15967 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15968 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15969 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15972 /// \brief Creates an SDNode for a predicated scalar operation.
15973 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15974 /// The mask is coming as MVT::i8 and it should be truncated
15975 /// to MVT::i1 while lowering masking intrinsics.
15976 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15977 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15978 /// for a scalar instruction.
15979 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15980 SDValue PreservedSrc,
15981 const X86Subtarget *Subtarget,
15982 SelectionDAG &DAG) {
15983 if (isAllOnes(Mask))
15986 EVT VT = Op.getValueType();
15988 // The mask should be of type MVT::i1
15989 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15991 if (Op.getOpcode() == X86ISD::FSETCC)
15992 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15994 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15995 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15996 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15999 static int getSEHRegistrationNodeSize(const Function *Fn) {
16000 if (!Fn->hasPersonalityFn())
16001 report_fatal_error(
16002 "querying registration node size for function without personality");
16003 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16004 // WinEHStatePass for the full struct definition.
16005 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16006 case EHPersonality::MSVC_X86SEH: return 24;
16007 case EHPersonality::MSVC_CXX: return 16;
16010 report_fatal_error("can only recover FP for MSVC EH personality functions");
16013 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16014 /// function or when returning to a parent frame after catching an exception, we
16015 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16016 /// Here's the math:
16017 /// RegNodeBase = EntryEBP - RegNodeSize
16018 /// ParentFP = RegNodeBase - RegNodeFrameOffset
16019 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16020 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16021 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16022 SDValue EntryEBP) {
16023 MachineFunction &MF = DAG.getMachineFunction();
16026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16027 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16029 // It's possible that the parent function no longer has a personality function
16030 // if the exceptional code was optimized away, in which case we just return
16031 // the incoming EBP.
16032 if (!Fn->hasPersonalityFn())
16035 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16037 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16039 MCSymbol *OffsetSym =
16040 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16041 GlobalValue::getRealLinkageName(Fn->getName()));
16042 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16043 SDValue RegNodeFrameOffset =
16044 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16046 // RegNodeBase = EntryEBP - RegNodeSize
16047 // ParentFP = RegNodeBase - RegNodeFrameOffset
16048 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16049 DAG.getConstant(RegNodeSize, dl, PtrVT));
16050 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16053 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16054 SelectionDAG &DAG) {
16056 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16057 EVT VT = Op.getValueType();
16058 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16060 switch(IntrData->Type) {
16061 case INTR_TYPE_1OP:
16062 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16063 case INTR_TYPE_2OP:
16064 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16066 case INTR_TYPE_2OP_IMM8:
16067 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16068 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16069 case INTR_TYPE_3OP:
16070 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16071 Op.getOperand(2), Op.getOperand(3));
16072 case INTR_TYPE_4OP:
16073 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16074 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16075 case INTR_TYPE_1OP_MASK_RM: {
16076 SDValue Src = Op.getOperand(1);
16077 SDValue PassThru = Op.getOperand(2);
16078 SDValue Mask = Op.getOperand(3);
16079 SDValue RoundingMode;
16080 // We allways add rounding mode to the Node.
16081 // If the rounding mode is not specified, we add the
16082 // "current direction" mode.
16083 if (Op.getNumOperands() == 4)
16085 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16087 RoundingMode = Op.getOperand(4);
16088 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16089 if (IntrWithRoundingModeOpcode != 0)
16090 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16091 X86::STATIC_ROUNDING::CUR_DIRECTION)
16092 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16093 dl, Op.getValueType(), Src, RoundingMode),
16094 Mask, PassThru, Subtarget, DAG);
16095 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16097 Mask, PassThru, Subtarget, DAG);
16099 case INTR_TYPE_1OP_MASK: {
16100 SDValue Src = Op.getOperand(1);
16101 SDValue PassThru = Op.getOperand(2);
16102 SDValue Mask = Op.getOperand(3);
16103 // We add rounding mode to the Node when
16104 // - RM Opcode is specified and
16105 // - RM is not "current direction".
16106 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16107 if (IntrWithRoundingModeOpcode != 0) {
16108 SDValue Rnd = Op.getOperand(4);
16109 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16110 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16111 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16112 dl, Op.getValueType(),
16114 Mask, PassThru, Subtarget, DAG);
16117 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16118 Mask, PassThru, Subtarget, DAG);
16120 case INTR_TYPE_SCALAR_MASK: {
16121 SDValue Src1 = Op.getOperand(1);
16122 SDValue Src2 = Op.getOperand(2);
16123 SDValue passThru = Op.getOperand(3);
16124 SDValue Mask = Op.getOperand(4);
16125 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16126 Mask, passThru, Subtarget, DAG);
16128 case INTR_TYPE_SCALAR_MASK_RM: {
16129 SDValue Src1 = Op.getOperand(1);
16130 SDValue Src2 = Op.getOperand(2);
16131 SDValue Src0 = Op.getOperand(3);
16132 SDValue Mask = Op.getOperand(4);
16133 // There are 2 kinds of intrinsics in this group:
16134 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16135 // (2) With rounding mode and sae - 7 operands.
16136 if (Op.getNumOperands() == 6) {
16137 SDValue Sae = Op.getOperand(5);
16138 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16139 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16141 Mask, Src0, Subtarget, DAG);
16143 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16144 SDValue RoundingMode = Op.getOperand(5);
16145 SDValue Sae = Op.getOperand(6);
16146 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16147 RoundingMode, Sae),
16148 Mask, Src0, Subtarget, DAG);
16150 case INTR_TYPE_2OP_MASK:
16151 case INTR_TYPE_2OP_IMM8_MASK: {
16152 SDValue Src1 = Op.getOperand(1);
16153 SDValue Src2 = Op.getOperand(2);
16154 SDValue PassThru = Op.getOperand(3);
16155 SDValue Mask = Op.getOperand(4);
16157 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16158 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16160 // We specify 2 possible opcodes for intrinsics with rounding modes.
16161 // First, we check if the intrinsic may have non-default rounding mode,
16162 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16163 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16164 if (IntrWithRoundingModeOpcode != 0) {
16165 SDValue Rnd = Op.getOperand(5);
16166 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16167 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16168 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16169 dl, Op.getValueType(),
16171 Mask, PassThru, Subtarget, DAG);
16174 // TODO: Intrinsics should have fast-math-flags to propagate.
16175 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16176 Mask, PassThru, Subtarget, DAG);
16178 case INTR_TYPE_2OP_MASK_RM: {
16179 SDValue Src1 = Op.getOperand(1);
16180 SDValue Src2 = Op.getOperand(2);
16181 SDValue PassThru = Op.getOperand(3);
16182 SDValue Mask = Op.getOperand(4);
16183 // We specify 2 possible modes for intrinsics, with/without rounding
16185 // First, we check if the intrinsic have rounding mode (6 operands),
16186 // if not, we set rounding mode to "current".
16188 if (Op.getNumOperands() == 6)
16189 Rnd = Op.getOperand(5);
16191 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16192 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16194 Mask, PassThru, Subtarget, DAG);
16196 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16197 SDValue Src1 = Op.getOperand(1);
16198 SDValue Src2 = Op.getOperand(2);
16199 SDValue Src3 = Op.getOperand(3);
16200 SDValue PassThru = Op.getOperand(4);
16201 SDValue Mask = Op.getOperand(5);
16202 SDValue Sae = Op.getOperand(6);
16204 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16206 Mask, PassThru, Subtarget, DAG);
16208 case INTR_TYPE_3OP_MASK_RM: {
16209 SDValue Src1 = Op.getOperand(1);
16210 SDValue Src2 = Op.getOperand(2);
16211 SDValue Imm = Op.getOperand(3);
16212 SDValue PassThru = Op.getOperand(4);
16213 SDValue Mask = Op.getOperand(5);
16214 // We specify 2 possible modes for intrinsics, with/without rounding
16216 // First, we check if the intrinsic have rounding mode (7 operands),
16217 // if not, we set rounding mode to "current".
16219 if (Op.getNumOperands() == 7)
16220 Rnd = Op.getOperand(6);
16222 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16223 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16224 Src1, Src2, Imm, Rnd),
16225 Mask, PassThru, Subtarget, DAG);
16227 case INTR_TYPE_3OP_IMM8_MASK:
16228 case INTR_TYPE_3OP_MASK:
16229 case INSERT_SUBVEC: {
16230 SDValue Src1 = Op.getOperand(1);
16231 SDValue Src2 = Op.getOperand(2);
16232 SDValue Src3 = Op.getOperand(3);
16233 SDValue PassThru = Op.getOperand(4);
16234 SDValue Mask = Op.getOperand(5);
16236 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16237 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16238 else if (IntrData->Type == INSERT_SUBVEC) {
16239 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16240 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16241 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16242 Imm *= Src2.getValueType().getVectorNumElements();
16243 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16246 // We specify 2 possible opcodes for intrinsics with rounding modes.
16247 // First, we check if the intrinsic may have non-default rounding mode,
16248 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16249 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16250 if (IntrWithRoundingModeOpcode != 0) {
16251 SDValue Rnd = Op.getOperand(6);
16252 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16253 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16254 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16255 dl, Op.getValueType(),
16256 Src1, Src2, Src3, Rnd),
16257 Mask, PassThru, Subtarget, DAG);
16260 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16262 Mask, PassThru, Subtarget, DAG);
16264 case VPERM_3OP_MASKZ:
16265 case VPERM_3OP_MASK:
16268 case FMA_OP_MASK: {
16269 SDValue Src1 = Op.getOperand(1);
16270 SDValue Src2 = Op.getOperand(2);
16271 SDValue Src3 = Op.getOperand(3);
16272 SDValue Mask = Op.getOperand(4);
16273 EVT VT = Op.getValueType();
16274 SDValue PassThru = SDValue();
16276 // set PassThru element
16277 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16278 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16279 else if (IntrData->Type == FMA_OP_MASK3)
16284 // We specify 2 possible opcodes for intrinsics with rounding modes.
16285 // First, we check if the intrinsic may have non-default rounding mode,
16286 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16287 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16288 if (IntrWithRoundingModeOpcode != 0) {
16289 SDValue Rnd = Op.getOperand(5);
16290 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16291 X86::STATIC_ROUNDING::CUR_DIRECTION)
16292 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16293 dl, Op.getValueType(),
16294 Src1, Src2, Src3, Rnd),
16295 Mask, PassThru, Subtarget, DAG);
16297 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16298 dl, Op.getValueType(),
16300 Mask, PassThru, Subtarget, DAG);
16302 case TERLOG_OP_MASK:
16303 case TERLOG_OP_MASKZ: {
16304 SDValue Src1 = Op.getOperand(1);
16305 SDValue Src2 = Op.getOperand(2);
16306 SDValue Src3 = Op.getOperand(3);
16307 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16308 SDValue Mask = Op.getOperand(5);
16309 EVT VT = Op.getValueType();
16310 SDValue PassThru = Src1;
16311 // Set PassThru element.
16312 if (IntrData->Type == TERLOG_OP_MASKZ)
16313 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16315 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16316 Src1, Src2, Src3, Src4),
16317 Mask, PassThru, Subtarget, DAG);
16320 // FPclass intrinsics with mask
16321 SDValue Src1 = Op.getOperand(1);
16322 EVT VT = Src1.getValueType();
16323 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16324 VT.getVectorNumElements());
16325 SDValue Imm = Op.getOperand(2);
16326 SDValue Mask = Op.getOperand(3);
16327 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16328 Mask.getValueType().getSizeInBits());
16329 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16330 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16331 DAG.getTargetConstant(0, dl, MaskVT),
16333 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16334 DAG.getUNDEF(BitcastVT), FPclassMask,
16335 DAG.getIntPtrConstant(0, dl));
16336 return DAG.getBitcast(Op.getValueType(), Res);
16339 case CMP_MASK_CC: {
16340 // Comparison intrinsics with masks.
16341 // Example of transformation:
16342 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16343 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16345 // (v8i1 (insert_subvector undef,
16346 // (v2i1 (and (PCMPEQM %a, %b),
16347 // (extract_subvector
16348 // (v8i1 (bitcast %mask)), 0))), 0))))
16349 EVT VT = Op.getOperand(1).getValueType();
16350 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16351 VT.getVectorNumElements());
16352 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16353 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16354 Mask.getValueType().getSizeInBits());
16356 if (IntrData->Type == CMP_MASK_CC) {
16357 SDValue CC = Op.getOperand(3);
16358 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16359 // We specify 2 possible opcodes for intrinsics with rounding modes.
16360 // First, we check if the intrinsic may have non-default rounding mode,
16361 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16362 if (IntrData->Opc1 != 0) {
16363 SDValue Rnd = Op.getOperand(5);
16364 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16365 X86::STATIC_ROUNDING::CUR_DIRECTION)
16366 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16367 Op.getOperand(2), CC, Rnd);
16369 //default rounding mode
16371 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16372 Op.getOperand(2), CC);
16375 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16376 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16379 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16380 DAG.getTargetConstant(0, dl,
16383 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16384 DAG.getUNDEF(BitcastVT), CmpMask,
16385 DAG.getIntPtrConstant(0, dl));
16386 return DAG.getBitcast(Op.getValueType(), Res);
16388 case CMP_MASK_SCALAR_CC: {
16389 SDValue Src1 = Op.getOperand(1);
16390 SDValue Src2 = Op.getOperand(2);
16391 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16392 SDValue Mask = Op.getOperand(4);
16395 if (IntrData->Opc1 != 0) {
16396 SDValue Rnd = Op.getOperand(5);
16397 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16398 X86::STATIC_ROUNDING::CUR_DIRECTION)
16399 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16401 //default rounding mode
16403 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16405 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16406 DAG.getTargetConstant(0, dl,
16410 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16411 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16412 DAG.getValueType(MVT::i1));
16414 case COMI: { // Comparison intrinsics
16415 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16416 SDValue LHS = Op.getOperand(1);
16417 SDValue RHS = Op.getOperand(2);
16418 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16419 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16420 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16421 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16422 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16423 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16426 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16427 Op.getOperand(1), Op.getOperand(2), DAG);
16429 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16430 Op.getSimpleValueType(),
16432 Op.getOperand(2), DAG),
16433 Op.getOperand(4), Op.getOperand(3), Subtarget,
16435 case COMPRESS_EXPAND_IN_REG: {
16436 SDValue Mask = Op.getOperand(3);
16437 SDValue DataToCompress = Op.getOperand(1);
16438 SDValue PassThru = Op.getOperand(2);
16439 if (isAllOnes(Mask)) // return data as is
16440 return Op.getOperand(1);
16442 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16444 Mask, PassThru, Subtarget, DAG);
16447 SDValue Mask = Op.getOperand(3);
16448 EVT VT = Op.getValueType();
16449 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16450 VT.getVectorNumElements());
16451 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16452 Mask.getValueType().getSizeInBits());
16454 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16455 DAG.getBitcast(BitcastVT, Mask),
16456 DAG.getIntPtrConstant(0, dl));
16457 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16466 default: return SDValue(); // Don't custom lower most intrinsics.
16468 case Intrinsic::x86_avx2_permd:
16469 case Intrinsic::x86_avx2_permps:
16470 // Operands intentionally swapped. Mask is last operand to intrinsic,
16471 // but second operand for node/instruction.
16472 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16473 Op.getOperand(2), Op.getOperand(1));
16475 // ptest and testp intrinsics. The intrinsic these come from are designed to
16476 // return an integer value, not just an instruction so lower it to the ptest
16477 // or testp pattern and a setcc for the result.
16478 case Intrinsic::x86_sse41_ptestz:
16479 case Intrinsic::x86_sse41_ptestc:
16480 case Intrinsic::x86_sse41_ptestnzc:
16481 case Intrinsic::x86_avx_ptestz_256:
16482 case Intrinsic::x86_avx_ptestc_256:
16483 case Intrinsic::x86_avx_ptestnzc_256:
16484 case Intrinsic::x86_avx_vtestz_ps:
16485 case Intrinsic::x86_avx_vtestc_ps:
16486 case Intrinsic::x86_avx_vtestnzc_ps:
16487 case Intrinsic::x86_avx_vtestz_pd:
16488 case Intrinsic::x86_avx_vtestc_pd:
16489 case Intrinsic::x86_avx_vtestnzc_pd:
16490 case Intrinsic::x86_avx_vtestz_ps_256:
16491 case Intrinsic::x86_avx_vtestc_ps_256:
16492 case Intrinsic::x86_avx_vtestnzc_ps_256:
16493 case Intrinsic::x86_avx_vtestz_pd_256:
16494 case Intrinsic::x86_avx_vtestc_pd_256:
16495 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16496 bool IsTestPacked = false;
16499 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16500 case Intrinsic::x86_avx_vtestz_ps:
16501 case Intrinsic::x86_avx_vtestz_pd:
16502 case Intrinsic::x86_avx_vtestz_ps_256:
16503 case Intrinsic::x86_avx_vtestz_pd_256:
16504 IsTestPacked = true; // Fallthrough
16505 case Intrinsic::x86_sse41_ptestz:
16506 case Intrinsic::x86_avx_ptestz_256:
16508 X86CC = X86::COND_E;
16510 case Intrinsic::x86_avx_vtestc_ps:
16511 case Intrinsic::x86_avx_vtestc_pd:
16512 case Intrinsic::x86_avx_vtestc_ps_256:
16513 case Intrinsic::x86_avx_vtestc_pd_256:
16514 IsTestPacked = true; // Fallthrough
16515 case Intrinsic::x86_sse41_ptestc:
16516 case Intrinsic::x86_avx_ptestc_256:
16518 X86CC = X86::COND_B;
16520 case Intrinsic::x86_avx_vtestnzc_ps:
16521 case Intrinsic::x86_avx_vtestnzc_pd:
16522 case Intrinsic::x86_avx_vtestnzc_ps_256:
16523 case Intrinsic::x86_avx_vtestnzc_pd_256:
16524 IsTestPacked = true; // Fallthrough
16525 case Intrinsic::x86_sse41_ptestnzc:
16526 case Intrinsic::x86_avx_ptestnzc_256:
16528 X86CC = X86::COND_A;
16532 SDValue LHS = Op.getOperand(1);
16533 SDValue RHS = Op.getOperand(2);
16534 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16535 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16536 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16537 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16538 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16540 case Intrinsic::x86_avx512_kortestz_w:
16541 case Intrinsic::x86_avx512_kortestc_w: {
16542 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16543 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16544 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16545 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16546 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16547 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16548 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16551 case Intrinsic::x86_sse42_pcmpistria128:
16552 case Intrinsic::x86_sse42_pcmpestria128:
16553 case Intrinsic::x86_sse42_pcmpistric128:
16554 case Intrinsic::x86_sse42_pcmpestric128:
16555 case Intrinsic::x86_sse42_pcmpistrio128:
16556 case Intrinsic::x86_sse42_pcmpestrio128:
16557 case Intrinsic::x86_sse42_pcmpistris128:
16558 case Intrinsic::x86_sse42_pcmpestris128:
16559 case Intrinsic::x86_sse42_pcmpistriz128:
16560 case Intrinsic::x86_sse42_pcmpestriz128: {
16564 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16565 case Intrinsic::x86_sse42_pcmpistria128:
16566 Opcode = X86ISD::PCMPISTRI;
16567 X86CC = X86::COND_A;
16569 case Intrinsic::x86_sse42_pcmpestria128:
16570 Opcode = X86ISD::PCMPESTRI;
16571 X86CC = X86::COND_A;
16573 case Intrinsic::x86_sse42_pcmpistric128:
16574 Opcode = X86ISD::PCMPISTRI;
16575 X86CC = X86::COND_B;
16577 case Intrinsic::x86_sse42_pcmpestric128:
16578 Opcode = X86ISD::PCMPESTRI;
16579 X86CC = X86::COND_B;
16581 case Intrinsic::x86_sse42_pcmpistrio128:
16582 Opcode = X86ISD::PCMPISTRI;
16583 X86CC = X86::COND_O;
16585 case Intrinsic::x86_sse42_pcmpestrio128:
16586 Opcode = X86ISD::PCMPESTRI;
16587 X86CC = X86::COND_O;
16589 case Intrinsic::x86_sse42_pcmpistris128:
16590 Opcode = X86ISD::PCMPISTRI;
16591 X86CC = X86::COND_S;
16593 case Intrinsic::x86_sse42_pcmpestris128:
16594 Opcode = X86ISD::PCMPESTRI;
16595 X86CC = X86::COND_S;
16597 case Intrinsic::x86_sse42_pcmpistriz128:
16598 Opcode = X86ISD::PCMPISTRI;
16599 X86CC = X86::COND_E;
16601 case Intrinsic::x86_sse42_pcmpestriz128:
16602 Opcode = X86ISD::PCMPESTRI;
16603 X86CC = X86::COND_E;
16606 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16607 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16608 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16609 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16610 DAG.getConstant(X86CC, dl, MVT::i8),
16611 SDValue(PCMP.getNode(), 1));
16612 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16615 case Intrinsic::x86_sse42_pcmpistri128:
16616 case Intrinsic::x86_sse42_pcmpestri128: {
16618 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16619 Opcode = X86ISD::PCMPISTRI;
16621 Opcode = X86ISD::PCMPESTRI;
16623 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16624 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16625 return DAG.getNode(Opcode, dl, VTs, NewOps);
16628 case Intrinsic::x86_seh_lsda: {
16629 // Compute the symbol for the LSDA. We know it'll get emitted later.
16630 MachineFunction &MF = DAG.getMachineFunction();
16631 SDValue Op1 = Op.getOperand(1);
16632 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16633 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16634 GlobalValue::getRealLinkageName(Fn->getName()));
16636 // Generate a simple absolute symbol reference. This intrinsic is only
16637 // supported on 32-bit Windows, which isn't PIC.
16638 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16639 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16642 case Intrinsic::x86_seh_recoverfp: {
16643 SDValue FnOp = Op.getOperand(1);
16644 SDValue IncomingFPOp = Op.getOperand(2);
16645 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16646 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16648 report_fatal_error(
16649 "llvm.x86.seh.recoverfp must take a function as the first argument");
16650 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16653 case Intrinsic::localaddress: {
16654 // Returns one of the stack, base, or frame pointer registers, depending on
16655 // which is used to reference local variables.
16656 MachineFunction &MF = DAG.getMachineFunction();
16657 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16659 if (RegInfo->hasBasePointer(MF))
16660 Reg = RegInfo->getBaseRegister();
16661 else // This function handles the SP or FP case.
16662 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16663 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16668 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16669 SDValue Src, SDValue Mask, SDValue Base,
16670 SDValue Index, SDValue ScaleOp, SDValue Chain,
16671 const X86Subtarget * Subtarget) {
16673 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16675 llvm_unreachable("Invalid scale type");
16676 unsigned ScaleVal = C->getZExtValue();
16677 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16678 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16680 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16681 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16682 Index.getSimpleValueType().getVectorNumElements());
16684 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16686 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16688 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16689 Mask.getValueType().getSizeInBits());
16691 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16692 // are extracted by EXTRACT_SUBVECTOR.
16693 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16694 DAG.getBitcast(BitcastVT, Mask),
16695 DAG.getIntPtrConstant(0, dl));
16697 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16698 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16699 SDValue Segment = DAG.getRegister(0, MVT::i32);
16700 if (Src.getOpcode() == ISD::UNDEF)
16701 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16702 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16703 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16704 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16705 return DAG.getMergeValues(RetOps, dl);
16708 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16709 SDValue Src, SDValue Mask, SDValue Base,
16710 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16712 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16714 llvm_unreachable("Invalid scale type");
16715 unsigned ScaleVal = C->getZExtValue();
16716 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16717 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16719 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16720 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16721 SDValue Segment = DAG.getRegister(0, MVT::i32);
16722 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16723 Index.getSimpleValueType().getVectorNumElements());
16725 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16727 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16729 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16730 Mask.getValueType().getSizeInBits());
16732 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16733 // are extracted by EXTRACT_SUBVECTOR.
16734 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16735 DAG.getBitcast(BitcastVT, Mask),
16736 DAG.getIntPtrConstant(0, dl));
16738 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16739 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16740 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16741 return SDValue(Res, 1);
16744 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16745 SDValue Mask, SDValue Base, SDValue Index,
16746 SDValue ScaleOp, SDValue Chain) {
16748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16749 assert(C && "Invalid scale type");
16750 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16751 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16752 SDValue Segment = DAG.getRegister(0, MVT::i32);
16754 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16756 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16758 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16760 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16761 //SDVTList VTs = DAG.getVTList(MVT::Other);
16762 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16763 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16764 return SDValue(Res, 0);
16767 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16768 // read performance monitor counters (x86_rdpmc).
16769 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16770 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16771 SmallVectorImpl<SDValue> &Results) {
16772 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16773 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16776 // The ECX register is used to select the index of the performance counter
16778 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16780 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16782 // Reads the content of a 64-bit performance counter and returns it in the
16783 // registers EDX:EAX.
16784 if (Subtarget->is64Bit()) {
16785 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16786 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16789 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16790 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16793 Chain = HI.getValue(1);
16795 if (Subtarget->is64Bit()) {
16796 // The EAX register is loaded with the low-order 32 bits. The EDX register
16797 // is loaded with the supported high-order bits of the counter.
16798 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16799 DAG.getConstant(32, DL, MVT::i8));
16800 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16801 Results.push_back(Chain);
16805 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16806 SDValue Ops[] = { LO, HI };
16807 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16808 Results.push_back(Pair);
16809 Results.push_back(Chain);
16812 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16813 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16814 // also used to custom lower READCYCLECOUNTER nodes.
16815 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16816 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16817 SmallVectorImpl<SDValue> &Results) {
16818 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16819 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16822 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16823 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16824 // and the EAX register is loaded with the low-order 32 bits.
16825 if (Subtarget->is64Bit()) {
16826 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16827 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16830 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16831 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16834 SDValue Chain = HI.getValue(1);
16836 if (Opcode == X86ISD::RDTSCP_DAG) {
16837 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16839 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16840 // the ECX register. Add 'ecx' explicitly to the chain.
16841 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16843 // Explicitly store the content of ECX at the location passed in input
16844 // to the 'rdtscp' intrinsic.
16845 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16846 MachinePointerInfo(), false, false, 0);
16849 if (Subtarget->is64Bit()) {
16850 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16851 // the EAX register is loaded with the low-order 32 bits.
16852 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16853 DAG.getConstant(32, DL, MVT::i8));
16854 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16855 Results.push_back(Chain);
16859 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16860 SDValue Ops[] = { LO, HI };
16861 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16862 Results.push_back(Pair);
16863 Results.push_back(Chain);
16866 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16867 SelectionDAG &DAG) {
16868 SmallVector<SDValue, 2> Results;
16870 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16872 return DAG.getMergeValues(Results, DL);
16875 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16876 SelectionDAG &DAG) {
16877 MachineFunction &MF = DAG.getMachineFunction();
16878 const Function *Fn = MF.getFunction();
16880 SDValue Chain = Op.getOperand(0);
16882 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16883 "using llvm.x86.seh.restoreframe requires a frame pointer");
16885 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16886 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16888 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16889 unsigned FrameReg =
16890 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16891 unsigned SPReg = RegInfo->getStackRegister();
16892 unsigned SlotSize = RegInfo->getSlotSize();
16894 // Get incoming EBP.
16895 SDValue IncomingEBP =
16896 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16898 // SP is saved in the first field of every registration node, so load
16899 // [EBP-RegNodeSize] into SP.
16900 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16901 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16902 DAG.getConstant(-RegNodeSize, dl, VT));
16904 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16905 false, VT.getScalarSizeInBits() / 8);
16906 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16908 if (!RegInfo->needsStackRealignment(MF)) {
16909 // Adjust EBP to point back to the original frame position.
16910 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16911 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16913 assert(RegInfo->hasBasePointer(MF) &&
16914 "functions with Win32 EH must use frame or base pointer register");
16916 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16917 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16918 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16920 // Reload the spilled EBP value, now that the stack and base pointers are
16922 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16923 X86FI->setHasSEHFramePtrSave(true);
16924 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16925 X86FI->setSEHFramePtrSaveIndex(FI);
16926 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16927 MachinePointerInfo(), false, false, false,
16928 VT.getScalarSizeInBits() / 8);
16929 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16935 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16936 /// return truncate Store/MaskedStore Node
16937 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16941 SDValue Mask = Op.getOperand(4);
16942 SDValue DataToTruncate = Op.getOperand(3);
16943 SDValue Addr = Op.getOperand(2);
16944 SDValue Chain = Op.getOperand(0);
16946 EVT VT = DataToTruncate.getValueType();
16947 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16948 ElementType, VT.getVectorNumElements());
16950 if (isAllOnes(Mask)) // return just a truncate store
16951 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16952 MachinePointerInfo(), SVT, false, false,
16953 SVT.getScalarSizeInBits()/8);
16955 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16956 MVT::i1, VT.getVectorNumElements());
16957 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16958 Mask.getValueType().getSizeInBits());
16959 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16960 // are extracted by EXTRACT_SUBVECTOR.
16961 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16962 DAG.getBitcast(BitcastVT, Mask),
16963 DAG.getIntPtrConstant(0, dl));
16965 MachineMemOperand *MMO = DAG.getMachineFunction().
16966 getMachineMemOperand(MachinePointerInfo(),
16967 MachineMemOperand::MOStore, SVT.getStoreSize(),
16968 SVT.getScalarSizeInBits()/8);
16970 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16971 VMask, SVT, MMO, true);
16974 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16975 SelectionDAG &DAG) {
16976 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16978 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16980 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16981 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16986 switch(IntrData->Type) {
16988 llvm_unreachable("Unknown Intrinsic Type");
16992 // Emit the node with the right value type.
16993 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16994 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16996 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16997 // Otherwise return the value from Rand, which is always 0, casted to i32.
16998 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16999 DAG.getConstant(1, dl, Op->getValueType(1)),
17000 DAG.getConstant(X86::COND_B, dl, MVT::i32),
17001 SDValue(Result.getNode(), 1) };
17002 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17003 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17006 // Return { result, isValid, chain }.
17007 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17008 SDValue(Result.getNode(), 2));
17011 //gather(v1, mask, index, base, scale);
17012 SDValue Chain = Op.getOperand(0);
17013 SDValue Src = Op.getOperand(2);
17014 SDValue Base = Op.getOperand(3);
17015 SDValue Index = Op.getOperand(4);
17016 SDValue Mask = Op.getOperand(5);
17017 SDValue Scale = Op.getOperand(6);
17018 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17022 //scatter(base, mask, index, v1, scale);
17023 SDValue Chain = Op.getOperand(0);
17024 SDValue Base = Op.getOperand(2);
17025 SDValue Mask = Op.getOperand(3);
17026 SDValue Index = Op.getOperand(4);
17027 SDValue Src = Op.getOperand(5);
17028 SDValue Scale = Op.getOperand(6);
17029 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17033 SDValue Hint = Op.getOperand(6);
17034 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17035 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17036 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17037 SDValue Chain = Op.getOperand(0);
17038 SDValue Mask = Op.getOperand(2);
17039 SDValue Index = Op.getOperand(3);
17040 SDValue Base = Op.getOperand(4);
17041 SDValue Scale = Op.getOperand(5);
17042 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17044 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17046 SmallVector<SDValue, 2> Results;
17047 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17049 return DAG.getMergeValues(Results, dl);
17051 // Read Performance Monitoring Counters.
17053 SmallVector<SDValue, 2> Results;
17054 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17055 return DAG.getMergeValues(Results, dl);
17057 // XTEST intrinsics.
17059 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17060 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17061 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17062 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17064 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17065 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17066 Ret, SDValue(InTrans.getNode(), 1));
17070 SmallVector<SDValue, 2> Results;
17071 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17072 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17073 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17074 DAG.getConstant(-1, dl, MVT::i8));
17075 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17076 Op.getOperand(4), GenCF.getValue(1));
17077 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17078 Op.getOperand(5), MachinePointerInfo(),
17080 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17081 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17083 Results.push_back(SetCC);
17084 Results.push_back(Store);
17085 return DAG.getMergeValues(Results, dl);
17087 case COMPRESS_TO_MEM: {
17089 SDValue Mask = Op.getOperand(4);
17090 SDValue DataToCompress = Op.getOperand(3);
17091 SDValue Addr = Op.getOperand(2);
17092 SDValue Chain = Op.getOperand(0);
17094 EVT VT = DataToCompress.getValueType();
17095 if (isAllOnes(Mask)) // return just a store
17096 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17097 MachinePointerInfo(), false, false,
17098 VT.getScalarSizeInBits()/8);
17100 SDValue Compressed =
17101 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17102 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17103 return DAG.getStore(Chain, dl, Compressed, Addr,
17104 MachinePointerInfo(), false, false,
17105 VT.getScalarSizeInBits()/8);
17107 case TRUNCATE_TO_MEM_VI8:
17108 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17109 case TRUNCATE_TO_MEM_VI16:
17110 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17111 case TRUNCATE_TO_MEM_VI32:
17112 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17113 case EXPAND_FROM_MEM: {
17115 SDValue Mask = Op.getOperand(4);
17116 SDValue PassThru = Op.getOperand(3);
17117 SDValue Addr = Op.getOperand(2);
17118 SDValue Chain = Op.getOperand(0);
17119 EVT VT = Op.getValueType();
17121 if (isAllOnes(Mask)) // return just a load
17122 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17123 false, VT.getScalarSizeInBits()/8);
17125 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17126 false, false, false,
17127 VT.getScalarSizeInBits()/8);
17129 SDValue Results[] = {
17130 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17131 Mask, PassThru, Subtarget, DAG), Chain};
17132 return DAG.getMergeValues(Results, dl);
17137 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17138 SelectionDAG &DAG) const {
17139 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17140 MFI->setReturnAddressIsTaken(true);
17142 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17145 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17147 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17150 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17151 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17152 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17153 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17154 DAG.getNode(ISD::ADD, dl, PtrVT,
17155 FrameAddr, Offset),
17156 MachinePointerInfo(), false, false, false, 0);
17159 // Just load the return address.
17160 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17161 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17162 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17165 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17166 MachineFunction &MF = DAG.getMachineFunction();
17167 MachineFrameInfo *MFI = MF.getFrameInfo();
17168 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17169 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17170 EVT VT = Op.getValueType();
17172 MFI->setFrameAddressIsTaken(true);
17174 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17175 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17176 // is not possible to crawl up the stack without looking at the unwind codes
17178 int FrameAddrIndex = FuncInfo->getFAIndex();
17179 if (!FrameAddrIndex) {
17180 // Set up a frame object for the return address.
17181 unsigned SlotSize = RegInfo->getSlotSize();
17182 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17183 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17184 FuncInfo->setFAIndex(FrameAddrIndex);
17186 return DAG.getFrameIndex(FrameAddrIndex, VT);
17189 unsigned FrameReg =
17190 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17191 SDLoc dl(Op); // FIXME probably not meaningful
17192 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17193 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17194 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17195 "Invalid Frame Register!");
17196 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17198 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17199 MachinePointerInfo(),
17200 false, false, false, 0);
17204 // FIXME? Maybe this could be a TableGen attribute on some registers and
17205 // this table could be generated automatically from RegInfo.
17206 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17207 SelectionDAG &DAG) const {
17208 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17209 const MachineFunction &MF = DAG.getMachineFunction();
17211 unsigned Reg = StringSwitch<unsigned>(RegName)
17212 .Case("esp", X86::ESP)
17213 .Case("rsp", X86::RSP)
17214 .Case("ebp", X86::EBP)
17215 .Case("rbp", X86::RBP)
17218 if (Reg == X86::EBP || Reg == X86::RBP) {
17219 if (!TFI.hasFP(MF))
17220 report_fatal_error("register " + StringRef(RegName) +
17221 " is allocatable: function has no frame pointer");
17224 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17225 unsigned FrameReg =
17226 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17227 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17228 "Invalid Frame Register!");
17236 report_fatal_error("Invalid register name global variable");
17239 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17240 SelectionDAG &DAG) const {
17241 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17242 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17245 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17246 SDValue Chain = Op.getOperand(0);
17247 SDValue Offset = Op.getOperand(1);
17248 SDValue Handler = Op.getOperand(2);
17251 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17252 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17253 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17254 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17255 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17256 "Invalid Frame Register!");
17257 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17258 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17260 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17261 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17263 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17264 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17266 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17268 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17269 DAG.getRegister(StoreAddrReg, PtrVT));
17272 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17273 SelectionDAG &DAG) const {
17275 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17276 DAG.getVTList(MVT::i32, MVT::Other),
17277 Op.getOperand(0), Op.getOperand(1));
17280 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17281 SelectionDAG &DAG) const {
17283 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17284 Op.getOperand(0), Op.getOperand(1));
17287 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17288 return Op.getOperand(0);
17291 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17292 SelectionDAG &DAG) const {
17293 SDValue Root = Op.getOperand(0);
17294 SDValue Trmp = Op.getOperand(1); // trampoline
17295 SDValue FPtr = Op.getOperand(2); // nested function
17296 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17299 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17300 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17302 if (Subtarget->is64Bit()) {
17303 SDValue OutChains[6];
17305 // Large code-model.
17306 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17307 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17309 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17310 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17312 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17314 // Load the pointer to the nested function into R11.
17315 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17316 SDValue Addr = Trmp;
17317 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17318 Addr, MachinePointerInfo(TrmpAddr),
17321 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17322 DAG.getConstant(2, dl, MVT::i64));
17323 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17324 MachinePointerInfo(TrmpAddr, 2),
17327 // Load the 'nest' parameter value into R10.
17328 // R10 is specified in X86CallingConv.td
17329 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17330 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17331 DAG.getConstant(10, dl, MVT::i64));
17332 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17333 Addr, MachinePointerInfo(TrmpAddr, 10),
17336 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17337 DAG.getConstant(12, dl, MVT::i64));
17338 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17339 MachinePointerInfo(TrmpAddr, 12),
17342 // Jump to the nested function.
17343 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17344 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17345 DAG.getConstant(20, dl, MVT::i64));
17346 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17347 Addr, MachinePointerInfo(TrmpAddr, 20),
17350 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17351 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17352 DAG.getConstant(22, dl, MVT::i64));
17353 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17354 Addr, MachinePointerInfo(TrmpAddr, 22),
17357 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17359 const Function *Func =
17360 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17361 CallingConv::ID CC = Func->getCallingConv();
17366 llvm_unreachable("Unsupported calling convention");
17367 case CallingConv::C:
17368 case CallingConv::X86_StdCall: {
17369 // Pass 'nest' parameter in ECX.
17370 // Must be kept in sync with X86CallingConv.td
17371 NestReg = X86::ECX;
17373 // Check that ECX wasn't needed by an 'inreg' parameter.
17374 FunctionType *FTy = Func->getFunctionType();
17375 const AttributeSet &Attrs = Func->getAttributes();
17377 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17378 unsigned InRegCount = 0;
17381 for (FunctionType::param_iterator I = FTy->param_begin(),
17382 E = FTy->param_end(); I != E; ++I, ++Idx)
17383 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17384 auto &DL = DAG.getDataLayout();
17385 // FIXME: should only count parameters that are lowered to integers.
17386 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17389 if (InRegCount > 2) {
17390 report_fatal_error("Nest register in use - reduce number of inreg"
17396 case CallingConv::X86_FastCall:
17397 case CallingConv::X86_ThisCall:
17398 case CallingConv::Fast:
17399 // Pass 'nest' parameter in EAX.
17400 // Must be kept in sync with X86CallingConv.td
17401 NestReg = X86::EAX;
17405 SDValue OutChains[4];
17406 SDValue Addr, Disp;
17408 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17409 DAG.getConstant(10, dl, MVT::i32));
17410 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17412 // This is storing the opcode for MOV32ri.
17413 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17414 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17415 OutChains[0] = DAG.getStore(Root, dl,
17416 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17417 Trmp, MachinePointerInfo(TrmpAddr),
17420 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17421 DAG.getConstant(1, dl, MVT::i32));
17422 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17423 MachinePointerInfo(TrmpAddr, 1),
17426 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17427 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17428 DAG.getConstant(5, dl, MVT::i32));
17429 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17430 Addr, MachinePointerInfo(TrmpAddr, 5),
17433 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17434 DAG.getConstant(6, dl, MVT::i32));
17435 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17436 MachinePointerInfo(TrmpAddr, 6),
17439 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17443 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17444 SelectionDAG &DAG) const {
17446 The rounding mode is in bits 11:10 of FPSR, and has the following
17448 00 Round to nearest
17453 FLT_ROUNDS, on the other hand, expects the following:
17460 To perform the conversion, we do:
17461 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17464 MachineFunction &MF = DAG.getMachineFunction();
17465 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17466 unsigned StackAlignment = TFI.getStackAlignment();
17467 MVT VT = Op.getSimpleValueType();
17470 // Save FP Control Word to stack slot
17471 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17472 SDValue StackSlot =
17473 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17475 MachineMemOperand *MMO =
17476 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17477 MachineMemOperand::MOStore, 2, 2);
17479 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17480 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17481 DAG.getVTList(MVT::Other),
17482 Ops, MVT::i16, MMO);
17484 // Load FP Control Word from stack slot
17485 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17486 MachinePointerInfo(), false, false, false, 0);
17488 // Transform as necessary
17490 DAG.getNode(ISD::SRL, DL, MVT::i16,
17491 DAG.getNode(ISD::AND, DL, MVT::i16,
17492 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17493 DAG.getConstant(11, DL, MVT::i8));
17495 DAG.getNode(ISD::SRL, DL, MVT::i16,
17496 DAG.getNode(ISD::AND, DL, MVT::i16,
17497 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17498 DAG.getConstant(9, DL, MVT::i8));
17501 DAG.getNode(ISD::AND, DL, MVT::i16,
17502 DAG.getNode(ISD::ADD, DL, MVT::i16,
17503 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17504 DAG.getConstant(1, DL, MVT::i16)),
17505 DAG.getConstant(3, DL, MVT::i16));
17507 return DAG.getNode((VT.getSizeInBits() < 16 ?
17508 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17511 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17512 MVT VT = Op.getSimpleValueType();
17514 unsigned NumBits = VT.getSizeInBits();
17517 Op = Op.getOperand(0);
17518 if (VT == MVT::i8) {
17519 // Zero extend to i32 since there is not an i8 bsr.
17521 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17524 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17525 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17526 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17528 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17531 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17532 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17535 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17537 // Finally xor with NumBits-1.
17538 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17539 DAG.getConstant(NumBits - 1, dl, OpVT));
17542 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17546 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17547 MVT VT = Op.getSimpleValueType();
17549 unsigned NumBits = VT.getSizeInBits();
17552 Op = Op.getOperand(0);
17553 if (VT == MVT::i8) {
17554 // Zero extend to i32 since there is not an i8 bsr.
17556 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17559 // Issue a bsr (scan bits in reverse).
17560 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17561 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17563 // And xor with NumBits-1.
17564 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17565 DAG.getConstant(NumBits - 1, dl, OpVT));
17568 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17572 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17573 MVT VT = Op.getSimpleValueType();
17574 unsigned NumBits = VT.getScalarSizeInBits();
17577 if (VT.isVector()) {
17578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17580 SDValue N0 = Op.getOperand(0);
17581 SDValue Zero = DAG.getConstant(0, dl, VT);
17583 // lsb(x) = (x & -x)
17584 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17585 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17587 // cttz_undef(x) = (width - 1) - ctlz(lsb)
17588 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17589 TLI.isOperationLegal(ISD::CTLZ, VT)) {
17590 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17591 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17592 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17595 // cttz(x) = ctpop(lsb - 1)
17596 SDValue One = DAG.getConstant(1, dl, VT);
17597 return DAG.getNode(ISD::CTPOP, dl, VT,
17598 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17601 assert(Op.getOpcode() == ISD::CTTZ &&
17602 "Only scalar CTTZ requires custom lowering");
17604 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17605 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17606 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17608 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17611 DAG.getConstant(NumBits, dl, VT),
17612 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17615 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17618 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17619 // ones, and then concatenate the result back.
17620 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17621 MVT VT = Op.getSimpleValueType();
17623 assert(VT.is256BitVector() && VT.isInteger() &&
17624 "Unsupported value type for operation");
17626 unsigned NumElems = VT.getVectorNumElements();
17629 // Extract the LHS vectors
17630 SDValue LHS = Op.getOperand(0);
17631 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17632 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17634 // Extract the RHS vectors
17635 SDValue RHS = Op.getOperand(1);
17636 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17637 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17639 MVT EltVT = VT.getVectorElementType();
17640 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17642 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17643 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17644 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17647 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17648 if (Op.getValueType() == MVT::i1)
17649 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17650 Op.getOperand(0), Op.getOperand(1));
17651 assert(Op.getSimpleValueType().is256BitVector() &&
17652 Op.getSimpleValueType().isInteger() &&
17653 "Only handle AVX 256-bit vector integer operation");
17654 return Lower256IntArith(Op, DAG);
17657 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17658 if (Op.getValueType() == MVT::i1)
17659 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17660 Op.getOperand(0), Op.getOperand(1));
17661 assert(Op.getSimpleValueType().is256BitVector() &&
17662 Op.getSimpleValueType().isInteger() &&
17663 "Only handle AVX 256-bit vector integer operation");
17664 return Lower256IntArith(Op, DAG);
17667 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17668 assert(Op.getSimpleValueType().is256BitVector() &&
17669 Op.getSimpleValueType().isInteger() &&
17670 "Only handle AVX 256-bit vector integer operation");
17671 return Lower256IntArith(Op, DAG);
17674 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17675 SelectionDAG &DAG) {
17677 MVT VT = Op.getSimpleValueType();
17680 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17682 // Decompose 256-bit ops into smaller 128-bit ops.
17683 if (VT.is256BitVector() && !Subtarget->hasInt256())
17684 return Lower256IntArith(Op, DAG);
17686 SDValue A = Op.getOperand(0);
17687 SDValue B = Op.getOperand(1);
17689 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17690 // pairs, multiply and truncate.
17691 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17692 if (Subtarget->hasInt256()) {
17693 if (VT == MVT::v32i8) {
17694 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17695 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17696 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17697 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17698 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17699 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17700 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17701 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17702 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17703 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17706 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17707 return DAG.getNode(
17708 ISD::TRUNCATE, dl, VT,
17709 DAG.getNode(ISD::MUL, dl, ExVT,
17710 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17711 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17714 assert(VT == MVT::v16i8 &&
17715 "Pre-AVX2 support only supports v16i8 multiplication");
17716 MVT ExVT = MVT::v8i16;
17718 // Extract the lo parts and sign extend to i16
17720 if (Subtarget->hasSSE41()) {
17721 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17722 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17724 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17725 -1, 4, -1, 5, -1, 6, -1, 7};
17726 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17727 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17728 ALo = DAG.getBitcast(ExVT, ALo);
17729 BLo = DAG.getBitcast(ExVT, BLo);
17730 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17731 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17734 // Extract the hi parts and sign extend to i16
17736 if (Subtarget->hasSSE41()) {
17737 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17738 -1, -1, -1, -1, -1, -1, -1, -1};
17739 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17740 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17741 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17742 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17744 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17745 -1, 12, -1, 13, -1, 14, -1, 15};
17746 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17747 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17748 AHi = DAG.getBitcast(ExVT, AHi);
17749 BHi = DAG.getBitcast(ExVT, BHi);
17750 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17751 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17754 // Multiply, mask the lower 8bits of the lo/hi results and pack
17755 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17756 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17757 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17758 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17759 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17762 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17763 if (VT == MVT::v4i32) {
17764 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17765 "Should not custom lower when pmuldq is available!");
17767 // Extract the odd parts.
17768 static const int UnpackMask[] = { 1, -1, 3, -1 };
17769 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17770 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17772 // Multiply the even parts.
17773 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17774 // Now multiply odd parts.
17775 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17777 Evens = DAG.getBitcast(VT, Evens);
17778 Odds = DAG.getBitcast(VT, Odds);
17780 // Merge the two vectors back together with a shuffle. This expands into 2
17782 static const int ShufMask[] = { 0, 4, 2, 6 };
17783 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17786 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17787 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17789 // Ahi = psrlqi(a, 32);
17790 // Bhi = psrlqi(b, 32);
17792 // AloBlo = pmuludq(a, b);
17793 // AloBhi = pmuludq(a, Bhi);
17794 // AhiBlo = pmuludq(Ahi, b);
17796 // AloBhi = psllqi(AloBhi, 32);
17797 // AhiBlo = psllqi(AhiBlo, 32);
17798 // return AloBlo + AloBhi + AhiBlo;
17800 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17801 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17803 SDValue AhiBlo = Ahi;
17804 SDValue AloBhi = Bhi;
17805 // Bit cast to 32-bit vectors for MULUDQ
17806 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17807 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17808 A = DAG.getBitcast(MulVT, A);
17809 B = DAG.getBitcast(MulVT, B);
17810 Ahi = DAG.getBitcast(MulVT, Ahi);
17811 Bhi = DAG.getBitcast(MulVT, Bhi);
17813 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17814 // After shifting right const values the result may be all-zero.
17815 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17816 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17817 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17819 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17820 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17821 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17824 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17825 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17828 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17829 assert(Subtarget->isTargetWin64() && "Unexpected target");
17830 EVT VT = Op.getValueType();
17831 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17832 "Unexpected return type for lowering");
17836 switch (Op->getOpcode()) {
17837 default: llvm_unreachable("Unexpected request for libcall!");
17838 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17839 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17840 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17841 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17842 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17843 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17847 SDValue InChain = DAG.getEntryNode();
17849 TargetLowering::ArgListTy Args;
17850 TargetLowering::ArgListEntry Entry;
17851 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17852 EVT ArgVT = Op->getOperand(i).getValueType();
17853 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17854 "Unexpected argument type for lowering");
17855 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17856 Entry.Node = StackPtr;
17857 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17859 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17860 Entry.Ty = PointerType::get(ArgTy,0);
17861 Entry.isSExt = false;
17862 Entry.isZExt = false;
17863 Args.push_back(Entry);
17866 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17867 getPointerTy(DAG.getDataLayout()));
17869 TargetLowering::CallLoweringInfo CLI(DAG);
17870 CLI.setDebugLoc(dl).setChain(InChain)
17871 .setCallee(getLibcallCallingConv(LC),
17872 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17873 Callee, std::move(Args), 0)
17874 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17876 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17877 return DAG.getBitcast(VT, CallInfo.first);
17880 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17881 SelectionDAG &DAG) {
17882 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17883 EVT VT = Op0.getValueType();
17886 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17887 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17889 // PMULxD operations multiply each even value (starting at 0) of LHS with
17890 // the related value of RHS and produce a widen result.
17891 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17892 // => <2 x i64> <ae|cg>
17894 // In other word, to have all the results, we need to perform two PMULxD:
17895 // 1. one with the even values.
17896 // 2. one with the odd values.
17897 // To achieve #2, with need to place the odd values at an even position.
17899 // Place the odd value at an even position (basically, shift all values 1
17900 // step to the left):
17901 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17902 // <a|b|c|d> => <b|undef|d|undef>
17903 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17904 // <e|f|g|h> => <f|undef|h|undef>
17905 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17907 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17909 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17910 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17912 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17913 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17914 // => <2 x i64> <ae|cg>
17915 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17916 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17917 // => <2 x i64> <bf|dh>
17918 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17920 // Shuffle it back into the right order.
17921 SDValue Highs, Lows;
17922 if (VT == MVT::v8i32) {
17923 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17924 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17925 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17926 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17928 const int HighMask[] = {1, 5, 3, 7};
17929 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17930 const int LowMask[] = {0, 4, 2, 6};
17931 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17934 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17935 // unsigned multiply.
17936 if (IsSigned && !Subtarget->hasSSE41()) {
17937 SDValue ShAmt = DAG.getConstant(
17939 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17940 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17941 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17942 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17943 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17945 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17946 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17949 // The first result of MUL_LOHI is actually the low value, followed by the
17951 SDValue Ops[] = {Lows, Highs};
17952 return DAG.getMergeValues(Ops, dl);
17955 // Return true if the required (according to Opcode) shift-imm form is natively
17956 // supported by the Subtarget
17957 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17959 if (VT.getScalarSizeInBits() < 16)
17962 if (VT.is512BitVector() &&
17963 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17966 bool LShift = VT.is128BitVector() ||
17967 (VT.is256BitVector() && Subtarget->hasInt256());
17969 bool AShift = LShift && (Subtarget->hasVLX() ||
17970 (VT != MVT::v2i64 && VT != MVT::v4i64));
17971 return (Opcode == ISD::SRA) ? AShift : LShift;
17974 // The shift amount is a variable, but it is the same for all vector lanes.
17975 // These instructions are defined together with shift-immediate.
17977 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17979 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17982 // Return true if the required (according to Opcode) variable-shift form is
17983 // natively supported by the Subtarget
17984 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17987 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17990 // vXi16 supported only on AVX-512, BWI
17991 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17994 if (VT.is512BitVector() || Subtarget->hasVLX())
17997 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17998 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17999 return (Opcode == ISD::SRA) ? AShift : LShift;
18002 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18003 const X86Subtarget *Subtarget) {
18004 MVT VT = Op.getSimpleValueType();
18006 SDValue R = Op.getOperand(0);
18007 SDValue Amt = Op.getOperand(1);
18009 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18010 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18012 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18013 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18014 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18015 SDValue Ex = DAG.getBitcast(ExVT, R);
18017 if (ShiftAmt >= 32) {
18018 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18020 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18021 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18022 ShiftAmt - 32, DAG);
18023 if (VT == MVT::v2i64)
18024 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18025 if (VT == MVT::v4i64)
18026 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18027 {9, 1, 11, 3, 13, 5, 15, 7});
18029 // SRA upper i32, SHL whole i64 and select lower i32.
18030 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18033 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18034 Lower = DAG.getBitcast(ExVT, Lower);
18035 if (VT == MVT::v2i64)
18036 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18037 if (VT == MVT::v4i64)
18038 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18039 {8, 1, 10, 3, 12, 5, 14, 7});
18041 return DAG.getBitcast(VT, Ex);
18044 // Optimize shl/srl/sra with constant shift amount.
18045 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18046 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18047 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18049 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18050 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18052 // i64 SRA needs to be performed as partial shifts.
18053 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18054 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18055 return ArithmeticShiftRight64(ShiftAmt);
18057 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18058 unsigned NumElts = VT.getVectorNumElements();
18059 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18061 // Simple i8 add case
18062 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18063 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18065 // ashr(R, 7) === cmp_slt(R, 0)
18066 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18067 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18068 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18071 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18072 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18075 if (Op.getOpcode() == ISD::SHL) {
18076 // Make a large shift.
18077 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18079 SHL = DAG.getBitcast(VT, SHL);
18080 // Zero out the rightmost bits.
18081 SmallVector<SDValue, 32> V(
18082 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18083 return DAG.getNode(ISD::AND, dl, VT, SHL,
18084 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18086 if (Op.getOpcode() == ISD::SRL) {
18087 // Make a large shift.
18088 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18090 SRL = DAG.getBitcast(VT, SRL);
18091 // Zero out the leftmost bits.
18092 SmallVector<SDValue, 32> V(
18093 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18094 return DAG.getNode(ISD::AND, dl, VT, SRL,
18095 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18097 if (Op.getOpcode() == ISD::SRA) {
18098 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18099 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18100 SmallVector<SDValue, 32> V(NumElts,
18101 DAG.getConstant(128 >> ShiftAmt, dl,
18103 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18104 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18105 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18108 llvm_unreachable("Unknown shift opcode.");
18113 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18114 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18115 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18117 // Peek through any splat that was introduced for i64 shift vectorization.
18118 int SplatIndex = -1;
18119 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18120 if (SVN->isSplat()) {
18121 SplatIndex = SVN->getSplatIndex();
18122 Amt = Amt.getOperand(0);
18123 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18124 "Splat shuffle referencing second operand");
18127 if (Amt.getOpcode() != ISD::BITCAST ||
18128 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18131 Amt = Amt.getOperand(0);
18132 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18133 VT.getVectorNumElements();
18134 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18135 uint64_t ShiftAmt = 0;
18136 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18137 for (unsigned i = 0; i != Ratio; ++i) {
18138 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18142 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18145 // Check remaining shift amounts (if not a splat).
18146 if (SplatIndex < 0) {
18147 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18148 uint64_t ShAmt = 0;
18149 for (unsigned j = 0; j != Ratio; ++j) {
18150 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18154 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18156 if (ShAmt != ShiftAmt)
18161 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18162 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18164 if (Op.getOpcode() == ISD::SRA)
18165 return ArithmeticShiftRight64(ShiftAmt);
18171 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18172 const X86Subtarget* Subtarget) {
18173 MVT VT = Op.getSimpleValueType();
18175 SDValue R = Op.getOperand(0);
18176 SDValue Amt = Op.getOperand(1);
18178 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18179 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18181 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18182 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18184 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18186 EVT EltVT = VT.getVectorElementType();
18188 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18189 // Check if this build_vector node is doing a splat.
18190 // If so, then set BaseShAmt equal to the splat value.
18191 BaseShAmt = BV->getSplatValue();
18192 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18193 BaseShAmt = SDValue();
18195 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18196 Amt = Amt.getOperand(0);
18198 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18199 if (SVN && SVN->isSplat()) {
18200 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18201 SDValue InVec = Amt.getOperand(0);
18202 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18203 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18204 "Unexpected shuffle index found!");
18205 BaseShAmt = InVec.getOperand(SplatIdx);
18206 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18207 if (ConstantSDNode *C =
18208 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18209 if (C->getZExtValue() == SplatIdx)
18210 BaseShAmt = InVec.getOperand(1);
18215 // Avoid introducing an extract element from a shuffle.
18216 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18217 DAG.getIntPtrConstant(SplatIdx, dl));
18221 if (BaseShAmt.getNode()) {
18222 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18223 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18224 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18225 else if (EltVT.bitsLT(MVT::i32))
18226 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18228 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18232 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18233 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18234 Amt.getOpcode() == ISD::BITCAST &&
18235 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18236 Amt = Amt.getOperand(0);
18237 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18238 VT.getVectorNumElements();
18239 std::vector<SDValue> Vals(Ratio);
18240 for (unsigned i = 0; i != Ratio; ++i)
18241 Vals[i] = Amt.getOperand(i);
18242 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18243 for (unsigned j = 0; j != Ratio; ++j)
18244 if (Vals[j] != Amt.getOperand(i + j))
18248 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18249 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18254 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18255 SelectionDAG &DAG) {
18256 MVT VT = Op.getSimpleValueType();
18258 SDValue R = Op.getOperand(0);
18259 SDValue Amt = Op.getOperand(1);
18261 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18262 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18264 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18267 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18270 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18273 // XOP has 128-bit variable logical/arithmetic shifts.
18274 // +ve/-ve Amt = shift left/right.
18275 if (Subtarget->hasXOP() &&
18276 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18277 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18278 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18279 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18280 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18282 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18283 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18284 if (Op.getOpcode() == ISD::SRA)
18285 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18288 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18289 // shifts per-lane and then shuffle the partial results back together.
18290 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18291 // Splat the shift amounts so the scalar shifts above will catch it.
18292 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18293 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18294 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18295 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18296 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18299 // i64 vector arithmetic shift can be emulated with the transform:
18300 // M = lshr(SIGN_BIT, Amt)
18301 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18302 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18303 Op.getOpcode() == ISD::SRA) {
18304 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18305 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18306 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18307 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18308 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18312 // If possible, lower this packed shift into a vector multiply instead of
18313 // expanding it into a sequence of scalar shifts.
18314 // Do this only if the vector shift count is a constant build_vector.
18315 if (Op.getOpcode() == ISD::SHL &&
18316 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18317 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18318 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18319 SmallVector<SDValue, 8> Elts;
18320 EVT SVT = VT.getScalarType();
18321 unsigned SVTBits = SVT.getSizeInBits();
18322 const APInt &One = APInt(SVTBits, 1);
18323 unsigned NumElems = VT.getVectorNumElements();
18325 for (unsigned i=0; i !=NumElems; ++i) {
18326 SDValue Op = Amt->getOperand(i);
18327 if (Op->getOpcode() == ISD::UNDEF) {
18328 Elts.push_back(Op);
18332 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18333 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18334 uint64_t ShAmt = C.getZExtValue();
18335 if (ShAmt >= SVTBits) {
18336 Elts.push_back(DAG.getUNDEF(SVT));
18339 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18341 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18342 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18345 // Lower SHL with variable shift amount.
18346 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18347 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18349 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18350 DAG.getConstant(0x3f800000U, dl, VT));
18351 Op = DAG.getBitcast(MVT::v4f32, Op);
18352 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18353 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18356 // If possible, lower this shift as a sequence of two shifts by
18357 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18359 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18361 // Could be rewritten as:
18362 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18364 // The advantage is that the two shifts from the example would be
18365 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18366 // the vector shift into four scalar shifts plus four pairs of vector
18368 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18369 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18370 unsigned TargetOpcode = X86ISD::MOVSS;
18371 bool CanBeSimplified;
18372 // The splat value for the first packed shift (the 'X' from the example).
18373 SDValue Amt1 = Amt->getOperand(0);
18374 // The splat value for the second packed shift (the 'Y' from the example).
18375 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18376 Amt->getOperand(2);
18378 // See if it is possible to replace this node with a sequence of
18379 // two shifts followed by a MOVSS/MOVSD
18380 if (VT == MVT::v4i32) {
18381 // Check if it is legal to use a MOVSS.
18382 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18383 Amt2 == Amt->getOperand(3);
18384 if (!CanBeSimplified) {
18385 // Otherwise, check if we can still simplify this node using a MOVSD.
18386 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18387 Amt->getOperand(2) == Amt->getOperand(3);
18388 TargetOpcode = X86ISD::MOVSD;
18389 Amt2 = Amt->getOperand(2);
18392 // Do similar checks for the case where the machine value type
18394 CanBeSimplified = Amt1 == Amt->getOperand(1);
18395 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18396 CanBeSimplified = Amt2 == Amt->getOperand(i);
18398 if (!CanBeSimplified) {
18399 TargetOpcode = X86ISD::MOVSD;
18400 CanBeSimplified = true;
18401 Amt2 = Amt->getOperand(4);
18402 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18403 CanBeSimplified = Amt1 == Amt->getOperand(i);
18404 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18405 CanBeSimplified = Amt2 == Amt->getOperand(j);
18409 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18410 isa<ConstantSDNode>(Amt2)) {
18411 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18412 EVT CastVT = MVT::v4i32;
18414 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18415 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18417 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18418 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18419 if (TargetOpcode == X86ISD::MOVSD)
18420 CastVT = MVT::v2i64;
18421 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18422 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18423 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18425 return DAG.getBitcast(VT, Result);
18429 // v4i32 Non Uniform Shifts.
18430 // If the shift amount is constant we can shift each lane using the SSE2
18431 // immediate shifts, else we need to zero-extend each lane to the lower i64
18432 // and shift using the SSE2 variable shifts.
18433 // The separate results can then be blended together.
18434 if (VT == MVT::v4i32) {
18435 unsigned Opc = Op.getOpcode();
18436 SDValue Amt0, Amt1, Amt2, Amt3;
18437 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18438 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18439 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18440 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18441 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18443 // ISD::SHL is handled above but we include it here for completeness.
18446 llvm_unreachable("Unknown target vector shift node");
18448 Opc = X86ISD::VSHL;
18451 Opc = X86ISD::VSRL;
18454 Opc = X86ISD::VSRA;
18457 // The SSE2 shifts use the lower i64 as the same shift amount for
18458 // all lanes and the upper i64 is ignored. These shuffle masks
18459 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18460 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18461 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18462 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18463 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18464 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18467 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18468 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18469 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18470 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18471 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18472 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18473 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18476 if (VT == MVT::v16i8 ||
18477 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18478 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18479 unsigned ShiftOpcode = Op->getOpcode();
18481 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18482 // On SSE41 targets we make use of the fact that VSELECT lowers
18483 // to PBLENDVB which selects bytes based just on the sign bit.
18484 if (Subtarget->hasSSE41()) {
18485 V0 = DAG.getBitcast(VT, V0);
18486 V1 = DAG.getBitcast(VT, V1);
18487 Sel = DAG.getBitcast(VT, Sel);
18488 return DAG.getBitcast(SelVT,
18489 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18491 // On pre-SSE41 targets we test for the sign bit by comparing to
18492 // zero - a negative value will set all bits of the lanes to true
18493 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18494 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18495 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18496 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18499 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18500 // We can safely do this using i16 shifts as we're only interested in
18501 // the 3 lower bits of each byte.
18502 Amt = DAG.getBitcast(ExtVT, Amt);
18503 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18504 Amt = DAG.getBitcast(VT, Amt);
18506 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18507 // r = VSELECT(r, shift(r, 4), a);
18509 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18510 R = SignBitSelect(VT, Amt, M, R);
18513 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18515 // r = VSELECT(r, shift(r, 2), a);
18516 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18517 R = SignBitSelect(VT, Amt, M, R);
18520 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18522 // return VSELECT(r, shift(r, 1), a);
18523 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18524 R = SignBitSelect(VT, Amt, M, R);
18528 if (Op->getOpcode() == ISD::SRA) {
18529 // For SRA we need to unpack each byte to the higher byte of a i16 vector
18530 // so we can correctly sign extend. We don't care what happens to the
18532 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18533 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18534 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18535 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18536 ALo = DAG.getBitcast(ExtVT, ALo);
18537 AHi = DAG.getBitcast(ExtVT, AHi);
18538 RLo = DAG.getBitcast(ExtVT, RLo);
18539 RHi = DAG.getBitcast(ExtVT, RHi);
18541 // r = VSELECT(r, shift(r, 4), a);
18542 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18543 DAG.getConstant(4, dl, ExtVT));
18544 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18545 DAG.getConstant(4, dl, ExtVT));
18546 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18547 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18550 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18551 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18553 // r = VSELECT(r, shift(r, 2), a);
18554 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18555 DAG.getConstant(2, dl, ExtVT));
18556 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18557 DAG.getConstant(2, dl, ExtVT));
18558 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18559 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18562 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18563 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18565 // r = VSELECT(r, shift(r, 1), a);
18566 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18567 DAG.getConstant(1, dl, ExtVT));
18568 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18569 DAG.getConstant(1, dl, ExtVT));
18570 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18571 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18573 // Logical shift the result back to the lower byte, leaving a zero upper
18575 // meaning that we can safely pack with PACKUSWB.
18577 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18579 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18580 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18584 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18585 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18586 // solution better.
18587 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18588 MVT ExtVT = MVT::v8i32;
18590 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18591 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18592 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18593 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18594 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18597 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18598 MVT ExtVT = MVT::v8i32;
18599 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18600 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18601 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18602 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18603 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18604 ALo = DAG.getBitcast(ExtVT, ALo);
18605 AHi = DAG.getBitcast(ExtVT, AHi);
18606 RLo = DAG.getBitcast(ExtVT, RLo);
18607 RHi = DAG.getBitcast(ExtVT, RHi);
18608 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18609 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18610 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18611 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18612 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18615 if (VT == MVT::v8i16) {
18616 unsigned ShiftOpcode = Op->getOpcode();
18618 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18619 // On SSE41 targets we make use of the fact that VSELECT lowers
18620 // to PBLENDVB which selects bytes based just on the sign bit.
18621 if (Subtarget->hasSSE41()) {
18622 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18623 V0 = DAG.getBitcast(ExtVT, V0);
18624 V1 = DAG.getBitcast(ExtVT, V1);
18625 Sel = DAG.getBitcast(ExtVT, Sel);
18626 return DAG.getBitcast(
18627 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18629 // On pre-SSE41 targets we splat the sign bit - a negative value will
18630 // set all bits of the lanes to true and VSELECT uses that in
18631 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18633 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18634 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18637 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18638 if (Subtarget->hasSSE41()) {
18639 // On SSE41 targets we need to replicate the shift mask in both
18640 // bytes for PBLENDVB.
18643 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18644 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18646 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18649 // r = VSELECT(r, shift(r, 8), a);
18650 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18651 R = SignBitSelect(Amt, M, R);
18654 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18656 // r = VSELECT(r, shift(r, 4), a);
18657 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18658 R = SignBitSelect(Amt, M, R);
18661 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18663 // r = VSELECT(r, shift(r, 2), a);
18664 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18665 R = SignBitSelect(Amt, M, R);
18668 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18670 // return VSELECT(r, shift(r, 1), a);
18671 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18672 R = SignBitSelect(Amt, M, R);
18676 // Decompose 256-bit shifts into smaller 128-bit shifts.
18677 if (VT.is256BitVector()) {
18678 unsigned NumElems = VT.getVectorNumElements();
18679 MVT EltVT = VT.getVectorElementType();
18680 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18682 // Extract the two vectors
18683 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18684 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18686 // Recreate the shift amount vectors
18687 SDValue Amt1, Amt2;
18688 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18689 // Constant shift amount
18690 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18691 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18692 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18694 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18695 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18697 // Variable shift amount
18698 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18699 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18702 // Issue new vector shifts for the smaller types
18703 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18704 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18706 // Concatenate the result back
18707 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18713 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18714 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18715 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18716 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18717 // has only one use.
18718 SDNode *N = Op.getNode();
18719 SDValue LHS = N->getOperand(0);
18720 SDValue RHS = N->getOperand(1);
18721 unsigned BaseOp = 0;
18724 switch (Op.getOpcode()) {
18725 default: llvm_unreachable("Unknown ovf instruction!");
18727 // A subtract of one will be selected as a INC. Note that INC doesn't
18728 // set CF, so we can't do this for UADDO.
18729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18731 BaseOp = X86ISD::INC;
18732 Cond = X86::COND_O;
18735 BaseOp = X86ISD::ADD;
18736 Cond = X86::COND_O;
18739 BaseOp = X86ISD::ADD;
18740 Cond = X86::COND_B;
18743 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18744 // set CF, so we can't do this for USUBO.
18745 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18747 BaseOp = X86ISD::DEC;
18748 Cond = X86::COND_O;
18751 BaseOp = X86ISD::SUB;
18752 Cond = X86::COND_O;
18755 BaseOp = X86ISD::SUB;
18756 Cond = X86::COND_B;
18759 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18760 Cond = X86::COND_O;
18762 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18763 if (N->getValueType(0) == MVT::i8) {
18764 BaseOp = X86ISD::UMUL8;
18765 Cond = X86::COND_O;
18768 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18770 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18773 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18774 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18775 SDValue(Sum.getNode(), 2));
18777 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18781 // Also sets EFLAGS.
18782 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18783 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18786 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18787 DAG.getConstant(Cond, DL, MVT::i32),
18788 SDValue(Sum.getNode(), 1));
18790 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18793 /// Returns true if the operand type is exactly twice the native width, and
18794 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18795 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18796 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18797 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18798 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18801 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18802 else if (OpWidth == 128)
18803 return Subtarget->hasCmpxchg16b();
18808 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18809 return needsCmpXchgNb(SI->getValueOperand()->getType());
18812 // Note: this turns large loads into lock cmpxchg8b/16b.
18813 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18814 TargetLowering::AtomicExpansionKind
18815 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18816 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18817 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18818 : AtomicExpansionKind::None;
18821 TargetLowering::AtomicExpansionKind
18822 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18823 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18824 Type *MemType = AI->getType();
18826 // If the operand is too big, we must see if cmpxchg8/16b is available
18827 // and default to library calls otherwise.
18828 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18829 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18830 : AtomicExpansionKind::None;
18833 AtomicRMWInst::BinOp Op = AI->getOperation();
18836 llvm_unreachable("Unknown atomic operation");
18837 case AtomicRMWInst::Xchg:
18838 case AtomicRMWInst::Add:
18839 case AtomicRMWInst::Sub:
18840 // It's better to use xadd, xsub or xchg for these in all cases.
18841 return AtomicExpansionKind::None;
18842 case AtomicRMWInst::Or:
18843 case AtomicRMWInst::And:
18844 case AtomicRMWInst::Xor:
18845 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18846 // prefix to a normal instruction for these operations.
18847 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18848 : AtomicExpansionKind::None;
18849 case AtomicRMWInst::Nand:
18850 case AtomicRMWInst::Max:
18851 case AtomicRMWInst::Min:
18852 case AtomicRMWInst::UMax:
18853 case AtomicRMWInst::UMin:
18854 // These always require a non-trivial set of data operations on x86. We must
18855 // use a cmpxchg loop.
18856 return AtomicExpansionKind::CmpXChg;
18860 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18861 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18862 // no-sse2). There isn't any reason to disable it if the target processor
18864 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18868 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18869 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18870 Type *MemType = AI->getType();
18871 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18872 // there is no benefit in turning such RMWs into loads, and it is actually
18873 // harmful as it introduces a mfence.
18874 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18877 auto Builder = IRBuilder<>(AI);
18878 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18879 auto SynchScope = AI->getSynchScope();
18880 // We must restrict the ordering to avoid generating loads with Release or
18881 // ReleaseAcquire orderings.
18882 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18883 auto Ptr = AI->getPointerOperand();
18885 // Before the load we need a fence. Here is an example lifted from
18886 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18889 // x.store(1, relaxed);
18890 // r1 = y.fetch_add(0, release);
18892 // y.fetch_add(42, acquire);
18893 // r2 = x.load(relaxed);
18894 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18895 // lowered to just a load without a fence. A mfence flushes the store buffer,
18896 // making the optimization clearly correct.
18897 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18898 // otherwise, we might be able to be more aggressive on relaxed idempotent
18899 // rmw. In practice, they do not look useful, so we don't try to be
18900 // especially clever.
18901 if (SynchScope == SingleThread)
18902 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18903 // the IR level, so we must wrap it in an intrinsic.
18906 if (!hasMFENCE(*Subtarget))
18907 // FIXME: it might make sense to use a locked operation here but on a
18908 // different cache-line to prevent cache-line bouncing. In practice it
18909 // is probably a small win, and x86 processors without mfence are rare
18910 // enough that we do not bother.
18914 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18915 Builder.CreateCall(MFence, {});
18917 // Finally we can emit the atomic load.
18918 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18919 AI->getType()->getPrimitiveSizeInBits());
18920 Loaded->setAtomic(Order, SynchScope);
18921 AI->replaceAllUsesWith(Loaded);
18922 AI->eraseFromParent();
18926 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18927 SelectionDAG &DAG) {
18929 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18930 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18931 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18932 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18934 // The only fence that needs an instruction is a sequentially-consistent
18935 // cross-thread fence.
18936 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18937 if (hasMFENCE(*Subtarget))
18938 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18940 SDValue Chain = Op.getOperand(0);
18941 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18943 DAG.getRegister(X86::ESP, MVT::i32), // Base
18944 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18945 DAG.getRegister(0, MVT::i32), // Index
18946 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18947 DAG.getRegister(0, MVT::i32), // Segment.
18951 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18952 return SDValue(Res, 0);
18955 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18956 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18959 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18960 SelectionDAG &DAG) {
18961 MVT T = Op.getSimpleValueType();
18965 switch(T.SimpleTy) {
18966 default: llvm_unreachable("Invalid value type!");
18967 case MVT::i8: Reg = X86::AL; size = 1; break;
18968 case MVT::i16: Reg = X86::AX; size = 2; break;
18969 case MVT::i32: Reg = X86::EAX; size = 4; break;
18971 assert(Subtarget->is64Bit() && "Node not type legal!");
18972 Reg = X86::RAX; size = 8;
18975 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18976 Op.getOperand(2), SDValue());
18977 SDValue Ops[] = { cpIn.getValue(0),
18980 DAG.getTargetConstant(size, DL, MVT::i8),
18981 cpIn.getValue(1) };
18982 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18983 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18984 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18988 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18989 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18990 MVT::i32, cpOut.getValue(2));
18991 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18992 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18995 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18996 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18997 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19001 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19002 SelectionDAG &DAG) {
19003 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19004 MVT DstVT = Op.getSimpleValueType();
19006 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19007 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19008 if (DstVT != MVT::f64)
19009 // This conversion needs to be expanded.
19012 SDValue InVec = Op->getOperand(0);
19014 unsigned NumElts = SrcVT.getVectorNumElements();
19015 EVT SVT = SrcVT.getVectorElementType();
19017 // Widen the vector in input in the case of MVT::v2i32.
19018 // Example: from MVT::v2i32 to MVT::v4i32.
19019 SmallVector<SDValue, 16> Elts;
19020 for (unsigned i = 0, e = NumElts; i != e; ++i)
19021 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19022 DAG.getIntPtrConstant(i, dl)));
19024 // Explicitly mark the extra elements as Undef.
19025 Elts.append(NumElts, DAG.getUNDEF(SVT));
19027 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19028 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19029 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19030 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19031 DAG.getIntPtrConstant(0, dl));
19034 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19035 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19036 assert((DstVT == MVT::i64 ||
19037 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19038 "Unexpected custom BITCAST");
19039 // i64 <=> MMX conversions are Legal.
19040 if (SrcVT==MVT::i64 && DstVT.isVector())
19042 if (DstVT==MVT::i64 && SrcVT.isVector())
19044 // MMX <=> MMX conversions are Legal.
19045 if (SrcVT.isVector() && DstVT.isVector())
19047 // All other conversions need to be expanded.
19051 /// Compute the horizontal sum of bytes in V for the elements of VT.
19053 /// Requires V to be a byte vector and VT to be an integer vector type with
19054 /// wider elements than V's type. The width of the elements of VT determines
19055 /// how many bytes of V are summed horizontally to produce each element of the
19057 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19058 const X86Subtarget *Subtarget,
19059 SelectionDAG &DAG) {
19061 MVT ByteVecVT = V.getSimpleValueType();
19062 MVT EltVT = VT.getVectorElementType();
19063 int NumElts = VT.getVectorNumElements();
19064 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19065 "Expected value to have byte element type.");
19066 assert(EltVT != MVT::i8 &&
19067 "Horizontal byte sum only makes sense for wider elements!");
19068 unsigned VecSize = VT.getSizeInBits();
19069 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19071 // PSADBW instruction horizontally add all bytes and leave the result in i64
19072 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19073 if (EltVT == MVT::i64) {
19074 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19075 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19076 return DAG.getBitcast(VT, V);
19079 if (EltVT == MVT::i32) {
19080 // We unpack the low half and high half into i32s interleaved with zeros so
19081 // that we can use PSADBW to horizontally sum them. The most useful part of
19082 // this is that it lines up the results of two PSADBW instructions to be
19083 // two v2i64 vectors which concatenated are the 4 population counts. We can
19084 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19085 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19086 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19087 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19089 // Do the horizontal sums into two v2i64s.
19090 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19091 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19092 DAG.getBitcast(ByteVecVT, Low), Zeros);
19093 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19094 DAG.getBitcast(ByteVecVT, High), Zeros);
19096 // Merge them together.
19097 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19098 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19099 DAG.getBitcast(ShortVecVT, Low),
19100 DAG.getBitcast(ShortVecVT, High));
19102 return DAG.getBitcast(VT, V);
19105 // The only element type left is i16.
19106 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19108 // To obtain pop count for each i16 element starting from the pop count for
19109 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19110 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19111 // directly supported.
19112 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19113 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19114 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19115 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19116 DAG.getBitcast(ByteVecVT, V));
19117 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19120 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19121 const X86Subtarget *Subtarget,
19122 SelectionDAG &DAG) {
19123 MVT VT = Op.getSimpleValueType();
19124 MVT EltVT = VT.getVectorElementType();
19125 unsigned VecSize = VT.getSizeInBits();
19127 // Implement a lookup table in register by using an algorithm based on:
19128 // http://wm.ite.pl/articles/sse-popcount.html
19130 // The general idea is that every lower byte nibble in the input vector is an
19131 // index into a in-register pre-computed pop count table. We then split up the
19132 // input vector in two new ones: (1) a vector with only the shifted-right
19133 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19134 // masked out higher ones) for each byte. PSHUB is used separately with both
19135 // to index the in-register table. Next, both are added and the result is a
19136 // i8 vector where each element contains the pop count for input byte.
19138 // To obtain the pop count for elements != i8, we follow up with the same
19139 // approach and use additional tricks as described below.
19141 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19142 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19143 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19144 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19146 int NumByteElts = VecSize / 8;
19147 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19148 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19149 SmallVector<SDValue, 16> LUTVec;
19150 for (int i = 0; i < NumByteElts; ++i)
19151 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19152 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19153 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19154 DAG.getConstant(0x0F, DL, MVT::i8));
19155 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19158 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19159 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19160 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19163 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19165 // The input vector is used as the shuffle mask that index elements into the
19166 // LUT. After counting low and high nibbles, add the vector to obtain the
19167 // final pop count per i8 element.
19168 SDValue HighPopCnt =
19169 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19170 SDValue LowPopCnt =
19171 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19172 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19174 if (EltVT == MVT::i8)
19177 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19180 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19181 const X86Subtarget *Subtarget,
19182 SelectionDAG &DAG) {
19183 MVT VT = Op.getSimpleValueType();
19184 assert(VT.is128BitVector() &&
19185 "Only 128-bit vector bitmath lowering supported.");
19187 int VecSize = VT.getSizeInBits();
19188 MVT EltVT = VT.getVectorElementType();
19189 int Len = EltVT.getSizeInBits();
19191 // This is the vectorized version of the "best" algorithm from
19192 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19193 // with a minor tweak to use a series of adds + shifts instead of vector
19194 // multiplications. Implemented for all integer vector types. We only use
19195 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19196 // much faster, even faster than using native popcnt instructions.
19198 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19199 MVT VT = V.getSimpleValueType();
19200 SmallVector<SDValue, 32> Shifters(
19201 VT.getVectorNumElements(),
19202 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19203 return DAG.getNode(OpCode, DL, VT, V,
19204 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19206 auto GetMask = [&](SDValue V, APInt Mask) {
19207 MVT VT = V.getSimpleValueType();
19208 SmallVector<SDValue, 32> Masks(
19209 VT.getVectorNumElements(),
19210 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19211 return DAG.getNode(ISD::AND, DL, VT, V,
19212 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19215 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19216 // x86, so set the SRL type to have elements at least i16 wide. This is
19217 // correct because all of our SRLs are followed immediately by a mask anyways
19218 // that handles any bits that sneak into the high bits of the byte elements.
19219 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19223 // v = v - ((v >> 1) & 0x55555555...)
19225 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19226 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19227 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19229 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19230 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19231 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19232 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19233 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19235 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19236 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19237 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19238 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19240 // At this point, V contains the byte-wise population count, and we are
19241 // merely doing a horizontal sum if necessary to get the wider element
19243 if (EltVT == MVT::i8)
19246 return LowerHorizontalByteSum(
19247 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19251 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19252 SelectionDAG &DAG) {
19253 MVT VT = Op.getSimpleValueType();
19254 // FIXME: Need to add AVX-512 support here!
19255 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19256 "Unknown CTPOP type to handle");
19257 SDLoc DL(Op.getNode());
19258 SDValue Op0 = Op.getOperand(0);
19260 if (!Subtarget->hasSSSE3()) {
19261 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19262 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19263 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19266 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19267 unsigned NumElems = VT.getVectorNumElements();
19269 // Extract each 128-bit vector, compute pop count and concat the result.
19270 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19271 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19273 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19274 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19275 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19278 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19281 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19282 SelectionDAG &DAG) {
19283 assert(Op.getValueType().isVector() &&
19284 "We only do custom lowering for vector population count.");
19285 return LowerVectorCTPOP(Op, Subtarget, DAG);
19288 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19289 SDNode *Node = Op.getNode();
19291 EVT T = Node->getValueType(0);
19292 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19293 DAG.getConstant(0, dl, T), Node->getOperand(2));
19294 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19295 cast<AtomicSDNode>(Node)->getMemoryVT(),
19296 Node->getOperand(0),
19297 Node->getOperand(1), negOp,
19298 cast<AtomicSDNode>(Node)->getMemOperand(),
19299 cast<AtomicSDNode>(Node)->getOrdering(),
19300 cast<AtomicSDNode>(Node)->getSynchScope());
19303 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19304 SDNode *Node = Op.getNode();
19306 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19308 // Convert seq_cst store -> xchg
19309 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19310 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19311 // (The only way to get a 16-byte store is cmpxchg16b)
19312 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19313 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19314 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19315 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19316 cast<AtomicSDNode>(Node)->getMemoryVT(),
19317 Node->getOperand(0),
19318 Node->getOperand(1), Node->getOperand(2),
19319 cast<AtomicSDNode>(Node)->getMemOperand(),
19320 cast<AtomicSDNode>(Node)->getOrdering(),
19321 cast<AtomicSDNode>(Node)->getSynchScope());
19322 return Swap.getValue(1);
19324 // Other atomic stores have a simple pattern.
19328 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19329 EVT VT = Op.getNode()->getSimpleValueType(0);
19331 // Let legalize expand this if it isn't a legal type yet.
19332 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19335 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19338 bool ExtraOp = false;
19339 switch (Op.getOpcode()) {
19340 default: llvm_unreachable("Invalid code");
19341 case ISD::ADDC: Opc = X86ISD::ADD; break;
19342 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19343 case ISD::SUBC: Opc = X86ISD::SUB; break;
19344 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19348 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19350 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19351 Op.getOperand(1), Op.getOperand(2));
19354 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19355 SelectionDAG &DAG) {
19356 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19358 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19359 // which returns the values as { float, float } (in XMM0) or
19360 // { double, double } (which is returned in XMM0, XMM1).
19362 SDValue Arg = Op.getOperand(0);
19363 EVT ArgVT = Arg.getValueType();
19364 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19366 TargetLowering::ArgListTy Args;
19367 TargetLowering::ArgListEntry Entry;
19371 Entry.isSExt = false;
19372 Entry.isZExt = false;
19373 Args.push_back(Entry);
19375 bool isF64 = ArgVT == MVT::f64;
19376 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19377 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19378 // the results are returned via SRet in memory.
19379 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19380 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19382 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19384 Type *RetTy = isF64
19385 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19386 : (Type*)VectorType::get(ArgTy, 4);
19388 TargetLowering::CallLoweringInfo CLI(DAG);
19389 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19390 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19392 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19395 // Returned in xmm0 and xmm1.
19396 return CallResult.first;
19398 // Returned in bits 0:31 and 32:64 xmm0.
19399 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19400 CallResult.first, DAG.getIntPtrConstant(0, dl));
19401 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19402 CallResult.first, DAG.getIntPtrConstant(1, dl));
19403 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19404 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19407 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19408 SelectionDAG &DAG) {
19409 assert(Subtarget->hasAVX512() &&
19410 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19412 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19413 EVT VT = N->getValue().getValueType();
19414 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19417 // X86 scatter kills mask register, so its type should be added to
19418 // the list of return values
19419 if (N->getNumValues() == 1) {
19420 SDValue Index = N->getIndex();
19421 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19422 !Index.getValueType().is512BitVector())
19423 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19425 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19426 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19427 N->getOperand(3), Index };
19429 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19430 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19431 return SDValue(NewScatter.getNode(), 0);
19436 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19437 SelectionDAG &DAG) {
19438 assert(Subtarget->hasAVX512() &&
19439 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19441 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19442 EVT VT = Op.getValueType();
19443 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19446 SDValue Index = N->getIndex();
19447 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19448 !Index.getValueType().is512BitVector()) {
19449 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19450 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19451 N->getOperand(3), Index };
19452 DAG.UpdateNodeOperands(N, Ops);
19457 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19458 SelectionDAG &DAG) const {
19459 // TODO: Eventually, the lowering of these nodes should be informed by or
19460 // deferred to the GC strategy for the function in which they appear. For
19461 // now, however, they must be lowered to something. Since they are logically
19462 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19463 // require special handling for these nodes), lower them as literal NOOPs for
19465 SmallVector<SDValue, 2> Ops;
19467 Ops.push_back(Op.getOperand(0));
19468 if (Op->getGluedNode())
19469 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19472 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19473 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19478 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19479 SelectionDAG &DAG) const {
19480 // TODO: Eventually, the lowering of these nodes should be informed by or
19481 // deferred to the GC strategy for the function in which they appear. For
19482 // now, however, they must be lowered to something. Since they are logically
19483 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19484 // require special handling for these nodes), lower them as literal NOOPs for
19486 SmallVector<SDValue, 2> Ops;
19488 Ops.push_back(Op.getOperand(0));
19489 if (Op->getGluedNode())
19490 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19493 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19494 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19499 /// LowerOperation - Provide custom lowering hooks for some operations.
19501 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19502 switch (Op.getOpcode()) {
19503 default: llvm_unreachable("Should not custom lower this!");
19504 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19505 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19506 return LowerCMP_SWAP(Op, Subtarget, DAG);
19507 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
19508 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
19509 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
19510 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
19511 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19512 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
19513 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
19514 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19515 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
19516 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19517 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19518 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
19519 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
19520 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
19521 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
19522 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
19523 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
19524 case ISD::SHL_PARTS:
19525 case ISD::SRA_PARTS:
19526 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
19527 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
19528 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
19529 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
19530 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
19531 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19532 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
19533 case ISD::SIGN_EXTEND_VECTOR_INREG:
19534 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19535 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
19536 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
19537 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
19538 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
19540 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
19541 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
19542 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
19543 case ISD::SETCC: return LowerSETCC(Op, DAG);
19544 case ISD::SELECT: return LowerSELECT(Op, DAG);
19545 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
19546 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
19547 case ISD::VASTART: return LowerVASTART(Op, DAG);
19548 case ISD::VAARG: return LowerVAARG(Op, DAG);
19549 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
19550 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19551 case ISD::INTRINSIC_VOID:
19552 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19553 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
19554 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
19555 case ISD::FRAME_TO_ARGS_OFFSET:
19556 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19557 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19558 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
19559 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
19560 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
19561 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
19562 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
19563 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
19564 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
19565 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19567 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
19568 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
19569 case ISD::UMUL_LOHI:
19570 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
19573 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
19579 case ISD::UMULO: return LowerXALUO(Op, DAG);
19580 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19581 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
19585 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19586 case ISD::ADD: return LowerADD(Op, DAG);
19587 case ISD::SUB: return LowerSUB(Op, DAG);
19591 case ISD::UMIN: return LowerMINMAX(Op, DAG);
19592 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
19593 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
19594 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
19595 case ISD::GC_TRANSITION_START:
19596 return LowerGC_TRANSITION_START(Op, DAG);
19597 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
19601 /// ReplaceNodeResults - Replace a node with an illegal result type
19602 /// with a new node built out of custom code.
19603 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19604 SmallVectorImpl<SDValue>&Results,
19605 SelectionDAG &DAG) const {
19607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19608 switch (N->getOpcode()) {
19610 llvm_unreachable("Do not know how to custom type legalize this operation!");
19611 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19612 case X86ISD::FMINC:
19614 case X86ISD::FMAXC:
19615 case X86ISD::FMAX: {
19616 EVT VT = N->getValueType(0);
19617 if (VT != MVT::v2f32)
19618 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19619 SDValue UNDEF = DAG.getUNDEF(VT);
19620 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19621 N->getOperand(0), UNDEF);
19622 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19623 N->getOperand(1), UNDEF);
19624 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19627 case ISD::SIGN_EXTEND_INREG:
19632 // We don't want to expand or promote these.
19639 case ISD::UDIVREM: {
19640 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19641 Results.push_back(V);
19644 case ISD::FP_TO_SINT:
19645 case ISD::FP_TO_UINT: {
19646 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19648 std::pair<SDValue,SDValue> Vals =
19649 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19650 SDValue FIST = Vals.first, StackSlot = Vals.second;
19651 if (FIST.getNode()) {
19652 EVT VT = N->getValueType(0);
19653 // Return a load from the stack slot.
19654 if (StackSlot.getNode())
19655 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19656 MachinePointerInfo(),
19657 false, false, false, 0));
19659 Results.push_back(FIST);
19663 case ISD::UINT_TO_FP: {
19664 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19665 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19666 N->getValueType(0) != MVT::v2f32)
19668 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19670 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19672 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19673 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19674 DAG.getBitcast(MVT::v2i64, VBias));
19675 Or = DAG.getBitcast(MVT::v2f64, Or);
19676 // TODO: Are there any fast-math-flags to propagate here?
19677 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19678 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19681 case ISD::FP_ROUND: {
19682 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19684 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19685 Results.push_back(V);
19688 case ISD::FP_EXTEND: {
19689 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19690 // No other ValueType for FP_EXTEND should reach this point.
19691 assert(N->getValueType(0) == MVT::v2f32 &&
19692 "Do not know how to legalize this Node");
19695 case ISD::INTRINSIC_W_CHAIN: {
19696 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19698 default : llvm_unreachable("Do not know how to custom type "
19699 "legalize this intrinsic operation!");
19700 case Intrinsic::x86_rdtsc:
19701 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19703 case Intrinsic::x86_rdtscp:
19704 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19706 case Intrinsic::x86_rdpmc:
19707 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19710 case ISD::READCYCLECOUNTER: {
19711 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19714 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19715 EVT T = N->getValueType(0);
19716 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19717 bool Regs64bit = T == MVT::i128;
19718 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19719 SDValue cpInL, cpInH;
19720 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19721 DAG.getConstant(0, dl, HalfT));
19722 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19723 DAG.getConstant(1, dl, HalfT));
19724 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19725 Regs64bit ? X86::RAX : X86::EAX,
19727 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19728 Regs64bit ? X86::RDX : X86::EDX,
19729 cpInH, cpInL.getValue(1));
19730 SDValue swapInL, swapInH;
19731 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19732 DAG.getConstant(0, dl, HalfT));
19733 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19734 DAG.getConstant(1, dl, HalfT));
19735 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19736 Regs64bit ? X86::RBX : X86::EBX,
19737 swapInL, cpInH.getValue(1));
19738 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19739 Regs64bit ? X86::RCX : X86::ECX,
19740 swapInH, swapInL.getValue(1));
19741 SDValue Ops[] = { swapInH.getValue(0),
19743 swapInH.getValue(1) };
19744 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19745 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19746 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19747 X86ISD::LCMPXCHG8_DAG;
19748 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19749 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19750 Regs64bit ? X86::RAX : X86::EAX,
19751 HalfT, Result.getValue(1));
19752 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19753 Regs64bit ? X86::RDX : X86::EDX,
19754 HalfT, cpOutL.getValue(2));
19755 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19757 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19758 MVT::i32, cpOutH.getValue(2));
19760 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19761 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19762 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19764 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19765 Results.push_back(Success);
19766 Results.push_back(EFLAGS.getValue(1));
19769 case ISD::ATOMIC_SWAP:
19770 case ISD::ATOMIC_LOAD_ADD:
19771 case ISD::ATOMIC_LOAD_SUB:
19772 case ISD::ATOMIC_LOAD_AND:
19773 case ISD::ATOMIC_LOAD_OR:
19774 case ISD::ATOMIC_LOAD_XOR:
19775 case ISD::ATOMIC_LOAD_NAND:
19776 case ISD::ATOMIC_LOAD_MIN:
19777 case ISD::ATOMIC_LOAD_MAX:
19778 case ISD::ATOMIC_LOAD_UMIN:
19779 case ISD::ATOMIC_LOAD_UMAX:
19780 case ISD::ATOMIC_LOAD: {
19781 // Delegate to generic TypeLegalization. Situations we can really handle
19782 // should have already been dealt with by AtomicExpandPass.cpp.
19785 case ISD::BITCAST: {
19786 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19787 EVT DstVT = N->getValueType(0);
19788 EVT SrcVT = N->getOperand(0)->getValueType(0);
19790 if (SrcVT != MVT::f64 ||
19791 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19794 unsigned NumElts = DstVT.getVectorNumElements();
19795 EVT SVT = DstVT.getVectorElementType();
19796 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19797 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19798 MVT::v2f64, N->getOperand(0));
19799 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19801 if (ExperimentalVectorWideningLegalization) {
19802 // If we are legalizing vectors by widening, we already have the desired
19803 // legal vector type, just return it.
19804 Results.push_back(ToVecInt);
19808 SmallVector<SDValue, 8> Elts;
19809 for (unsigned i = 0, e = NumElts; i != e; ++i)
19810 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19811 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19813 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19818 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19819 switch ((X86ISD::NodeType)Opcode) {
19820 case X86ISD::FIRST_NUMBER: break;
19821 case X86ISD::BSF: return "X86ISD::BSF";
19822 case X86ISD::BSR: return "X86ISD::BSR";
19823 case X86ISD::SHLD: return "X86ISD::SHLD";
19824 case X86ISD::SHRD: return "X86ISD::SHRD";
19825 case X86ISD::FAND: return "X86ISD::FAND";
19826 case X86ISD::FANDN: return "X86ISD::FANDN";
19827 case X86ISD::FOR: return "X86ISD::FOR";
19828 case X86ISD::FXOR: return "X86ISD::FXOR";
19829 case X86ISD::FILD: return "X86ISD::FILD";
19830 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19831 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19832 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19833 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19834 case X86ISD::FLD: return "X86ISD::FLD";
19835 case X86ISD::FST: return "X86ISD::FST";
19836 case X86ISD::CALL: return "X86ISD::CALL";
19837 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19838 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19839 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19840 case X86ISD::BT: return "X86ISD::BT";
19841 case X86ISD::CMP: return "X86ISD::CMP";
19842 case X86ISD::COMI: return "X86ISD::COMI";
19843 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19844 case X86ISD::CMPM: return "X86ISD::CMPM";
19845 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19846 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19847 case X86ISD::SETCC: return "X86ISD::SETCC";
19848 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19849 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19850 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19851 case X86ISD::CMOV: return "X86ISD::CMOV";
19852 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19853 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19854 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19855 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19856 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19857 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19858 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19859 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19860 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19861 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19862 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19863 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19864 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19865 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19866 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19867 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19868 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19869 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19870 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19871 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19872 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19873 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19874 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19875 case X86ISD::HADD: return "X86ISD::HADD";
19876 case X86ISD::HSUB: return "X86ISD::HSUB";
19877 case X86ISD::FHADD: return "X86ISD::FHADD";
19878 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19879 case X86ISD::ABS: return "X86ISD::ABS";
19880 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
19881 case X86ISD::FMAX: return "X86ISD::FMAX";
19882 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19883 case X86ISD::FMIN: return "X86ISD::FMIN";
19884 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19885 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19886 case X86ISD::FMINC: return "X86ISD::FMINC";
19887 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19888 case X86ISD::FRCP: return "X86ISD::FRCP";
19889 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19890 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19891 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19892 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19893 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19894 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19895 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19896 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19897 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19898 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19899 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19900 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19901 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19902 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19903 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19904 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19905 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19906 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19907 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19908 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19909 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19910 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19911 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19912 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19913 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19914 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19915 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19916 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19917 case X86ISD::VSHL: return "X86ISD::VSHL";
19918 case X86ISD::VSRL: return "X86ISD::VSRL";
19919 case X86ISD::VSRA: return "X86ISD::VSRA";
19920 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19921 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19922 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19923 case X86ISD::CMPP: return "X86ISD::CMPP";
19924 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19925 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19926 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19927 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19928 case X86ISD::ADD: return "X86ISD::ADD";
19929 case X86ISD::SUB: return "X86ISD::SUB";
19930 case X86ISD::ADC: return "X86ISD::ADC";
19931 case X86ISD::SBB: return "X86ISD::SBB";
19932 case X86ISD::SMUL: return "X86ISD::SMUL";
19933 case X86ISD::UMUL: return "X86ISD::UMUL";
19934 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19935 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19936 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19937 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19938 case X86ISD::INC: return "X86ISD::INC";
19939 case X86ISD::DEC: return "X86ISD::DEC";
19940 case X86ISD::OR: return "X86ISD::OR";
19941 case X86ISD::XOR: return "X86ISD::XOR";
19942 case X86ISD::AND: return "X86ISD::AND";
19943 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19944 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19945 case X86ISD::PTEST: return "X86ISD::PTEST";
19946 case X86ISD::TESTP: return "X86ISD::TESTP";
19947 case X86ISD::TESTM: return "X86ISD::TESTM";
19948 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19949 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19950 case X86ISD::KTEST: return "X86ISD::KTEST";
19951 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19952 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19953 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19954 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19955 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19956 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19957 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19958 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19959 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19960 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19961 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19962 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19963 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19964 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19965 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19966 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19967 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19968 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19969 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19970 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19971 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19972 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19973 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19974 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19975 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19976 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19977 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19978 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19979 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19980 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19981 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19982 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
19983 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19984 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19985 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19986 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19987 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19988 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
19989 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19990 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19991 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19992 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19993 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19994 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19995 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19996 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19997 case X86ISD::SAHF: return "X86ISD::SAHF";
19998 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19999 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20000 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20001 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20002 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20003 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20004 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20005 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20006 case X86ISD::FMADD: return "X86ISD::FMADD";
20007 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20008 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20009 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20010 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20011 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20012 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20013 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20014 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20015 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20016 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20017 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20018 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20019 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20020 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20021 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20022 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20023 case X86ISD::XTEST: return "X86ISD::XTEST";
20024 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20025 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20026 case X86ISD::SELECT: return "X86ISD::SELECT";
20027 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20028 case X86ISD::RCP28: return "X86ISD::RCP28";
20029 case X86ISD::EXP2: return "X86ISD::EXP2";
20030 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20031 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20032 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20033 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20034 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20035 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20036 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20037 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20038 case X86ISD::ADDS: return "X86ISD::ADDS";
20039 case X86ISD::SUBS: return "X86ISD::SUBS";
20040 case X86ISD::AVG: return "X86ISD::AVG";
20041 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20042 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20043 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20044 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20045 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20046 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20051 // isLegalAddressingMode - Return true if the addressing mode represented
20052 // by AM is legal for this target, for a load/store of the specified type.
20053 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20054 const AddrMode &AM, Type *Ty,
20055 unsigned AS) const {
20056 // X86 supports extremely general addressing modes.
20057 CodeModel::Model M = getTargetMachine().getCodeModel();
20058 Reloc::Model R = getTargetMachine().getRelocationModel();
20060 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20061 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20066 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20068 // If a reference to this global requires an extra load, we can't fold it.
20069 if (isGlobalStubReference(GVFlags))
20072 // If BaseGV requires a register for the PIC base, we cannot also have a
20073 // BaseReg specified.
20074 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20077 // If lower 4G is not available, then we must use rip-relative addressing.
20078 if ((M != CodeModel::Small || R != Reloc::Static) &&
20079 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20083 switch (AM.Scale) {
20089 // These scales always work.
20094 // These scales are formed with basereg+scalereg. Only accept if there is
20099 default: // Other stuff never works.
20106 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20107 unsigned Bits = Ty->getScalarSizeInBits();
20109 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20110 // particularly cheaper than those without.
20114 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20115 // variable shifts just as cheap as scalar ones.
20116 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20119 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20120 // fully general vector.
20124 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20125 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20127 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20128 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20129 return NumBits1 > NumBits2;
20132 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20133 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20136 if (!isTypeLegal(EVT::getEVT(Ty1)))
20139 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20141 // Assuming the caller doesn't have a zeroext or signext return parameter,
20142 // truncation all the way down to i1 is valid.
20146 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20147 return isInt<32>(Imm);
20150 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20151 // Can also use sub to handle negated immediates.
20152 return isInt<32>(Imm);
20155 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20156 if (!VT1.isInteger() || !VT2.isInteger())
20158 unsigned NumBits1 = VT1.getSizeInBits();
20159 unsigned NumBits2 = VT2.getSizeInBits();
20160 return NumBits1 > NumBits2;
20163 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20164 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20165 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20168 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20169 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20170 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20173 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20174 EVT VT1 = Val.getValueType();
20175 if (isZExtFree(VT1, VT2))
20178 if (Val.getOpcode() != ISD::LOAD)
20181 if (!VT1.isSimple() || !VT1.isInteger() ||
20182 !VT2.isSimple() || !VT2.isInteger())
20185 switch (VT1.getSimpleVT().SimpleTy) {
20190 // X86 has 8, 16, and 32-bit zero-extending loads.
20197 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20200 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20201 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20204 VT = VT.getScalarType();
20206 if (!VT.isSimple())
20209 switch (VT.getSimpleVT().SimpleTy) {
20220 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20221 // i16 instructions are longer (0x66 prefix) and potentially slower.
20222 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20225 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20226 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20227 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20228 /// are assumed to be legal.
20230 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20232 if (!VT.isSimple())
20235 // Not for i1 vectors
20236 if (VT.getScalarType() == MVT::i1)
20239 // Very little shuffling can be done for 64-bit vectors right now.
20240 if (VT.getSizeInBits() == 64)
20243 // We only care that the types being shuffled are legal. The lowering can
20244 // handle any possible shuffle mask that results.
20245 return isTypeLegal(VT.getSimpleVT());
20249 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20251 // Just delegate to the generic legality, clear masks aren't special.
20252 return isShuffleMaskLegal(Mask, VT);
20255 //===----------------------------------------------------------------------===//
20256 // X86 Scheduler Hooks
20257 //===----------------------------------------------------------------------===//
20259 /// Utility function to emit xbegin specifying the start of an RTM region.
20260 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20261 const TargetInstrInfo *TII) {
20262 DebugLoc DL = MI->getDebugLoc();
20264 const BasicBlock *BB = MBB->getBasicBlock();
20265 MachineFunction::iterator I = MBB;
20268 // For the v = xbegin(), we generate
20279 MachineBasicBlock *thisMBB = MBB;
20280 MachineFunction *MF = MBB->getParent();
20281 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20282 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20283 MF->insert(I, mainMBB);
20284 MF->insert(I, sinkMBB);
20286 // Transfer the remainder of BB and its successor edges to sinkMBB.
20287 sinkMBB->splice(sinkMBB->begin(), MBB,
20288 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20289 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20293 // # fallthrough to mainMBB
20294 // # abortion to sinkMBB
20295 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20296 thisMBB->addSuccessor(mainMBB);
20297 thisMBB->addSuccessor(sinkMBB);
20301 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20302 mainMBB->addSuccessor(sinkMBB);
20305 // EAX is live into the sinkMBB
20306 sinkMBB->addLiveIn(X86::EAX);
20307 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20308 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20311 MI->eraseFromParent();
20315 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20316 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20317 // in the .td file.
20318 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20319 const TargetInstrInfo *TII) {
20321 switch (MI->getOpcode()) {
20322 default: llvm_unreachable("illegal opcode!");
20323 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
20324 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20325 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
20326 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20327 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
20328 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20329 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
20330 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20333 DebugLoc dl = MI->getDebugLoc();
20334 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20336 unsigned NumArgs = MI->getNumOperands();
20337 for (unsigned i = 1; i < NumArgs; ++i) {
20338 MachineOperand &Op = MI->getOperand(i);
20339 if (!(Op.isReg() && Op.isImplicit()))
20340 MIB.addOperand(Op);
20342 if (MI->hasOneMemOperand())
20343 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20345 BuildMI(*BB, MI, dl,
20346 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20347 .addReg(X86::XMM0);
20349 MI->eraseFromParent();
20353 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20354 // defs in an instruction pattern
20355 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20356 const TargetInstrInfo *TII) {
20358 switch (MI->getOpcode()) {
20359 default: llvm_unreachable("illegal opcode!");
20360 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
20361 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20362 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
20363 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20364 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
20365 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20366 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
20367 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20370 DebugLoc dl = MI->getDebugLoc();
20371 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20373 unsigned NumArgs = MI->getNumOperands(); // remove the results
20374 for (unsigned i = 1; i < NumArgs; ++i) {
20375 MachineOperand &Op = MI->getOperand(i);
20376 if (!(Op.isReg() && Op.isImplicit()))
20377 MIB.addOperand(Op);
20379 if (MI->hasOneMemOperand())
20380 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20382 BuildMI(*BB, MI, dl,
20383 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20386 MI->eraseFromParent();
20390 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20391 const X86Subtarget *Subtarget) {
20392 DebugLoc dl = MI->getDebugLoc();
20393 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20394 // Address into RAX/EAX, other two args into ECX, EDX.
20395 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20396 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20397 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20398 for (int i = 0; i < X86::AddrNumOperands; ++i)
20399 MIB.addOperand(MI->getOperand(i));
20401 unsigned ValOps = X86::AddrNumOperands;
20402 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20403 .addReg(MI->getOperand(ValOps).getReg());
20404 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20405 .addReg(MI->getOperand(ValOps+1).getReg());
20407 // The instruction doesn't actually take any operands though.
20408 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20410 MI->eraseFromParent(); // The pseudo is gone now.
20414 MachineBasicBlock *
20415 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20416 MachineBasicBlock *MBB) const {
20417 // Emit va_arg instruction on X86-64.
20419 // Operands to this pseudo-instruction:
20420 // 0 ) Output : destination address (reg)
20421 // 1-5) Input : va_list address (addr, i64mem)
20422 // 6 ) ArgSize : Size (in bytes) of vararg type
20423 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20424 // 8 ) Align : Alignment of type
20425 // 9 ) EFLAGS (implicit-def)
20427 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20428 static_assert(X86::AddrNumOperands == 5,
20429 "VAARG_64 assumes 5 address operands");
20431 unsigned DestReg = MI->getOperand(0).getReg();
20432 MachineOperand &Base = MI->getOperand(1);
20433 MachineOperand &Scale = MI->getOperand(2);
20434 MachineOperand &Index = MI->getOperand(3);
20435 MachineOperand &Disp = MI->getOperand(4);
20436 MachineOperand &Segment = MI->getOperand(5);
20437 unsigned ArgSize = MI->getOperand(6).getImm();
20438 unsigned ArgMode = MI->getOperand(7).getImm();
20439 unsigned Align = MI->getOperand(8).getImm();
20441 // Memory Reference
20442 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20443 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20444 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20446 // Machine Information
20447 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20448 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20449 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20450 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20451 DebugLoc DL = MI->getDebugLoc();
20453 // struct va_list {
20456 // i64 overflow_area (address)
20457 // i64 reg_save_area (address)
20459 // sizeof(va_list) = 24
20460 // alignment(va_list) = 8
20462 unsigned TotalNumIntRegs = 6;
20463 unsigned TotalNumXMMRegs = 8;
20464 bool UseGPOffset = (ArgMode == 1);
20465 bool UseFPOffset = (ArgMode == 2);
20466 unsigned MaxOffset = TotalNumIntRegs * 8 +
20467 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20469 /* Align ArgSize to a multiple of 8 */
20470 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20471 bool NeedsAlign = (Align > 8);
20473 MachineBasicBlock *thisMBB = MBB;
20474 MachineBasicBlock *overflowMBB;
20475 MachineBasicBlock *offsetMBB;
20476 MachineBasicBlock *endMBB;
20478 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
20479 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
20480 unsigned OffsetReg = 0;
20482 if (!UseGPOffset && !UseFPOffset) {
20483 // If we only pull from the overflow region, we don't create a branch.
20484 // We don't need to alter control flow.
20485 OffsetDestReg = 0; // unused
20486 OverflowDestReg = DestReg;
20488 offsetMBB = nullptr;
20489 overflowMBB = thisMBB;
20492 // First emit code to check if gp_offset (or fp_offset) is below the bound.
20493 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20494 // If not, pull from overflow_area. (branch to overflowMBB)
20499 // offsetMBB overflowMBB
20504 // Registers for the PHI in endMBB
20505 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20506 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20508 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20509 MachineFunction *MF = MBB->getParent();
20510 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20511 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20512 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20514 MachineFunction::iterator MBBIter = MBB;
20517 // Insert the new basic blocks
20518 MF->insert(MBBIter, offsetMBB);
20519 MF->insert(MBBIter, overflowMBB);
20520 MF->insert(MBBIter, endMBB);
20522 // Transfer the remainder of MBB and its successor edges to endMBB.
20523 endMBB->splice(endMBB->begin(), thisMBB,
20524 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20525 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20527 // Make offsetMBB and overflowMBB successors of thisMBB
20528 thisMBB->addSuccessor(offsetMBB);
20529 thisMBB->addSuccessor(overflowMBB);
20531 // endMBB is a successor of both offsetMBB and overflowMBB
20532 offsetMBB->addSuccessor(endMBB);
20533 overflowMBB->addSuccessor(endMBB);
20535 // Load the offset value into a register
20536 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20537 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20541 .addDisp(Disp, UseFPOffset ? 4 : 0)
20542 .addOperand(Segment)
20543 .setMemRefs(MMOBegin, MMOEnd);
20545 // Check if there is enough room left to pull this argument.
20546 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20548 .addImm(MaxOffset + 8 - ArgSizeA8);
20550 // Branch to "overflowMBB" if offset >= max
20551 // Fall through to "offsetMBB" otherwise
20552 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20553 .addMBB(overflowMBB);
20556 // In offsetMBB, emit code to use the reg_save_area.
20558 assert(OffsetReg != 0);
20560 // Read the reg_save_area address.
20561 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20562 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20567 .addOperand(Segment)
20568 .setMemRefs(MMOBegin, MMOEnd);
20570 // Zero-extend the offset
20571 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20572 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20575 .addImm(X86::sub_32bit);
20577 // Add the offset to the reg_save_area to get the final address.
20578 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20579 .addReg(OffsetReg64)
20580 .addReg(RegSaveReg);
20582 // Compute the offset for the next argument
20583 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20584 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20586 .addImm(UseFPOffset ? 16 : 8);
20588 // Store it back into the va_list.
20589 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20593 .addDisp(Disp, UseFPOffset ? 4 : 0)
20594 .addOperand(Segment)
20595 .addReg(NextOffsetReg)
20596 .setMemRefs(MMOBegin, MMOEnd);
20599 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20604 // Emit code to use overflow area
20607 // Load the overflow_area address into a register.
20608 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20609 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20614 .addOperand(Segment)
20615 .setMemRefs(MMOBegin, MMOEnd);
20617 // If we need to align it, do so. Otherwise, just copy the address
20618 // to OverflowDestReg.
20620 // Align the overflow address
20621 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20622 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20624 // aligned_addr = (addr + (align-1)) & ~(align-1)
20625 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20626 .addReg(OverflowAddrReg)
20629 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20631 .addImm(~(uint64_t)(Align-1));
20633 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20634 .addReg(OverflowAddrReg);
20637 // Compute the next overflow address after this argument.
20638 // (the overflow address should be kept 8-byte aligned)
20639 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20640 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20641 .addReg(OverflowDestReg)
20642 .addImm(ArgSizeA8);
20644 // Store the new overflow address.
20645 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20650 .addOperand(Segment)
20651 .addReg(NextAddrReg)
20652 .setMemRefs(MMOBegin, MMOEnd);
20654 // If we branched, emit the PHI to the front of endMBB.
20656 BuildMI(*endMBB, endMBB->begin(), DL,
20657 TII->get(X86::PHI), DestReg)
20658 .addReg(OffsetDestReg).addMBB(offsetMBB)
20659 .addReg(OverflowDestReg).addMBB(overflowMBB);
20662 // Erase the pseudo instruction
20663 MI->eraseFromParent();
20668 MachineBasicBlock *
20669 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20671 MachineBasicBlock *MBB) const {
20672 // Emit code to save XMM registers to the stack. The ABI says that the
20673 // number of registers to save is given in %al, so it's theoretically
20674 // possible to do an indirect jump trick to avoid saving all of them,
20675 // however this code takes a simpler approach and just executes all
20676 // of the stores if %al is non-zero. It's less code, and it's probably
20677 // easier on the hardware branch predictor, and stores aren't all that
20678 // expensive anyway.
20680 // Create the new basic blocks. One block contains all the XMM stores,
20681 // and one block is the final destination regardless of whether any
20682 // stores were performed.
20683 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20684 MachineFunction *F = MBB->getParent();
20685 MachineFunction::iterator MBBIter = MBB;
20687 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20688 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20689 F->insert(MBBIter, XMMSaveMBB);
20690 F->insert(MBBIter, EndMBB);
20692 // Transfer the remainder of MBB and its successor edges to EndMBB.
20693 EndMBB->splice(EndMBB->begin(), MBB,
20694 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20695 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20697 // The original block will now fall through to the XMM save block.
20698 MBB->addSuccessor(XMMSaveMBB);
20699 // The XMMSaveMBB will fall through to the end block.
20700 XMMSaveMBB->addSuccessor(EndMBB);
20702 // Now add the instructions.
20703 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20704 DebugLoc DL = MI->getDebugLoc();
20706 unsigned CountReg = MI->getOperand(0).getReg();
20707 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20708 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20710 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20711 // If %al is 0, branch around the XMM save block.
20712 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20713 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20714 MBB->addSuccessor(EndMBB);
20717 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20718 // that was just emitted, but clearly shouldn't be "saved".
20719 assert((MI->getNumOperands() <= 3 ||
20720 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20721 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20722 && "Expected last argument to be EFLAGS");
20723 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20724 // In the XMM save block, save all the XMM argument registers.
20725 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20726 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20727 MachineMemOperand *MMO = F->getMachineMemOperand(
20728 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20729 MachineMemOperand::MOStore,
20730 /*Size=*/16, /*Align=*/16);
20731 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20732 .addFrameIndex(RegSaveFrameIndex)
20733 .addImm(/*Scale=*/1)
20734 .addReg(/*IndexReg=*/0)
20735 .addImm(/*Disp=*/Offset)
20736 .addReg(/*Segment=*/0)
20737 .addReg(MI->getOperand(i).getReg())
20738 .addMemOperand(MMO);
20741 MI->eraseFromParent(); // The pseudo instruction is gone now.
20746 // The EFLAGS operand of SelectItr might be missing a kill marker
20747 // because there were multiple uses of EFLAGS, and ISel didn't know
20748 // which to mark. Figure out whether SelectItr should have had a
20749 // kill marker, and set it if it should. Returns the correct kill
20751 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20752 MachineBasicBlock* BB,
20753 const TargetRegisterInfo* TRI) {
20754 // Scan forward through BB for a use/def of EFLAGS.
20755 MachineBasicBlock::iterator miI(std::next(SelectItr));
20756 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20757 const MachineInstr& mi = *miI;
20758 if (mi.readsRegister(X86::EFLAGS))
20760 if (mi.definesRegister(X86::EFLAGS))
20761 break; // Should have kill-flag - update below.
20764 // If we hit the end of the block, check whether EFLAGS is live into a
20766 if (miI == BB->end()) {
20767 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20768 sEnd = BB->succ_end();
20769 sItr != sEnd; ++sItr) {
20770 MachineBasicBlock* succ = *sItr;
20771 if (succ->isLiveIn(X86::EFLAGS))
20776 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20777 // out. SelectMI should have a kill flag on EFLAGS.
20778 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20782 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20783 // together with other CMOV pseudo-opcodes into a single basic-block with
20784 // conditional jump around it.
20785 static bool isCMOVPseudo(MachineInstr *MI) {
20786 switch (MI->getOpcode()) {
20787 case X86::CMOV_FR32:
20788 case X86::CMOV_FR64:
20789 case X86::CMOV_GR8:
20790 case X86::CMOV_GR16:
20791 case X86::CMOV_GR32:
20792 case X86::CMOV_RFP32:
20793 case X86::CMOV_RFP64:
20794 case X86::CMOV_RFP80:
20795 case X86::CMOV_V2F64:
20796 case X86::CMOV_V2I64:
20797 case X86::CMOV_V4F32:
20798 case X86::CMOV_V4F64:
20799 case X86::CMOV_V4I64:
20800 case X86::CMOV_V16F32:
20801 case X86::CMOV_V8F32:
20802 case X86::CMOV_V8F64:
20803 case X86::CMOV_V8I64:
20804 case X86::CMOV_V8I1:
20805 case X86::CMOV_V16I1:
20806 case X86::CMOV_V32I1:
20807 case X86::CMOV_V64I1:
20815 MachineBasicBlock *
20816 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20817 MachineBasicBlock *BB) const {
20818 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20819 DebugLoc DL = MI->getDebugLoc();
20821 // To "insert" a SELECT_CC instruction, we actually have to insert the
20822 // diamond control-flow pattern. The incoming instruction knows the
20823 // destination vreg to set, the condition code register to branch on, the
20824 // true/false values to select between, and a branch opcode to use.
20825 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20826 MachineFunction::iterator It = BB;
20832 // cmpTY ccX, r1, r2
20834 // fallthrough --> copy0MBB
20835 MachineBasicBlock *thisMBB = BB;
20836 MachineFunction *F = BB->getParent();
20838 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20839 // as described above, by inserting a BB, and then making a PHI at the join
20840 // point to select the true and false operands of the CMOV in the PHI.
20842 // The code also handles two different cases of multiple CMOV opcodes
20846 // In this case, there are multiple CMOVs in a row, all which are based on
20847 // the same condition setting (or the exact opposite condition setting).
20848 // In this case we can lower all the CMOVs using a single inserted BB, and
20849 // then make a number of PHIs at the join point to model the CMOVs. The only
20850 // trickiness here, is that in a case like:
20852 // t2 = CMOV cond1 t1, f1
20853 // t3 = CMOV cond1 t2, f2
20855 // when rewriting this into PHIs, we have to perform some renaming on the
20856 // temps since you cannot have a PHI operand refer to a PHI result earlier
20857 // in the same block. The "simple" but wrong lowering would be:
20859 // t2 = PHI t1(BB1), f1(BB2)
20860 // t3 = PHI t2(BB1), f2(BB2)
20862 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20863 // renaming is to note that on the path through BB1, t2 is really just a
20864 // copy of t1, and do that renaming, properly generating:
20866 // t2 = PHI t1(BB1), f1(BB2)
20867 // t3 = PHI t1(BB1), f2(BB2)
20869 // Case 2, we lower cascaded CMOVs such as
20871 // (CMOV (CMOV F, T, cc1), T, cc2)
20873 // to two successives branches. For that, we look for another CMOV as the
20874 // following instruction.
20876 // Without this, we would add a PHI between the two jumps, which ends up
20877 // creating a few copies all around. For instance, for
20879 // (sitofp (zext (fcmp une)))
20881 // we would generate:
20883 // ucomiss %xmm1, %xmm0
20884 // movss <1.0f>, %xmm0
20885 // movaps %xmm0, %xmm1
20887 // xorps %xmm1, %xmm1
20890 // movaps %xmm1, %xmm0
20894 // because this custom-inserter would have generated:
20906 // A: X = ...; Y = ...
20908 // C: Z = PHI [X, A], [Y, B]
20910 // E: PHI [X, C], [Z, D]
20912 // If we lower both CMOVs in a single step, we can instead generate:
20924 // A: X = ...; Y = ...
20926 // E: PHI [X, A], [X, C], [Y, D]
20928 // Which, in our sitofp/fcmp example, gives us something like:
20930 // ucomiss %xmm1, %xmm0
20931 // movss <1.0f>, %xmm0
20934 // xorps %xmm0, %xmm0
20938 MachineInstr *CascadedCMOV = nullptr;
20939 MachineInstr *LastCMOV = MI;
20940 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20941 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20942 MachineBasicBlock::iterator NextMIIt =
20943 std::next(MachineBasicBlock::iterator(MI));
20945 // Check for case 1, where there are multiple CMOVs with the same condition
20946 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20947 // number of jumps the most.
20949 if (isCMOVPseudo(MI)) {
20950 // See if we have a string of CMOVS with the same condition.
20951 while (NextMIIt != BB->end() &&
20952 isCMOVPseudo(NextMIIt) &&
20953 (NextMIIt->getOperand(3).getImm() == CC ||
20954 NextMIIt->getOperand(3).getImm() == OppCC)) {
20955 LastCMOV = &*NextMIIt;
20960 // This checks for case 2, but only do this if we didn't already find
20961 // case 1, as indicated by LastCMOV == MI.
20962 if (LastCMOV == MI &&
20963 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20964 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20965 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20966 CascadedCMOV = &*NextMIIt;
20969 MachineBasicBlock *jcc1MBB = nullptr;
20971 // If we have a cascaded CMOV, we lower it to two successive branches to
20972 // the same block. EFLAGS is used by both, so mark it as live in the second.
20973 if (CascadedCMOV) {
20974 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20975 F->insert(It, jcc1MBB);
20976 jcc1MBB->addLiveIn(X86::EFLAGS);
20979 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20980 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20981 F->insert(It, copy0MBB);
20982 F->insert(It, sinkMBB);
20984 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20985 // live into the sink and copy blocks.
20986 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20988 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20989 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20990 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20991 copy0MBB->addLiveIn(X86::EFLAGS);
20992 sinkMBB->addLiveIn(X86::EFLAGS);
20995 // Transfer the remainder of BB and its successor edges to sinkMBB.
20996 sinkMBB->splice(sinkMBB->begin(), BB,
20997 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20998 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21000 // Add the true and fallthrough blocks as its successors.
21001 if (CascadedCMOV) {
21002 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21003 BB->addSuccessor(jcc1MBB);
21005 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21006 // jump to the sinkMBB.
21007 jcc1MBB->addSuccessor(copy0MBB);
21008 jcc1MBB->addSuccessor(sinkMBB);
21010 BB->addSuccessor(copy0MBB);
21013 // The true block target of the first (or only) branch is always sinkMBB.
21014 BB->addSuccessor(sinkMBB);
21016 // Create the conditional branch instruction.
21017 unsigned Opc = X86::GetCondBranchFromCond(CC);
21018 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21020 if (CascadedCMOV) {
21021 unsigned Opc2 = X86::GetCondBranchFromCond(
21022 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21023 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21027 // %FalseValue = ...
21028 // # fallthrough to sinkMBB
21029 copy0MBB->addSuccessor(sinkMBB);
21032 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21034 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21035 MachineBasicBlock::iterator MIItEnd =
21036 std::next(MachineBasicBlock::iterator(LastCMOV));
21037 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21038 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21039 MachineInstrBuilder MIB;
21041 // As we are creating the PHIs, we have to be careful if there is more than
21042 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21043 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21044 // That also means that PHI construction must work forward from earlier to
21045 // later, and that the code must maintain a mapping from earlier PHI's
21046 // destination registers, and the registers that went into the PHI.
21048 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21049 unsigned DestReg = MIIt->getOperand(0).getReg();
21050 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21051 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21053 // If this CMOV we are generating is the opposite condition from
21054 // the jump we generated, then we have to swap the operands for the
21055 // PHI that is going to be generated.
21056 if (MIIt->getOperand(3).getImm() == OppCC)
21057 std::swap(Op1Reg, Op2Reg);
21059 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21060 Op1Reg = RegRewriteTable[Op1Reg].first;
21062 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21063 Op2Reg = RegRewriteTable[Op2Reg].second;
21065 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21066 TII->get(X86::PHI), DestReg)
21067 .addReg(Op1Reg).addMBB(copy0MBB)
21068 .addReg(Op2Reg).addMBB(thisMBB);
21070 // Add this PHI to the rewrite table.
21071 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21074 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21075 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21076 if (CascadedCMOV) {
21077 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21078 // Copy the PHI result to the register defined by the second CMOV.
21079 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21080 DL, TII->get(TargetOpcode::COPY),
21081 CascadedCMOV->getOperand(0).getReg())
21082 .addReg(MI->getOperand(0).getReg());
21083 CascadedCMOV->eraseFromParent();
21086 // Now remove the CMOV(s).
21087 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21088 (MIIt++)->eraseFromParent();
21093 MachineBasicBlock *
21094 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21095 MachineBasicBlock *BB) const {
21096 // Combine the following atomic floating-point modification pattern:
21097 // a.store(reg OP a.load(acquire), release)
21098 // Transform them into:
21099 // OPss (%gpr), %xmm
21100 // movss %xmm, (%gpr)
21101 // Or sd equivalent for 64-bit operations.
21103 switch (MI->getOpcode()) {
21104 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21105 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21106 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21108 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21109 DebugLoc DL = MI->getDebugLoc();
21110 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21111 MachineOperand MSrc = MI->getOperand(0);
21112 unsigned VSrc = MI->getOperand(5).getReg();
21113 const MachineOperand &Disp = MI->getOperand(3);
21114 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21115 bool hasDisp = Disp.isGlobal() || Disp.isImm();
21116 if (hasDisp && MSrc.isReg())
21117 MSrc.setIsKill(false);
21118 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21119 .addOperand(/*Base=*/MSrc)
21120 .addImm(/*Scale=*/1)
21121 .addReg(/*Index=*/0)
21122 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21124 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21125 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21127 .addOperand(/*Base=*/MSrc)
21128 .addImm(/*Scale=*/1)
21129 .addReg(/*Index=*/0)
21130 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21131 .addReg(/*Segment=*/0);
21132 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21133 MI->eraseFromParent(); // The pseudo instruction is gone now.
21137 MachineBasicBlock *
21138 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21139 MachineBasicBlock *BB) const {
21140 MachineFunction *MF = BB->getParent();
21141 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21142 DebugLoc DL = MI->getDebugLoc();
21143 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21145 assert(MF->shouldSplitStack());
21147 const bool Is64Bit = Subtarget->is64Bit();
21148 const bool IsLP64 = Subtarget->isTarget64BitLP64();
21150 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21151 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21154 // ... [Till the alloca]
21155 // If stacklet is not large enough, jump to mallocMBB
21158 // Allocate by subtracting from RSP
21159 // Jump to continueMBB
21162 // Allocate by call to runtime
21166 // [rest of original BB]
21169 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21170 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21171 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21173 MachineRegisterInfo &MRI = MF->getRegInfo();
21174 const TargetRegisterClass *AddrRegClass =
21175 getRegClassFor(getPointerTy(MF->getDataLayout()));
21177 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21178 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21179 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21180 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21181 sizeVReg = MI->getOperand(1).getReg(),
21182 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21184 MachineFunction::iterator MBBIter = BB;
21187 MF->insert(MBBIter, bumpMBB);
21188 MF->insert(MBBIter, mallocMBB);
21189 MF->insert(MBBIter, continueMBB);
21191 continueMBB->splice(continueMBB->begin(), BB,
21192 std::next(MachineBasicBlock::iterator(MI)), BB->end());
21193 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21195 // Add code to the main basic block to check if the stack limit has been hit,
21196 // and if so, jump to mallocMBB otherwise to bumpMBB.
21197 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21198 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21199 .addReg(tmpSPVReg).addReg(sizeVReg);
21200 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21201 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21202 .addReg(SPLimitVReg);
21203 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21205 // bumpMBB simply decreases the stack pointer, since we know the current
21206 // stacklet has enough space.
21207 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21208 .addReg(SPLimitVReg);
21209 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21210 .addReg(SPLimitVReg);
21211 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21213 // Calls into a routine in libgcc to allocate more space from the heap.
21214 const uint32_t *RegMask =
21215 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21217 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21219 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21220 .addExternalSymbol("__morestack_allocate_stack_space")
21221 .addRegMask(RegMask)
21222 .addReg(X86::RDI, RegState::Implicit)
21223 .addReg(X86::RAX, RegState::ImplicitDefine);
21224 } else if (Is64Bit) {
21225 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21227 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21228 .addExternalSymbol("__morestack_allocate_stack_space")
21229 .addRegMask(RegMask)
21230 .addReg(X86::EDI, RegState::Implicit)
21231 .addReg(X86::EAX, RegState::ImplicitDefine);
21233 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21235 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21236 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21237 .addExternalSymbol("__morestack_allocate_stack_space")
21238 .addRegMask(RegMask)
21239 .addReg(X86::EAX, RegState::ImplicitDefine);
21243 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21246 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21247 .addReg(IsLP64 ? X86::RAX : X86::EAX);
21248 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21250 // Set up the CFG correctly.
21251 BB->addSuccessor(bumpMBB);
21252 BB->addSuccessor(mallocMBB);
21253 mallocMBB->addSuccessor(continueMBB);
21254 bumpMBB->addSuccessor(continueMBB);
21256 // Take care of the PHI nodes.
21257 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21258 MI->getOperand(0).getReg())
21259 .addReg(mallocPtrVReg).addMBB(mallocMBB)
21260 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21262 // Delete the original pseudo instruction.
21263 MI->eraseFromParent();
21266 return continueMBB;
21269 MachineBasicBlock *
21270 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21271 MachineBasicBlock *BB) const {
21272 DebugLoc DL = MI->getDebugLoc();
21274 assert(!Subtarget->isTargetMachO());
21276 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21279 MI->eraseFromParent(); // The pseudo instruction is gone now.
21283 MachineBasicBlock *
21284 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21285 MachineBasicBlock *BB) const {
21286 // This is pretty easy. We're taking the value that we received from
21287 // our load from the relocation, sticking it in either RDI (x86-64)
21288 // or EAX and doing an indirect call. The return value will then
21289 // be in the normal return register.
21290 MachineFunction *F = BB->getParent();
21291 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21292 DebugLoc DL = MI->getDebugLoc();
21294 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21295 assert(MI->getOperand(3).isGlobal() && "This should be a global");
21297 // Get a register mask for the lowered call.
21298 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21299 // proper register mask.
21300 const uint32_t *RegMask =
21301 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21302 if (Subtarget->is64Bit()) {
21303 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21304 TII->get(X86::MOV64rm), X86::RDI)
21306 .addImm(0).addReg(0)
21307 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21308 MI->getOperand(3).getTargetFlags())
21310 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21311 addDirectMem(MIB, X86::RDI);
21312 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21313 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21314 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21315 TII->get(X86::MOV32rm), X86::EAX)
21317 .addImm(0).addReg(0)
21318 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21319 MI->getOperand(3).getTargetFlags())
21321 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21322 addDirectMem(MIB, X86::EAX);
21323 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21325 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21326 TII->get(X86::MOV32rm), X86::EAX)
21327 .addReg(TII->getGlobalBaseReg(F))
21328 .addImm(0).addReg(0)
21329 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21330 MI->getOperand(3).getTargetFlags())
21332 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21333 addDirectMem(MIB, X86::EAX);
21334 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21337 MI->eraseFromParent(); // The pseudo instruction is gone now.
21341 MachineBasicBlock *
21342 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21343 MachineBasicBlock *MBB) const {
21344 DebugLoc DL = MI->getDebugLoc();
21345 MachineFunction *MF = MBB->getParent();
21346 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21347 MachineRegisterInfo &MRI = MF->getRegInfo();
21349 const BasicBlock *BB = MBB->getBasicBlock();
21350 MachineFunction::iterator I = MBB;
21353 // Memory Reference
21354 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21355 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21358 unsigned MemOpndSlot = 0;
21360 unsigned CurOp = 0;
21362 DstReg = MI->getOperand(CurOp++).getReg();
21363 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21364 assert(RC->hasType(MVT::i32) && "Invalid destination!");
21365 unsigned mainDstReg = MRI.createVirtualRegister(RC);
21366 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21368 MemOpndSlot = CurOp;
21370 MVT PVT = getPointerTy(MF->getDataLayout());
21371 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21372 "Invalid Pointer Size!");
21374 // For v = setjmp(buf), we generate
21377 // buf[LabelOffset] = restoreMBB
21378 // SjLjSetup restoreMBB
21384 // v = phi(main, restore)
21387 // if base pointer being used, load it from frame
21390 MachineBasicBlock *thisMBB = MBB;
21391 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21392 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21393 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21394 MF->insert(I, mainMBB);
21395 MF->insert(I, sinkMBB);
21396 MF->push_back(restoreMBB);
21398 MachineInstrBuilder MIB;
21400 // Transfer the remainder of BB and its successor edges to sinkMBB.
21401 sinkMBB->splice(sinkMBB->begin(), MBB,
21402 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21403 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21406 unsigned PtrStoreOpc = 0;
21407 unsigned LabelReg = 0;
21408 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21409 Reloc::Model RM = MF->getTarget().getRelocationModel();
21410 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21411 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21413 // Prepare IP either in reg or imm.
21414 if (!UseImmLabel) {
21415 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21416 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21417 LabelReg = MRI.createVirtualRegister(PtrRC);
21418 if (Subtarget->is64Bit()) {
21419 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21423 .addMBB(restoreMBB)
21426 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21427 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21428 .addReg(XII->getGlobalBaseReg(MF))
21431 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21435 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21437 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21438 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21439 if (i == X86::AddrDisp)
21440 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21442 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21445 MIB.addReg(LabelReg);
21447 MIB.addMBB(restoreMBB);
21448 MIB.setMemRefs(MMOBegin, MMOEnd);
21450 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21451 .addMBB(restoreMBB);
21453 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21454 MIB.addRegMask(RegInfo->getNoPreservedMask());
21455 thisMBB->addSuccessor(mainMBB);
21456 thisMBB->addSuccessor(restoreMBB);
21460 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21461 mainMBB->addSuccessor(sinkMBB);
21464 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21465 TII->get(X86::PHI), DstReg)
21466 .addReg(mainDstReg).addMBB(mainMBB)
21467 .addReg(restoreDstReg).addMBB(restoreMBB);
21470 if (RegInfo->hasBasePointer(*MF)) {
21471 const bool Uses64BitFramePtr =
21472 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21473 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21474 X86FI->setRestoreBasePointer(MF);
21475 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21476 unsigned BasePtr = RegInfo->getBaseRegister();
21477 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21478 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21479 FramePtr, true, X86FI->getRestoreBasePointerOffset())
21480 .setMIFlag(MachineInstr::FrameSetup);
21482 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21483 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21484 restoreMBB->addSuccessor(sinkMBB);
21486 MI->eraseFromParent();
21490 MachineBasicBlock *
21491 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21492 MachineBasicBlock *MBB) const {
21493 DebugLoc DL = MI->getDebugLoc();
21494 MachineFunction *MF = MBB->getParent();
21495 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21496 MachineRegisterInfo &MRI = MF->getRegInfo();
21498 // Memory Reference
21499 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21500 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21502 MVT PVT = getPointerTy(MF->getDataLayout());
21503 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21504 "Invalid Pointer Size!");
21506 const TargetRegisterClass *RC =
21507 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21508 unsigned Tmp = MRI.createVirtualRegister(RC);
21509 // Since FP is only updated here but NOT referenced, it's treated as GPR.
21510 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21511 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21512 unsigned SP = RegInfo->getStackRegister();
21514 MachineInstrBuilder MIB;
21516 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21517 const int64_t SPOffset = 2 * PVT.getStoreSize();
21519 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21520 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21523 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21524 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21525 MIB.addOperand(MI->getOperand(i));
21526 MIB.setMemRefs(MMOBegin, MMOEnd);
21528 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21529 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21530 if (i == X86::AddrDisp)
21531 MIB.addDisp(MI->getOperand(i), LabelOffset);
21533 MIB.addOperand(MI->getOperand(i));
21535 MIB.setMemRefs(MMOBegin, MMOEnd);
21537 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21538 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21539 if (i == X86::AddrDisp)
21540 MIB.addDisp(MI->getOperand(i), SPOffset);
21542 MIB.addOperand(MI->getOperand(i));
21544 MIB.setMemRefs(MMOBegin, MMOEnd);
21546 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21548 MI->eraseFromParent();
21552 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21553 // accumulator loops. Writing back to the accumulator allows the coalescer
21554 // to remove extra copies in the loop.
21555 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
21556 MachineBasicBlock *
21557 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21558 MachineBasicBlock *MBB) const {
21559 MachineOperand &AddendOp = MI->getOperand(3);
21561 // Bail out early if the addend isn't a register - we can't switch these.
21562 if (!AddendOp.isReg())
21565 MachineFunction &MF = *MBB->getParent();
21566 MachineRegisterInfo &MRI = MF.getRegInfo();
21568 // Check whether the addend is defined by a PHI:
21569 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21570 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21571 if (!AddendDef.isPHI())
21574 // Look for the following pattern:
21576 // %addend = phi [%entry, 0], [%loop, %result]
21578 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21582 // %addend = phi [%entry, 0], [%loop, %result]
21584 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21586 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21587 assert(AddendDef.getOperand(i).isReg());
21588 MachineOperand PHISrcOp = AddendDef.getOperand(i);
21589 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21590 if (&PHISrcInst == MI) {
21591 // Found a matching instruction.
21592 unsigned NewFMAOpc = 0;
21593 switch (MI->getOpcode()) {
21594 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21595 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21596 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21597 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21598 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21599 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21600 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21601 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21602 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21603 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21604 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21605 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21606 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21607 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21608 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21609 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21610 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21611 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21612 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21613 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21615 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21616 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21617 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21618 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21619 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21620 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21621 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21622 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21623 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21624 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21625 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21626 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21627 default: llvm_unreachable("Unrecognized FMA variant.");
21630 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21631 MachineInstrBuilder MIB =
21632 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21633 .addOperand(MI->getOperand(0))
21634 .addOperand(MI->getOperand(3))
21635 .addOperand(MI->getOperand(2))
21636 .addOperand(MI->getOperand(1));
21637 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21638 MI->eraseFromParent();
21645 MachineBasicBlock *
21646 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21647 MachineBasicBlock *BB) const {
21648 switch (MI->getOpcode()) {
21649 default: llvm_unreachable("Unexpected instr type to insert");
21650 case X86::TAILJMPd64:
21651 case X86::TAILJMPr64:
21652 case X86::TAILJMPm64:
21653 case X86::TAILJMPd64_REX:
21654 case X86::TAILJMPr64_REX:
21655 case X86::TAILJMPm64_REX:
21656 llvm_unreachable("TAILJMP64 would not be touched here.");
21657 case X86::TCRETURNdi64:
21658 case X86::TCRETURNri64:
21659 case X86::TCRETURNmi64:
21661 case X86::WIN_ALLOCA:
21662 return EmitLoweredWinAlloca(MI, BB);
21663 case X86::SEG_ALLOCA_32:
21664 case X86::SEG_ALLOCA_64:
21665 return EmitLoweredSegAlloca(MI, BB);
21666 case X86::TLSCall_32:
21667 case X86::TLSCall_64:
21668 return EmitLoweredTLSCall(MI, BB);
21669 case X86::CMOV_FR32:
21670 case X86::CMOV_FR64:
21671 case X86::CMOV_GR8:
21672 case X86::CMOV_GR16:
21673 case X86::CMOV_GR32:
21674 case X86::CMOV_RFP32:
21675 case X86::CMOV_RFP64:
21676 case X86::CMOV_RFP80:
21677 case X86::CMOV_V2F64:
21678 case X86::CMOV_V2I64:
21679 case X86::CMOV_V4F32:
21680 case X86::CMOV_V4F64:
21681 case X86::CMOV_V4I64:
21682 case X86::CMOV_V16F32:
21683 case X86::CMOV_V8F32:
21684 case X86::CMOV_V8F64:
21685 case X86::CMOV_V8I64:
21686 case X86::CMOV_V8I1:
21687 case X86::CMOV_V16I1:
21688 case X86::CMOV_V32I1:
21689 case X86::CMOV_V64I1:
21690 return EmitLoweredSelect(MI, BB);
21692 case X86::RELEASE_FADD32mr:
21693 case X86::RELEASE_FADD64mr:
21694 return EmitLoweredAtomicFP(MI, BB);
21696 case X86::FP32_TO_INT16_IN_MEM:
21697 case X86::FP32_TO_INT32_IN_MEM:
21698 case X86::FP32_TO_INT64_IN_MEM:
21699 case X86::FP64_TO_INT16_IN_MEM:
21700 case X86::FP64_TO_INT32_IN_MEM:
21701 case X86::FP64_TO_INT64_IN_MEM:
21702 case X86::FP80_TO_INT16_IN_MEM:
21703 case X86::FP80_TO_INT32_IN_MEM:
21704 case X86::FP80_TO_INT64_IN_MEM: {
21705 MachineFunction *F = BB->getParent();
21706 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21707 DebugLoc DL = MI->getDebugLoc();
21709 // Change the floating point control register to use "round towards zero"
21710 // mode when truncating to an integer value.
21711 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21712 addFrameReference(BuildMI(*BB, MI, DL,
21713 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21715 // Load the old value of the high byte of the control word...
21717 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21718 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21721 // Set the high part to be round to zero...
21722 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21725 // Reload the modified control word now...
21726 addFrameReference(BuildMI(*BB, MI, DL,
21727 TII->get(X86::FLDCW16m)), CWFrameIdx);
21729 // Restore the memory image of control word to original value
21730 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21733 // Get the X86 opcode to use.
21735 switch (MI->getOpcode()) {
21736 default: llvm_unreachable("illegal opcode!");
21737 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21738 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21739 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21740 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21741 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21742 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21743 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21744 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21745 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21749 MachineOperand &Op = MI->getOperand(0);
21751 AM.BaseType = X86AddressMode::RegBase;
21752 AM.Base.Reg = Op.getReg();
21754 AM.BaseType = X86AddressMode::FrameIndexBase;
21755 AM.Base.FrameIndex = Op.getIndex();
21757 Op = MI->getOperand(1);
21759 AM.Scale = Op.getImm();
21760 Op = MI->getOperand(2);
21762 AM.IndexReg = Op.getImm();
21763 Op = MI->getOperand(3);
21764 if (Op.isGlobal()) {
21765 AM.GV = Op.getGlobal();
21767 AM.Disp = Op.getImm();
21769 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21770 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21772 // Reload the original control word now.
21773 addFrameReference(BuildMI(*BB, MI, DL,
21774 TII->get(X86::FLDCW16m)), CWFrameIdx);
21776 MI->eraseFromParent(); // The pseudo instruction is gone now.
21779 // String/text processing lowering.
21780 case X86::PCMPISTRM128REG:
21781 case X86::VPCMPISTRM128REG:
21782 case X86::PCMPISTRM128MEM:
21783 case X86::VPCMPISTRM128MEM:
21784 case X86::PCMPESTRM128REG:
21785 case X86::VPCMPESTRM128REG:
21786 case X86::PCMPESTRM128MEM:
21787 case X86::VPCMPESTRM128MEM:
21788 assert(Subtarget->hasSSE42() &&
21789 "Target must have SSE4.2 or AVX features enabled");
21790 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21792 // String/text processing lowering.
21793 case X86::PCMPISTRIREG:
21794 case X86::VPCMPISTRIREG:
21795 case X86::PCMPISTRIMEM:
21796 case X86::VPCMPISTRIMEM:
21797 case X86::PCMPESTRIREG:
21798 case X86::VPCMPESTRIREG:
21799 case X86::PCMPESTRIMEM:
21800 case X86::VPCMPESTRIMEM:
21801 assert(Subtarget->hasSSE42() &&
21802 "Target must have SSE4.2 or AVX features enabled");
21803 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21805 // Thread synchronization.
21807 return EmitMonitor(MI, BB, Subtarget);
21811 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21813 case X86::VASTART_SAVE_XMM_REGS:
21814 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21816 case X86::VAARG_64:
21817 return EmitVAARG64WithCustomInserter(MI, BB);
21819 case X86::EH_SjLj_SetJmp32:
21820 case X86::EH_SjLj_SetJmp64:
21821 return emitEHSjLjSetJmp(MI, BB);
21823 case X86::EH_SjLj_LongJmp32:
21824 case X86::EH_SjLj_LongJmp64:
21825 return emitEHSjLjLongJmp(MI, BB);
21827 case TargetOpcode::STATEPOINT:
21828 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21829 // this point in the process. We diverge later.
21830 return emitPatchPoint(MI, BB);
21832 case TargetOpcode::STACKMAP:
21833 case TargetOpcode::PATCHPOINT:
21834 return emitPatchPoint(MI, BB);
21836 case X86::VFMADDPDr213r:
21837 case X86::VFMADDPSr213r:
21838 case X86::VFMADDSDr213r:
21839 case X86::VFMADDSSr213r:
21840 case X86::VFMSUBPDr213r:
21841 case X86::VFMSUBPSr213r:
21842 case X86::VFMSUBSDr213r:
21843 case X86::VFMSUBSSr213r:
21844 case X86::VFNMADDPDr213r:
21845 case X86::VFNMADDPSr213r:
21846 case X86::VFNMADDSDr213r:
21847 case X86::VFNMADDSSr213r:
21848 case X86::VFNMSUBPDr213r:
21849 case X86::VFNMSUBPSr213r:
21850 case X86::VFNMSUBSDr213r:
21851 case X86::VFNMSUBSSr213r:
21852 case X86::VFMADDSUBPDr213r:
21853 case X86::VFMADDSUBPSr213r:
21854 case X86::VFMSUBADDPDr213r:
21855 case X86::VFMSUBADDPSr213r:
21856 case X86::VFMADDPDr213rY:
21857 case X86::VFMADDPSr213rY:
21858 case X86::VFMSUBPDr213rY:
21859 case X86::VFMSUBPSr213rY:
21860 case X86::VFNMADDPDr213rY:
21861 case X86::VFNMADDPSr213rY:
21862 case X86::VFNMSUBPDr213rY:
21863 case X86::VFNMSUBPSr213rY:
21864 case X86::VFMADDSUBPDr213rY:
21865 case X86::VFMADDSUBPSr213rY:
21866 case X86::VFMSUBADDPDr213rY:
21867 case X86::VFMSUBADDPSr213rY:
21868 return emitFMA3Instr(MI, BB);
21872 //===----------------------------------------------------------------------===//
21873 // X86 Optimization Hooks
21874 //===----------------------------------------------------------------------===//
21876 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21879 const SelectionDAG &DAG,
21880 unsigned Depth) const {
21881 unsigned BitWidth = KnownZero.getBitWidth();
21882 unsigned Opc = Op.getOpcode();
21883 assert((Opc >= ISD::BUILTIN_OP_END ||
21884 Opc == ISD::INTRINSIC_WO_CHAIN ||
21885 Opc == ISD::INTRINSIC_W_CHAIN ||
21886 Opc == ISD::INTRINSIC_VOID) &&
21887 "Should use MaskedValueIsZero if you don't know whether Op"
21888 " is a target node!");
21890 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21904 // These nodes' second result is a boolean.
21905 if (Op.getResNo() == 0)
21908 case X86ISD::SETCC:
21909 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21911 case ISD::INTRINSIC_WO_CHAIN: {
21912 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21913 unsigned NumLoBits = 0;
21916 case Intrinsic::x86_sse_movmsk_ps:
21917 case Intrinsic::x86_avx_movmsk_ps_256:
21918 case Intrinsic::x86_sse2_movmsk_pd:
21919 case Intrinsic::x86_avx_movmsk_pd_256:
21920 case Intrinsic::x86_mmx_pmovmskb:
21921 case Intrinsic::x86_sse2_pmovmskb_128:
21922 case Intrinsic::x86_avx2_pmovmskb: {
21923 // High bits of movmskp{s|d}, pmovmskb are known zero.
21925 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21926 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21927 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21928 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21929 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21930 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21931 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21932 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21934 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21943 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21945 const SelectionDAG &,
21946 unsigned Depth) const {
21947 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21948 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21949 return Op.getValueType().getScalarType().getSizeInBits();
21955 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21956 /// node is a GlobalAddress + offset.
21957 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21958 const GlobalValue* &GA,
21959 int64_t &Offset) const {
21960 if (N->getOpcode() == X86ISD::Wrapper) {
21961 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21962 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21963 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21967 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21970 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21971 /// same as extracting the high 128-bit part of 256-bit vector and then
21972 /// inserting the result into the low part of a new 256-bit vector
21973 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21974 EVT VT = SVOp->getValueType(0);
21975 unsigned NumElems = VT.getVectorNumElements();
21977 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21978 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21979 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21980 SVOp->getMaskElt(j) >= 0)
21986 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21987 /// same as extracting the low 128-bit part of 256-bit vector and then
21988 /// inserting the result into the high part of a new 256-bit vector
21989 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21990 EVT VT = SVOp->getValueType(0);
21991 unsigned NumElems = VT.getVectorNumElements();
21993 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21994 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21995 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21996 SVOp->getMaskElt(j) >= 0)
22002 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22003 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22004 TargetLowering::DAGCombinerInfo &DCI,
22005 const X86Subtarget* Subtarget) {
22007 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22008 SDValue V1 = SVOp->getOperand(0);
22009 SDValue V2 = SVOp->getOperand(1);
22010 EVT VT = SVOp->getValueType(0);
22011 unsigned NumElems = VT.getVectorNumElements();
22013 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22014 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22018 // V UNDEF BUILD_VECTOR UNDEF
22020 // CONCAT_VECTOR CONCAT_VECTOR
22023 // RESULT: V + zero extended
22025 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22026 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22027 V1.getOperand(1).getOpcode() != ISD::UNDEF)
22030 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22033 // To match the shuffle mask, the first half of the mask should
22034 // be exactly the first vector, and all the rest a splat with the
22035 // first element of the second one.
22036 for (unsigned i = 0; i != NumElems/2; ++i)
22037 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22038 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22041 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22042 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22043 if (Ld->hasNUsesOfValue(1, 0)) {
22044 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22045 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22047 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22049 Ld->getPointerInfo(),
22050 Ld->getAlignment(),
22051 false/*isVolatile*/, true/*ReadMem*/,
22052 false/*WriteMem*/);
22054 // Make sure the newly-created LOAD is in the same position as Ld in
22055 // terms of dependency. We create a TokenFactor for Ld and ResNode,
22056 // and update uses of Ld's output chain to use the TokenFactor.
22057 if (Ld->hasAnyUseOfValue(1)) {
22058 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22059 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22060 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22061 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22062 SDValue(ResNode.getNode(), 1));
22065 return DAG.getBitcast(VT, ResNode);
22069 // Emit a zeroed vector and insert the desired subvector on its
22071 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22072 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22073 return DCI.CombineTo(N, InsV);
22076 //===--------------------------------------------------------------------===//
22077 // Combine some shuffles into subvector extracts and inserts:
22080 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22081 if (isShuffleHigh128VectorInsertLow(SVOp)) {
22082 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22083 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22084 return DCI.CombineTo(N, InsV);
22087 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22088 if (isShuffleLow128VectorInsertHigh(SVOp)) {
22089 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22090 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22091 return DCI.CombineTo(N, InsV);
22097 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22100 /// This is the leaf of the recursive combinine below. When we have found some
22101 /// chain of single-use x86 shuffle instructions and accumulated the combined
22102 /// shuffle mask represented by them, this will try to pattern match that mask
22103 /// into either a single instruction if there is a special purpose instruction
22104 /// for this operation, or into a PSHUFB instruction which is a fully general
22105 /// instruction but should only be used to replace chains over a certain depth.
22106 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22107 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22108 TargetLowering::DAGCombinerInfo &DCI,
22109 const X86Subtarget *Subtarget) {
22110 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22112 // Find the operand that enters the chain. Note that multiple uses are OK
22113 // here, we're not going to remove the operand we find.
22114 SDValue Input = Op.getOperand(0);
22115 while (Input.getOpcode() == ISD::BITCAST)
22116 Input = Input.getOperand(0);
22118 MVT VT = Input.getSimpleValueType();
22119 MVT RootVT = Root.getSimpleValueType();
22122 if (Mask.size() == 1) {
22123 int Index = Mask[0];
22124 assert((Index >= 0 || Index == SM_SentinelUndef ||
22125 Index == SM_SentinelZero) &&
22126 "Invalid shuffle index found!");
22128 // We may end up with an accumulated mask of size 1 as a result of
22129 // widening of shuffle operands (see function canWidenShuffleElements).
22130 // If the only shuffle index is equal to SM_SentinelZero then propagate
22131 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22132 // mask, and therefore the entire chain of shuffles can be folded away.
22133 if (Index == SM_SentinelZero)
22134 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22136 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22141 // Use the float domain if the operand type is a floating point type.
22142 bool FloatDomain = VT.isFloatingPoint();
22144 // For floating point shuffles, we don't have free copies in the shuffle
22145 // instructions or the ability to load as part of the instruction, so
22146 // canonicalize their shuffles to UNPCK or MOV variants.
22148 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22149 // vectors because it can have a load folded into it that UNPCK cannot. This
22150 // doesn't preclude something switching to the shorter encoding post-RA.
22152 // FIXME: Should teach these routines about AVX vector widths.
22153 if (FloatDomain && VT.getSizeInBits() == 128) {
22154 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22155 bool Lo = Mask.equals({0, 0});
22158 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22159 // is no slower than UNPCKLPD but has the option to fold the input operand
22160 // into even an unaligned memory load.
22161 if (Lo && Subtarget->hasSSE3()) {
22162 Shuffle = X86ISD::MOVDDUP;
22163 ShuffleVT = MVT::v2f64;
22165 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22166 // than the UNPCK variants.
22167 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22168 ShuffleVT = MVT::v4f32;
22170 if (Depth == 1 && Root->getOpcode() == Shuffle)
22171 return false; // Nothing to do!
22172 Op = DAG.getBitcast(ShuffleVT, Input);
22173 DCI.AddToWorklist(Op.getNode());
22174 if (Shuffle == X86ISD::MOVDDUP)
22175 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22177 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22178 DCI.AddToWorklist(Op.getNode());
22179 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22183 if (Subtarget->hasSSE3() &&
22184 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22185 bool Lo = Mask.equals({0, 0, 2, 2});
22186 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22187 MVT ShuffleVT = MVT::v4f32;
22188 if (Depth == 1 && Root->getOpcode() == Shuffle)
22189 return false; // Nothing to do!
22190 Op = DAG.getBitcast(ShuffleVT, Input);
22191 DCI.AddToWorklist(Op.getNode());
22192 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22193 DCI.AddToWorklist(Op.getNode());
22194 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22198 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22199 bool Lo = Mask.equals({0, 0, 1, 1});
22200 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22201 MVT ShuffleVT = MVT::v4f32;
22202 if (Depth == 1 && Root->getOpcode() == Shuffle)
22203 return false; // Nothing to do!
22204 Op = DAG.getBitcast(ShuffleVT, Input);
22205 DCI.AddToWorklist(Op.getNode());
22206 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22207 DCI.AddToWorklist(Op.getNode());
22208 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22214 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22215 // variants as none of these have single-instruction variants that are
22216 // superior to the UNPCK formulation.
22217 if (!FloatDomain && VT.getSizeInBits() == 128 &&
22218 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22219 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22220 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22222 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22223 bool Lo = Mask[0] == 0;
22224 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22225 if (Depth == 1 && Root->getOpcode() == Shuffle)
22226 return false; // Nothing to do!
22228 switch (Mask.size()) {
22230 ShuffleVT = MVT::v8i16;
22233 ShuffleVT = MVT::v16i8;
22236 llvm_unreachable("Impossible mask size!");
22238 Op = DAG.getBitcast(ShuffleVT, Input);
22239 DCI.AddToWorklist(Op.getNode());
22240 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22241 DCI.AddToWorklist(Op.getNode());
22242 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22247 // Don't try to re-form single instruction chains under any circumstances now
22248 // that we've done encoding canonicalization for them.
22252 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22253 // can replace them with a single PSHUFB instruction profitably. Intel's
22254 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22255 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22256 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22257 SmallVector<SDValue, 16> PSHUFBMask;
22258 int NumBytes = VT.getSizeInBits() / 8;
22259 int Ratio = NumBytes / Mask.size();
22260 for (int i = 0; i < NumBytes; ++i) {
22261 if (Mask[i / Ratio] == SM_SentinelUndef) {
22262 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22265 int M = Mask[i / Ratio] != SM_SentinelZero
22266 ? Ratio * Mask[i / Ratio] + i % Ratio
22268 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22270 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22271 Op = DAG.getBitcast(ByteVT, Input);
22272 DCI.AddToWorklist(Op.getNode());
22273 SDValue PSHUFBMaskOp =
22274 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22275 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22276 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22277 DCI.AddToWorklist(Op.getNode());
22278 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22283 // Failed to find any combines.
22287 /// \brief Fully generic combining of x86 shuffle instructions.
22289 /// This should be the last combine run over the x86 shuffle instructions. Once
22290 /// they have been fully optimized, this will recursively consider all chains
22291 /// of single-use shuffle instructions, build a generic model of the cumulative
22292 /// shuffle operation, and check for simpler instructions which implement this
22293 /// operation. We use this primarily for two purposes:
22295 /// 1) Collapse generic shuffles to specialized single instructions when
22296 /// equivalent. In most cases, this is just an encoding size win, but
22297 /// sometimes we will collapse multiple generic shuffles into a single
22298 /// special-purpose shuffle.
22299 /// 2) Look for sequences of shuffle instructions with 3 or more total
22300 /// instructions, and replace them with the slightly more expensive SSSE3
22301 /// PSHUFB instruction if available. We do this as the last combining step
22302 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
22303 /// a suitable short sequence of other instructions. The PHUFB will either
22304 /// use a register or have to read from memory and so is slightly (but only
22305 /// slightly) more expensive than the other shuffle instructions.
22307 /// Because this is inherently a quadratic operation (for each shuffle in
22308 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22309 /// This should never be an issue in practice as the shuffle lowering doesn't
22310 /// produce sequences of more than 8 instructions.
22312 /// FIXME: We will currently miss some cases where the redundant shuffling
22313 /// would simplify under the threshold for PSHUFB formation because of
22314 /// combine-ordering. To fix this, we should do the redundant instruction
22315 /// combining in this recursive walk.
22316 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22317 ArrayRef<int> RootMask,
22318 int Depth, bool HasPSHUFB,
22320 TargetLowering::DAGCombinerInfo &DCI,
22321 const X86Subtarget *Subtarget) {
22322 // Bound the depth of our recursive combine because this is ultimately
22323 // quadratic in nature.
22327 // Directly rip through bitcasts to find the underlying operand.
22328 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22329 Op = Op.getOperand(0);
22331 MVT VT = Op.getSimpleValueType();
22332 if (!VT.isVector())
22333 return false; // Bail if we hit a non-vector.
22335 assert(Root.getSimpleValueType().isVector() &&
22336 "Shuffles operate on vector types!");
22337 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22338 "Can only combine shuffles of the same vector register size.");
22340 if (!isTargetShuffle(Op.getOpcode()))
22342 SmallVector<int, 16> OpMask;
22344 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22345 // We only can combine unary shuffles which we can decode the mask for.
22346 if (!HaveMask || !IsUnary)
22349 assert(VT.getVectorNumElements() == OpMask.size() &&
22350 "Different mask size from vector size!");
22351 assert(((RootMask.size() > OpMask.size() &&
22352 RootMask.size() % OpMask.size() == 0) ||
22353 (OpMask.size() > RootMask.size() &&
22354 OpMask.size() % RootMask.size() == 0) ||
22355 OpMask.size() == RootMask.size()) &&
22356 "The smaller number of elements must divide the larger.");
22357 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22358 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22359 assert(((RootRatio == 1 && OpRatio == 1) ||
22360 (RootRatio == 1) != (OpRatio == 1)) &&
22361 "Must not have a ratio for both incoming and op masks!");
22363 SmallVector<int, 16> Mask;
22364 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22366 // Merge this shuffle operation's mask into our accumulated mask. Note that
22367 // this shuffle's mask will be the first applied to the input, followed by the
22368 // root mask to get us all the way to the root value arrangement. The reason
22369 // for this order is that we are recursing up the operation chain.
22370 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22371 int RootIdx = i / RootRatio;
22372 if (RootMask[RootIdx] < 0) {
22373 // This is a zero or undef lane, we're done.
22374 Mask.push_back(RootMask[RootIdx]);
22378 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22379 int OpIdx = RootMaskedIdx / OpRatio;
22380 if (OpMask[OpIdx] < 0) {
22381 // The incoming lanes are zero or undef, it doesn't matter which ones we
22383 Mask.push_back(OpMask[OpIdx]);
22387 // Ok, we have non-zero lanes, map them through.
22388 Mask.push_back(OpMask[OpIdx] * OpRatio +
22389 RootMaskedIdx % OpRatio);
22392 // See if we can recurse into the operand to combine more things.
22393 switch (Op.getOpcode()) {
22394 case X86ISD::PSHUFB:
22396 case X86ISD::PSHUFD:
22397 case X86ISD::PSHUFHW:
22398 case X86ISD::PSHUFLW:
22399 if (Op.getOperand(0).hasOneUse() &&
22400 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22401 HasPSHUFB, DAG, DCI, Subtarget))
22405 case X86ISD::UNPCKL:
22406 case X86ISD::UNPCKH:
22407 assert(Op.getOperand(0) == Op.getOperand(1) &&
22408 "We only combine unary shuffles!");
22409 // We can't check for single use, we have to check that this shuffle is the
22411 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22412 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22413 HasPSHUFB, DAG, DCI, Subtarget))
22418 // Minor canonicalization of the accumulated shuffle mask to make it easier
22419 // to match below. All this does is detect masks with squential pairs of
22420 // elements, and shrink them to the half-width mask. It does this in a loop
22421 // so it will reduce the size of the mask to the minimal width mask which
22422 // performs an equivalent shuffle.
22423 SmallVector<int, 16> WidenedMask;
22424 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22425 Mask = std::move(WidenedMask);
22426 WidenedMask.clear();
22429 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22433 /// \brief Get the PSHUF-style mask from PSHUF node.
22435 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22436 /// PSHUF-style masks that can be reused with such instructions.
22437 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22438 MVT VT = N.getSimpleValueType();
22439 SmallVector<int, 4> Mask;
22441 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22445 // If we have more than 128-bits, only the low 128-bits of shuffle mask
22446 // matter. Check that the upper masks are repeats and remove them.
22447 if (VT.getSizeInBits() > 128) {
22448 int LaneElts = 128 / VT.getScalarSizeInBits();
22450 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22451 for (int j = 0; j < LaneElts; ++j)
22452 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22453 "Mask doesn't repeat in high 128-bit lanes!");
22455 Mask.resize(LaneElts);
22458 switch (N.getOpcode()) {
22459 case X86ISD::PSHUFD:
22461 case X86ISD::PSHUFLW:
22464 case X86ISD::PSHUFHW:
22465 Mask.erase(Mask.begin(), Mask.begin() + 4);
22466 for (int &M : Mask)
22470 llvm_unreachable("No valid shuffle instruction found!");
22474 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22476 /// We walk up the chain and look for a combinable shuffle, skipping over
22477 /// shuffles that we could hoist this shuffle's transformation past without
22478 /// altering anything.
22480 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22482 TargetLowering::DAGCombinerInfo &DCI) {
22483 assert(N.getOpcode() == X86ISD::PSHUFD &&
22484 "Called with something other than an x86 128-bit half shuffle!");
22487 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22488 // of the shuffles in the chain so that we can form a fresh chain to replace
22490 SmallVector<SDValue, 8> Chain;
22491 SDValue V = N.getOperand(0);
22492 for (; V.hasOneUse(); V = V.getOperand(0)) {
22493 switch (V.getOpcode()) {
22495 return SDValue(); // Nothing combined!
22498 // Skip bitcasts as we always know the type for the target specific
22502 case X86ISD::PSHUFD:
22503 // Found another dword shuffle.
22506 case X86ISD::PSHUFLW:
22507 // Check that the low words (being shuffled) are the identity in the
22508 // dword shuffle, and the high words are self-contained.
22509 if (Mask[0] != 0 || Mask[1] != 1 ||
22510 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22513 Chain.push_back(V);
22516 case X86ISD::PSHUFHW:
22517 // Check that the high words (being shuffled) are the identity in the
22518 // dword shuffle, and the low words are self-contained.
22519 if (Mask[2] != 2 || Mask[3] != 3 ||
22520 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22523 Chain.push_back(V);
22526 case X86ISD::UNPCKL:
22527 case X86ISD::UNPCKH:
22528 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22529 // shuffle into a preceding word shuffle.
22530 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22531 V.getSimpleValueType().getScalarType() != MVT::i16)
22534 // Search for a half-shuffle which we can combine with.
22535 unsigned CombineOp =
22536 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22537 if (V.getOperand(0) != V.getOperand(1) ||
22538 !V->isOnlyUserOf(V.getOperand(0).getNode()))
22540 Chain.push_back(V);
22541 V = V.getOperand(0);
22543 switch (V.getOpcode()) {
22545 return SDValue(); // Nothing to combine.
22547 case X86ISD::PSHUFLW:
22548 case X86ISD::PSHUFHW:
22549 if (V.getOpcode() == CombineOp)
22552 Chain.push_back(V);
22556 V = V.getOperand(0);
22560 } while (V.hasOneUse());
22563 // Break out of the loop if we break out of the switch.
22567 if (!V.hasOneUse())
22568 // We fell out of the loop without finding a viable combining instruction.
22571 // Merge this node's mask and our incoming mask.
22572 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22573 for (int &M : Mask)
22575 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22576 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22578 // Rebuild the chain around this new shuffle.
22579 while (!Chain.empty()) {
22580 SDValue W = Chain.pop_back_val();
22582 if (V.getValueType() != W.getOperand(0).getValueType())
22583 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22585 switch (W.getOpcode()) {
22587 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22589 case X86ISD::UNPCKL:
22590 case X86ISD::UNPCKH:
22591 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22594 case X86ISD::PSHUFD:
22595 case X86ISD::PSHUFLW:
22596 case X86ISD::PSHUFHW:
22597 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22601 if (V.getValueType() != N.getValueType())
22602 V = DAG.getBitcast(N.getValueType(), V);
22604 // Return the new chain to replace N.
22608 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22611 /// We walk up the chain, skipping shuffles of the other half and looking
22612 /// through shuffles which switch halves trying to find a shuffle of the same
22613 /// pair of dwords.
22614 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22616 TargetLowering::DAGCombinerInfo &DCI) {
22618 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22619 "Called with something other than an x86 128-bit half shuffle!");
22621 unsigned CombineOpcode = N.getOpcode();
22623 // Walk up a single-use chain looking for a combinable shuffle.
22624 SDValue V = N.getOperand(0);
22625 for (; V.hasOneUse(); V = V.getOperand(0)) {
22626 switch (V.getOpcode()) {
22628 return false; // Nothing combined!
22631 // Skip bitcasts as we always know the type for the target specific
22635 case X86ISD::PSHUFLW:
22636 case X86ISD::PSHUFHW:
22637 if (V.getOpcode() == CombineOpcode)
22640 // Other-half shuffles are no-ops.
22643 // Break out of the loop if we break out of the switch.
22647 if (!V.hasOneUse())
22648 // We fell out of the loop without finding a viable combining instruction.
22651 // Combine away the bottom node as its shuffle will be accumulated into
22652 // a preceding shuffle.
22653 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22655 // Record the old value.
22658 // Merge this node's mask and our incoming mask (adjusted to account for all
22659 // the pshufd instructions encountered).
22660 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22661 for (int &M : Mask)
22663 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22664 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22666 // Check that the shuffles didn't cancel each other out. If not, we need to
22667 // combine to the new one.
22669 // Replace the combinable shuffle with the combined one, updating all users
22670 // so that we re-evaluate the chain here.
22671 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22676 /// \brief Try to combine x86 target specific shuffles.
22677 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22678 TargetLowering::DAGCombinerInfo &DCI,
22679 const X86Subtarget *Subtarget) {
22681 MVT VT = N.getSimpleValueType();
22682 SmallVector<int, 4> Mask;
22684 switch (N.getOpcode()) {
22685 case X86ISD::PSHUFD:
22686 case X86ISD::PSHUFLW:
22687 case X86ISD::PSHUFHW:
22688 Mask = getPSHUFShuffleMask(N);
22689 assert(Mask.size() == 4);
22695 // Nuke no-op shuffles that show up after combining.
22696 if (isNoopShuffleMask(Mask))
22697 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22699 // Look for simplifications involving one or two shuffle instructions.
22700 SDValue V = N.getOperand(0);
22701 switch (N.getOpcode()) {
22704 case X86ISD::PSHUFLW:
22705 case X86ISD::PSHUFHW:
22706 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22708 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22709 return SDValue(); // We combined away this shuffle, so we're done.
22711 // See if this reduces to a PSHUFD which is no more expensive and can
22712 // combine with more operations. Note that it has to at least flip the
22713 // dwords as otherwise it would have been removed as a no-op.
22714 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22715 int DMask[] = {0, 1, 2, 3};
22716 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22717 DMask[DOffset + 0] = DOffset + 1;
22718 DMask[DOffset + 1] = DOffset + 0;
22719 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22720 V = DAG.getBitcast(DVT, V);
22721 DCI.AddToWorklist(V.getNode());
22722 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22723 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22724 DCI.AddToWorklist(V.getNode());
22725 return DAG.getBitcast(VT, V);
22728 // Look for shuffle patterns which can be implemented as a single unpack.
22729 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22730 // only works when we have a PSHUFD followed by two half-shuffles.
22731 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22732 (V.getOpcode() == X86ISD::PSHUFLW ||
22733 V.getOpcode() == X86ISD::PSHUFHW) &&
22734 V.getOpcode() != N.getOpcode() &&
22736 SDValue D = V.getOperand(0);
22737 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22738 D = D.getOperand(0);
22739 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22740 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22741 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22742 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22743 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22745 for (int i = 0; i < 4; ++i) {
22746 WordMask[i + NOffset] = Mask[i] + NOffset;
22747 WordMask[i + VOffset] = VMask[i] + VOffset;
22749 // Map the word mask through the DWord mask.
22751 for (int i = 0; i < 8; ++i)
22752 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22753 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22754 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22755 // We can replace all three shuffles with an unpack.
22756 V = DAG.getBitcast(VT, D.getOperand(0));
22757 DCI.AddToWorklist(V.getNode());
22758 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22767 case X86ISD::PSHUFD:
22768 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22777 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22779 /// We combine this directly on the abstract vector shuffle nodes so it is
22780 /// easier to generically match. We also insert dummy vector shuffle nodes for
22781 /// the operands which explicitly discard the lanes which are unused by this
22782 /// operation to try to flow through the rest of the combiner the fact that
22783 /// they're unused.
22784 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22786 EVT VT = N->getValueType(0);
22788 // We only handle target-independent shuffles.
22789 // FIXME: It would be easy and harmless to use the target shuffle mask
22790 // extraction tool to support more.
22791 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22794 auto *SVN = cast<ShuffleVectorSDNode>(N);
22795 ArrayRef<int> Mask = SVN->getMask();
22796 SDValue V1 = N->getOperand(0);
22797 SDValue V2 = N->getOperand(1);
22799 // We require the first shuffle operand to be the SUB node, and the second to
22800 // be the ADD node.
22801 // FIXME: We should support the commuted patterns.
22802 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22805 // If there are other uses of these operations we can't fold them.
22806 if (!V1->hasOneUse() || !V2->hasOneUse())
22809 // Ensure that both operations have the same operands. Note that we can
22810 // commute the FADD operands.
22811 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22812 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22813 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22816 // We're looking for blends between FADD and FSUB nodes. We insist on these
22817 // nodes being lined up in a specific expected pattern.
22818 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22819 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22820 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22823 // Only specific types are legal at this point, assert so we notice if and
22824 // when these change.
22825 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22826 VT == MVT::v4f64) &&
22827 "Unknown vector type encountered!");
22829 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22832 /// PerformShuffleCombine - Performs several different shuffle combines.
22833 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22834 TargetLowering::DAGCombinerInfo &DCI,
22835 const X86Subtarget *Subtarget) {
22837 SDValue N0 = N->getOperand(0);
22838 SDValue N1 = N->getOperand(1);
22839 EVT VT = N->getValueType(0);
22841 // Don't create instructions with illegal types after legalize types has run.
22842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22843 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22846 // If we have legalized the vector types, look for blends of FADD and FSUB
22847 // nodes that we can fuse into an ADDSUB node.
22848 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22849 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22852 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22853 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22854 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22855 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22857 // During Type Legalization, when promoting illegal vector types,
22858 // the backend might introduce new shuffle dag nodes and bitcasts.
22860 // This code performs the following transformation:
22861 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22862 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22864 // We do this only if both the bitcast and the BINOP dag nodes have
22865 // one use. Also, perform this transformation only if the new binary
22866 // operation is legal. This is to avoid introducing dag nodes that
22867 // potentially need to be further expanded (or custom lowered) into a
22868 // less optimal sequence of dag nodes.
22869 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22870 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22871 N0.getOpcode() == ISD::BITCAST) {
22872 SDValue BC0 = N0.getOperand(0);
22873 EVT SVT = BC0.getValueType();
22874 unsigned Opcode = BC0.getOpcode();
22875 unsigned NumElts = VT.getVectorNumElements();
22877 if (BC0.hasOneUse() && SVT.isVector() &&
22878 SVT.getVectorNumElements() * 2 == NumElts &&
22879 TLI.isOperationLegal(Opcode, VT)) {
22880 bool CanFold = false;
22892 unsigned SVTNumElts = SVT.getVectorNumElements();
22893 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22894 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22895 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22896 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22897 CanFold = SVOp->getMaskElt(i) < 0;
22900 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22901 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22902 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22903 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22908 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22909 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22910 // consecutive, non-overlapping, and in the right order.
22911 SmallVector<SDValue, 16> Elts;
22912 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22913 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22915 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22918 if (isTargetShuffle(N->getOpcode())) {
22920 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22921 if (Shuffle.getNode())
22924 // Try recursively combining arbitrary sequences of x86 shuffle
22925 // instructions into higher-order shuffles. We do this after combining
22926 // specific PSHUF instruction sequences into their minimal form so that we
22927 // can evaluate how many specialized shuffle instructions are involved in
22928 // a particular chain.
22929 SmallVector<int, 1> NonceMask; // Just a placeholder.
22930 NonceMask.push_back(0);
22931 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22932 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22934 return SDValue(); // This routine will use CombineTo to replace N.
22940 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22941 /// specific shuffle of a load can be folded into a single element load.
22942 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22943 /// shuffles have been custom lowered so we need to handle those here.
22944 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22945 TargetLowering::DAGCombinerInfo &DCI) {
22946 if (DCI.isBeforeLegalizeOps())
22949 SDValue InVec = N->getOperand(0);
22950 SDValue EltNo = N->getOperand(1);
22952 if (!isa<ConstantSDNode>(EltNo))
22955 EVT OriginalVT = InVec.getValueType();
22957 if (InVec.getOpcode() == ISD::BITCAST) {
22958 // Don't duplicate a load with other uses.
22959 if (!InVec.hasOneUse())
22961 EVT BCVT = InVec.getOperand(0).getValueType();
22962 if (!BCVT.isVector() ||
22963 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22965 InVec = InVec.getOperand(0);
22968 EVT CurrentVT = InVec.getValueType();
22970 if (!isTargetShuffle(InVec.getOpcode()))
22973 // Don't duplicate a load with other uses.
22974 if (!InVec.hasOneUse())
22977 SmallVector<int, 16> ShuffleMask;
22979 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22980 ShuffleMask, UnaryShuffle))
22983 // Select the input vector, guarding against out of range extract vector.
22984 unsigned NumElems = CurrentVT.getVectorNumElements();
22985 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22986 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22987 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22988 : InVec.getOperand(1);
22990 // If inputs to shuffle are the same for both ops, then allow 2 uses
22991 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22992 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22994 if (LdNode.getOpcode() == ISD::BITCAST) {
22995 // Don't duplicate a load with other uses.
22996 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22999 AllowedUses = 1; // only allow 1 load use if we have a bitcast
23000 LdNode = LdNode.getOperand(0);
23003 if (!ISD::isNormalLoad(LdNode.getNode()))
23006 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23008 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23011 EVT EltVT = N->getValueType(0);
23012 // If there's a bitcast before the shuffle, check if the load type and
23013 // alignment is valid.
23014 unsigned Align = LN0->getAlignment();
23015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23016 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23017 EltVT.getTypeForEVT(*DAG.getContext()));
23019 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23022 // All checks match so transform back to vector_shuffle so that DAG combiner
23023 // can finish the job
23026 // Create shuffle node taking into account the case that its a unary shuffle
23027 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23028 : InVec.getOperand(1);
23029 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23030 InVec.getOperand(0), Shuffle,
23032 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23033 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23037 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23038 /// special and don't usually play with other vector types, it's better to
23039 /// handle them early to be sure we emit efficient code by avoiding
23040 /// store-load conversions.
23041 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
23042 if (N->getValueType(0) != MVT::x86mmx ||
23043 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
23044 N->getOperand(0)->getValueType(0) != MVT::v2i32)
23047 SDValue V = N->getOperand(0);
23048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
23049 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
23050 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
23051 N->getValueType(0), V.getOperand(0));
23056 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23057 /// generation and convert it from being a bunch of shuffles and extracts
23058 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23059 /// storing the value and loading scalars back, while for x64 we should
23060 /// use 64-bit extracts and shifts.
23061 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23062 TargetLowering::DAGCombinerInfo &DCI) {
23063 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23066 SDValue InputVector = N->getOperand(0);
23067 SDLoc dl(InputVector);
23068 // Detect mmx to i32 conversion through a v2i32 elt extract.
23069 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23070 N->getValueType(0) == MVT::i32 &&
23071 InputVector.getValueType() == MVT::v2i32) {
23073 // The bitcast source is a direct mmx result.
23074 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23075 if (MMXSrc.getValueType() == MVT::x86mmx)
23076 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23077 N->getValueType(0),
23078 InputVector.getNode()->getOperand(0));
23080 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23081 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23082 MMXSrc.getValueType() == MVT::i64) {
23083 SDValue MMXSrcOp = MMXSrc.getOperand(0);
23084 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23085 MMXSrcOp.getValueType() == MVT::v1i64 &&
23086 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23087 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23088 N->getValueType(0), MMXSrcOp.getOperand(0));
23092 EVT VT = N->getValueType(0);
23094 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
23095 InputVector.getOpcode() == ISD::BITCAST &&
23096 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
23097 uint64_t ExtractedElt =
23098 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23099 uint64_t InputValue =
23100 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23101 uint64_t Res = (InputValue >> ExtractedElt) & 1;
23102 return DAG.getConstant(Res, dl, MVT::i1);
23104 // Only operate on vectors of 4 elements, where the alternative shuffling
23105 // gets to be more expensive.
23106 if (InputVector.getValueType() != MVT::v4i32)
23109 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23110 // single use which is a sign-extend or zero-extend, and all elements are
23112 SmallVector<SDNode *, 4> Uses;
23113 unsigned ExtractedElements = 0;
23114 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23115 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23116 if (UI.getUse().getResNo() != InputVector.getResNo())
23119 SDNode *Extract = *UI;
23120 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23123 if (Extract->getValueType(0) != MVT::i32)
23125 if (!Extract->hasOneUse())
23127 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23128 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23130 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23133 // Record which element was extracted.
23134 ExtractedElements |=
23135 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23137 Uses.push_back(Extract);
23140 // If not all the elements were used, this may not be worthwhile.
23141 if (ExtractedElements != 15)
23144 // Ok, we've now decided to do the transformation.
23145 // If 64-bit shifts are legal, use the extract-shift sequence,
23146 // otherwise bounce the vector off the cache.
23147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23150 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23151 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23152 auto &DL = DAG.getDataLayout();
23153 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23154 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23155 DAG.getConstant(0, dl, VecIdxTy));
23156 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23157 DAG.getConstant(1, dl, VecIdxTy));
23159 SDValue ShAmt = DAG.getConstant(
23160 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23161 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23162 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23163 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23164 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23165 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23166 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23168 // Store the value to a temporary stack slot.
23169 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23170 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23171 MachinePointerInfo(), false, false, 0);
23173 EVT ElementType = InputVector.getValueType().getVectorElementType();
23174 unsigned EltSize = ElementType.getSizeInBits() / 8;
23176 // Replace each use (extract) with a load of the appropriate element.
23177 for (unsigned i = 0; i < 4; ++i) {
23178 uint64_t Offset = EltSize * i;
23179 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23180 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23182 SDValue ScalarAddr =
23183 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23185 // Load the scalar.
23186 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23187 ScalarAddr, MachinePointerInfo(),
23188 false, false, false, 0);
23193 // Replace the extracts
23194 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23195 UE = Uses.end(); UI != UE; ++UI) {
23196 SDNode *Extract = *UI;
23198 SDValue Idx = Extract->getOperand(1);
23199 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23200 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23203 // The replacement was made in place; don't return anything.
23208 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23209 const X86Subtarget *Subtarget) {
23211 SDValue Cond = N->getOperand(0);
23212 SDValue LHS = N->getOperand(1);
23213 SDValue RHS = N->getOperand(2);
23215 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23216 SDValue CondSrc = Cond->getOperand(0);
23217 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23218 Cond = CondSrc->getOperand(0);
23221 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23224 // A vselect where all conditions and data are constants can be optimized into
23225 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23226 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23227 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23230 unsigned MaskValue = 0;
23231 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23234 MVT VT = N->getSimpleValueType(0);
23235 unsigned NumElems = VT.getVectorNumElements();
23236 SmallVector<int, 8> ShuffleMask(NumElems, -1);
23237 for (unsigned i = 0; i < NumElems; ++i) {
23238 // Be sure we emit undef where we can.
23239 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23240 ShuffleMask[i] = -1;
23242 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23245 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23246 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23248 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23251 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23253 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23254 TargetLowering::DAGCombinerInfo &DCI,
23255 const X86Subtarget *Subtarget) {
23257 SDValue Cond = N->getOperand(0);
23258 // Get the LHS/RHS of the select.
23259 SDValue LHS = N->getOperand(1);
23260 SDValue RHS = N->getOperand(2);
23261 EVT VT = LHS.getValueType();
23262 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23264 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23265 // instructions match the semantics of the common C idiom x<y?x:y but not
23266 // x<=y?x:y, because of how they handle negative zero (which can be
23267 // ignored in unsafe-math mode).
23268 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23269 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23270 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23271 (Subtarget->hasSSE2() ||
23272 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23273 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23275 unsigned Opcode = 0;
23276 // Check for x CC y ? x : y.
23277 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23278 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23282 // Converting this to a min would handle NaNs incorrectly, and swapping
23283 // the operands would cause it to handle comparisons between positive
23284 // and negative zero incorrectly.
23285 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23286 if (!DAG.getTarget().Options.UnsafeFPMath &&
23287 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23289 std::swap(LHS, RHS);
23291 Opcode = X86ISD::FMIN;
23294 // Converting this to a min would handle comparisons between positive
23295 // and negative zero incorrectly.
23296 if (!DAG.getTarget().Options.UnsafeFPMath &&
23297 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23299 Opcode = X86ISD::FMIN;
23302 // Converting this to a min would handle both negative zeros and NaNs
23303 // incorrectly, but we can swap the operands to fix both.
23304 std::swap(LHS, RHS);
23308 Opcode = X86ISD::FMIN;
23312 // Converting this to a max would handle comparisons between positive
23313 // and negative zero incorrectly.
23314 if (!DAG.getTarget().Options.UnsafeFPMath &&
23315 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23317 Opcode = X86ISD::FMAX;
23320 // Converting this to a max would handle NaNs incorrectly, and swapping
23321 // the operands would cause it to handle comparisons between positive
23322 // and negative zero incorrectly.
23323 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23324 if (!DAG.getTarget().Options.UnsafeFPMath &&
23325 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23327 std::swap(LHS, RHS);
23329 Opcode = X86ISD::FMAX;
23332 // Converting this to a max would handle both negative zeros and NaNs
23333 // incorrectly, but we can swap the operands to fix both.
23334 std::swap(LHS, RHS);
23338 Opcode = X86ISD::FMAX;
23341 // Check for x CC y ? y : x -- a min/max with reversed arms.
23342 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23343 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23347 // Converting this to a min would handle comparisons between positive
23348 // and negative zero incorrectly, and swapping the operands would
23349 // cause it to handle NaNs incorrectly.
23350 if (!DAG.getTarget().Options.UnsafeFPMath &&
23351 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23352 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23354 std::swap(LHS, RHS);
23356 Opcode = X86ISD::FMIN;
23359 // Converting this to a min would handle NaNs incorrectly.
23360 if (!DAG.getTarget().Options.UnsafeFPMath &&
23361 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23363 Opcode = X86ISD::FMIN;
23366 // Converting this to a min would handle both negative zeros and NaNs
23367 // incorrectly, but we can swap the operands to fix both.
23368 std::swap(LHS, RHS);
23372 Opcode = X86ISD::FMIN;
23376 // Converting this to a max would handle NaNs incorrectly.
23377 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23379 Opcode = X86ISD::FMAX;
23382 // Converting this to a max would handle comparisons between positive
23383 // and negative zero incorrectly, and swapping the operands would
23384 // cause it to handle NaNs incorrectly.
23385 if (!DAG.getTarget().Options.UnsafeFPMath &&
23386 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23387 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23389 std::swap(LHS, RHS);
23391 Opcode = X86ISD::FMAX;
23394 // Converting this to a max would handle both negative zeros and NaNs
23395 // incorrectly, but we can swap the operands to fix both.
23396 std::swap(LHS, RHS);
23400 Opcode = X86ISD::FMAX;
23406 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23409 EVT CondVT = Cond.getValueType();
23410 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23411 CondVT.getVectorElementType() == MVT::i1) {
23412 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23413 // lowering on KNL. In this case we convert it to
23414 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23415 // The same situation for all 128 and 256-bit vectors of i8 and i16.
23416 // Since SKX these selects have a proper lowering.
23417 EVT OpVT = LHS.getValueType();
23418 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23419 (OpVT.getVectorElementType() == MVT::i8 ||
23420 OpVT.getVectorElementType() == MVT::i16) &&
23421 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23422 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23423 DCI.AddToWorklist(Cond.getNode());
23424 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23427 // If this is a select between two integer constants, try to do some
23429 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23430 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23431 // Don't do this for crazy integer types.
23432 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23433 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23434 // so that TrueC (the true value) is larger than FalseC.
23435 bool NeedsCondInvert = false;
23437 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23438 // Efficiently invertible.
23439 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
23440 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
23441 isa<ConstantSDNode>(Cond.getOperand(1))))) {
23442 NeedsCondInvert = true;
23443 std::swap(TrueC, FalseC);
23446 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
23447 if (FalseC->getAPIntValue() == 0 &&
23448 TrueC->getAPIntValue().isPowerOf2()) {
23449 if (NeedsCondInvert) // Invert the condition if needed.
23450 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23451 DAG.getConstant(1, DL, Cond.getValueType()));
23453 // Zero extend the condition if needed.
23454 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23456 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23457 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23458 DAG.getConstant(ShAmt, DL, MVT::i8));
23461 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23462 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23463 if (NeedsCondInvert) // Invert the condition if needed.
23464 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23465 DAG.getConstant(1, DL, Cond.getValueType()));
23467 // Zero extend the condition if needed.
23468 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23469 FalseC->getValueType(0), Cond);
23470 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23471 SDValue(FalseC, 0));
23474 // Optimize cases that will turn into an LEA instruction. This requires
23475 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23476 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23477 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23478 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23480 bool isFastMultiplier = false;
23482 switch ((unsigned char)Diff) {
23484 case 1: // result = add base, cond
23485 case 2: // result = lea base( , cond*2)
23486 case 3: // result = lea base(cond, cond*2)
23487 case 4: // result = lea base( , cond*4)
23488 case 5: // result = lea base(cond, cond*4)
23489 case 8: // result = lea base( , cond*8)
23490 case 9: // result = lea base(cond, cond*8)
23491 isFastMultiplier = true;
23496 if (isFastMultiplier) {
23497 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23498 if (NeedsCondInvert) // Invert the condition if needed.
23499 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23500 DAG.getConstant(1, DL, Cond.getValueType()));
23502 // Zero extend the condition if needed.
23503 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23505 // Scale the condition by the difference.
23507 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23508 DAG.getConstant(Diff, DL,
23509 Cond.getValueType()));
23511 // Add the base if non-zero.
23512 if (FalseC->getAPIntValue() != 0)
23513 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23514 SDValue(FalseC, 0));
23521 // Canonicalize max and min:
23522 // (x > y) ? x : y -> (x >= y) ? x : y
23523 // (x < y) ? x : y -> (x <= y) ? x : y
23524 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23525 // the need for an extra compare
23526 // against zero. e.g.
23527 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23529 // testl %edi, %edi
23531 // cmovgl %edi, %eax
23535 // cmovsl %eax, %edi
23536 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23537 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23538 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23539 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23544 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23545 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23546 Cond.getOperand(0), Cond.getOperand(1), NewCC);
23547 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23552 // Early exit check
23553 if (!TLI.isTypeLegal(VT))
23556 // Match VSELECTs into subs with unsigned saturation.
23557 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23558 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23559 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23560 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23561 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23563 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23564 // left side invert the predicate to simplify logic below.
23566 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23568 CC = ISD::getSetCCInverse(CC, true);
23569 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23573 if (Other.getNode() && Other->getNumOperands() == 2 &&
23574 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23575 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23576 SDValue CondRHS = Cond->getOperand(1);
23578 // Look for a general sub with unsigned saturation first.
23579 // x >= y ? x-y : 0 --> subus x, y
23580 // x > y ? x-y : 0 --> subus x, y
23581 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23582 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23583 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23585 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23586 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23587 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23588 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23589 // If the RHS is a constant we have to reverse the const
23590 // canonicalization.
23591 // x > C-1 ? x+-C : 0 --> subus x, C
23592 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23593 CondRHSConst->getAPIntValue() ==
23594 (-OpRHSConst->getAPIntValue() - 1))
23595 return DAG.getNode(
23596 X86ISD::SUBUS, DL, VT, OpLHS,
23597 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23599 // Another special case: If C was a sign bit, the sub has been
23600 // canonicalized into a xor.
23601 // FIXME: Would it be better to use computeKnownBits to determine
23602 // whether it's safe to decanonicalize the xor?
23603 // x s< 0 ? x^C : 0 --> subus x, C
23604 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23605 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23606 OpRHSConst->getAPIntValue().isSignBit())
23607 // Note that we have to rebuild the RHS constant here to ensure we
23608 // don't rely on particular values of undef lanes.
23609 return DAG.getNode(
23610 X86ISD::SUBUS, DL, VT, OpLHS,
23611 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23616 // Simplify vector selection if condition value type matches vselect
23618 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23619 assert(Cond.getValueType().isVector() &&
23620 "vector select expects a vector selector!");
23622 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23623 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23625 // Try invert the condition if true value is not all 1s and false value
23627 if (!TValIsAllOnes && !FValIsAllZeros &&
23628 // Check if the selector will be produced by CMPP*/PCMP*
23629 Cond.getOpcode() == ISD::SETCC &&
23630 // Check if SETCC has already been promoted
23631 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23633 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23634 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23636 if (TValIsAllZeros || FValIsAllOnes) {
23637 SDValue CC = Cond.getOperand(2);
23638 ISD::CondCode NewCC =
23639 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23640 Cond.getOperand(0).getValueType().isInteger());
23641 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23642 std::swap(LHS, RHS);
23643 TValIsAllOnes = FValIsAllOnes;
23644 FValIsAllZeros = TValIsAllZeros;
23648 if (TValIsAllOnes || FValIsAllZeros) {
23651 if (TValIsAllOnes && FValIsAllZeros)
23653 else if (TValIsAllOnes)
23655 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23656 else if (FValIsAllZeros)
23657 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23658 DAG.getBitcast(CondVT, LHS));
23660 return DAG.getBitcast(VT, Ret);
23664 // We should generate an X86ISD::BLENDI from a vselect if its argument
23665 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23666 // constants. This specific pattern gets generated when we split a
23667 // selector for a 512 bit vector in a machine without AVX512 (but with
23668 // 256-bit vectors), during legalization:
23670 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23672 // Iff we find this pattern and the build_vectors are built from
23673 // constants, we translate the vselect into a shuffle_vector that we
23674 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23675 if ((N->getOpcode() == ISD::VSELECT ||
23676 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23677 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23678 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23679 if (Shuffle.getNode())
23683 // If this is a *dynamic* select (non-constant condition) and we can match
23684 // this node with one of the variable blend instructions, restructure the
23685 // condition so that the blends can use the high bit of each element and use
23686 // SimplifyDemandedBits to simplify the condition operand.
23687 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23688 !DCI.isBeforeLegalize() &&
23689 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23690 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23692 // Don't optimize vector selects that map to mask-registers.
23696 // We can only handle the cases where VSELECT is directly legal on the
23697 // subtarget. We custom lower VSELECT nodes with constant conditions and
23698 // this makes it hard to see whether a dynamic VSELECT will correctly
23699 // lower, so we both check the operation's status and explicitly handle the
23700 // cases where a *dynamic* blend will fail even though a constant-condition
23701 // blend could be custom lowered.
23702 // FIXME: We should find a better way to handle this class of problems.
23703 // Potentially, we should combine constant-condition vselect nodes
23704 // pre-legalization into shuffles and not mark as many types as custom
23706 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23708 // FIXME: We don't support i16-element blends currently. We could and
23709 // should support them by making *all* the bits in the condition be set
23710 // rather than just the high bit and using an i8-element blend.
23711 if (VT.getScalarType() == MVT::i16)
23713 // Dynamic blending was only available from SSE4.1 onward.
23714 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23716 // Byte blends are only available in AVX2
23717 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23718 !Subtarget->hasAVX2())
23721 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23722 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23724 APInt KnownZero, KnownOne;
23725 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23726 DCI.isBeforeLegalizeOps());
23727 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23728 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23730 // If we changed the computation somewhere in the DAG, this change
23731 // will affect all users of Cond.
23732 // Make sure it is fine and update all the nodes so that we do not
23733 // use the generic VSELECT anymore. Otherwise, we may perform
23734 // wrong optimizations as we messed up with the actual expectation
23735 // for the vector boolean values.
23736 if (Cond != TLO.Old) {
23737 // Check all uses of that condition operand to check whether it will be
23738 // consumed by non-BLEND instructions, which may depend on all bits are
23740 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23742 if (I->getOpcode() != ISD::VSELECT)
23743 // TODO: Add other opcodes eventually lowered into BLEND.
23746 // Update all the users of the condition, before committing the change,
23747 // so that the VSELECT optimizations that expect the correct vector
23748 // boolean value will not be triggered.
23749 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23751 DAG.ReplaceAllUsesOfValueWith(
23753 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23754 Cond, I->getOperand(1), I->getOperand(2)));
23755 DCI.CommitTargetLoweringOpt(TLO);
23758 // At this point, only Cond is changed. Change the condition
23759 // just for N to keep the opportunity to optimize all other
23760 // users their own way.
23761 DAG.ReplaceAllUsesOfValueWith(
23763 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23764 TLO.New, N->getOperand(1), N->getOperand(2)));
23772 // Check whether a boolean test is testing a boolean value generated by
23773 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23776 // Simplify the following patterns:
23777 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23778 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23779 // to (Op EFLAGS Cond)
23781 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23782 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23783 // to (Op EFLAGS !Cond)
23785 // where Op could be BRCOND or CMOV.
23787 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23788 // Quit if not CMP and SUB with its value result used.
23789 if (Cmp.getOpcode() != X86ISD::CMP &&
23790 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23793 // Quit if not used as a boolean value.
23794 if (CC != X86::COND_E && CC != X86::COND_NE)
23797 // Check CMP operands. One of them should be 0 or 1 and the other should be
23798 // an SetCC or extended from it.
23799 SDValue Op1 = Cmp.getOperand(0);
23800 SDValue Op2 = Cmp.getOperand(1);
23803 const ConstantSDNode* C = nullptr;
23804 bool needOppositeCond = (CC == X86::COND_E);
23805 bool checkAgainstTrue = false; // Is it a comparison against 1?
23807 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23809 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23811 else // Quit if all operands are not constants.
23814 if (C->getZExtValue() == 1) {
23815 needOppositeCond = !needOppositeCond;
23816 checkAgainstTrue = true;
23817 } else if (C->getZExtValue() != 0)
23818 // Quit if the constant is neither 0 or 1.
23821 bool truncatedToBoolWithAnd = false;
23822 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23823 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23824 SetCC.getOpcode() == ISD::TRUNCATE ||
23825 SetCC.getOpcode() == ISD::AND) {
23826 if (SetCC.getOpcode() == ISD::AND) {
23828 ConstantSDNode *CS;
23829 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23830 CS->getZExtValue() == 1)
23832 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23833 CS->getZExtValue() == 1)
23837 SetCC = SetCC.getOperand(OpIdx);
23838 truncatedToBoolWithAnd = true;
23840 SetCC = SetCC.getOperand(0);
23843 switch (SetCC.getOpcode()) {
23844 case X86ISD::SETCC_CARRY:
23845 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23846 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23847 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23848 // truncated to i1 using 'and'.
23849 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23851 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23852 "Invalid use of SETCC_CARRY!");
23854 case X86ISD::SETCC:
23855 // Set the condition code or opposite one if necessary.
23856 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23857 if (needOppositeCond)
23858 CC = X86::GetOppositeBranchCondition(CC);
23859 return SetCC.getOperand(1);
23860 case X86ISD::CMOV: {
23861 // Check whether false/true value has canonical one, i.e. 0 or 1.
23862 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23863 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23864 // Quit if true value is not a constant.
23867 // Quit if false value is not a constant.
23869 SDValue Op = SetCC.getOperand(0);
23870 // Skip 'zext' or 'trunc' node.
23871 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23872 Op.getOpcode() == ISD::TRUNCATE)
23873 Op = Op.getOperand(0);
23874 // A special case for rdrand/rdseed, where 0 is set if false cond is
23876 if ((Op.getOpcode() != X86ISD::RDRAND &&
23877 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23880 // Quit if false value is not the constant 0 or 1.
23881 bool FValIsFalse = true;
23882 if (FVal && FVal->getZExtValue() != 0) {
23883 if (FVal->getZExtValue() != 1)
23885 // If FVal is 1, opposite cond is needed.
23886 needOppositeCond = !needOppositeCond;
23887 FValIsFalse = false;
23889 // Quit if TVal is not the constant opposite of FVal.
23890 if (FValIsFalse && TVal->getZExtValue() != 1)
23892 if (!FValIsFalse && TVal->getZExtValue() != 0)
23894 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23895 if (needOppositeCond)
23896 CC = X86::GetOppositeBranchCondition(CC);
23897 return SetCC.getOperand(3);
23904 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23906 /// (X86or (X86setcc) (X86setcc))
23907 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23908 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23909 X86::CondCode &CC1, SDValue &Flags,
23911 if (Cond->getOpcode() == X86ISD::CMP) {
23912 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23913 if (!CondOp1C || !CondOp1C->isNullValue())
23916 Cond = Cond->getOperand(0);
23921 SDValue SetCC0, SetCC1;
23922 switch (Cond->getOpcode()) {
23923 default: return false;
23930 SetCC0 = Cond->getOperand(0);
23931 SetCC1 = Cond->getOperand(1);
23935 // Make sure we have SETCC nodes, using the same flags value.
23936 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23937 SetCC1.getOpcode() != X86ISD::SETCC ||
23938 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23941 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23942 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23943 Flags = SetCC0->getOperand(1);
23947 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23948 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23949 TargetLowering::DAGCombinerInfo &DCI,
23950 const X86Subtarget *Subtarget) {
23953 // If the flag operand isn't dead, don't touch this CMOV.
23954 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23957 SDValue FalseOp = N->getOperand(0);
23958 SDValue TrueOp = N->getOperand(1);
23959 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23960 SDValue Cond = N->getOperand(3);
23962 if (CC == X86::COND_E || CC == X86::COND_NE) {
23963 switch (Cond.getOpcode()) {
23967 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23968 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23969 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23975 Flags = checkBoolTestSetCCCombine(Cond, CC);
23976 if (Flags.getNode() &&
23977 // Extra check as FCMOV only supports a subset of X86 cond.
23978 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23979 SDValue Ops[] = { FalseOp, TrueOp,
23980 DAG.getConstant(CC, DL, MVT::i8), Flags };
23981 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23984 // If this is a select between two integer constants, try to do some
23985 // optimizations. Note that the operands are ordered the opposite of SELECT
23987 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23988 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23989 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23990 // larger than FalseC (the false value).
23991 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23992 CC = X86::GetOppositeBranchCondition(CC);
23993 std::swap(TrueC, FalseC);
23994 std::swap(TrueOp, FalseOp);
23997 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23998 // This is efficient for any integer data type (including i8/i16) and
24000 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24001 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24002 DAG.getConstant(CC, DL, MVT::i8), Cond);
24004 // Zero extend the condition if needed.
24005 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24007 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24008 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24009 DAG.getConstant(ShAmt, DL, MVT::i8));
24010 if (N->getNumValues() == 2) // Dead flag value?
24011 return DCI.CombineTo(N, Cond, SDValue());
24015 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
24016 // for any integer data type, including i8/i16.
24017 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24018 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24019 DAG.getConstant(CC, DL, MVT::i8), Cond);
24021 // Zero extend the condition if needed.
24022 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24023 FalseC->getValueType(0), Cond);
24024 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24025 SDValue(FalseC, 0));
24027 if (N->getNumValues() == 2) // Dead flag value?
24028 return DCI.CombineTo(N, Cond, SDValue());
24032 // Optimize cases that will turn into an LEA instruction. This requires
24033 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24034 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24035 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24036 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24038 bool isFastMultiplier = false;
24040 switch ((unsigned char)Diff) {
24042 case 1: // result = add base, cond
24043 case 2: // result = lea base( , cond*2)
24044 case 3: // result = lea base(cond, cond*2)
24045 case 4: // result = lea base( , cond*4)
24046 case 5: // result = lea base(cond, cond*4)
24047 case 8: // result = lea base( , cond*8)
24048 case 9: // result = lea base(cond, cond*8)
24049 isFastMultiplier = true;
24054 if (isFastMultiplier) {
24055 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24056 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24057 DAG.getConstant(CC, DL, MVT::i8), Cond);
24058 // Zero extend the condition if needed.
24059 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24061 // Scale the condition by the difference.
24063 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24064 DAG.getConstant(Diff, DL, Cond.getValueType()));
24066 // Add the base if non-zero.
24067 if (FalseC->getAPIntValue() != 0)
24068 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24069 SDValue(FalseC, 0));
24070 if (N->getNumValues() == 2) // Dead flag value?
24071 return DCI.CombineTo(N, Cond, SDValue());
24078 // Handle these cases:
24079 // (select (x != c), e, c) -> select (x != c), e, x),
24080 // (select (x == c), c, e) -> select (x == c), x, e)
24081 // where the c is an integer constant, and the "select" is the combination
24082 // of CMOV and CMP.
24084 // The rationale for this change is that the conditional-move from a constant
24085 // needs two instructions, however, conditional-move from a register needs
24086 // only one instruction.
24088 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24089 // some instruction-combining opportunities. This opt needs to be
24090 // postponed as late as possible.
24092 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24093 // the DCI.xxxx conditions are provided to postpone the optimization as
24094 // late as possible.
24096 ConstantSDNode *CmpAgainst = nullptr;
24097 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24098 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24099 !isa<ConstantSDNode>(Cond.getOperand(0))) {
24101 if (CC == X86::COND_NE &&
24102 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24103 CC = X86::GetOppositeBranchCondition(CC);
24104 std::swap(TrueOp, FalseOp);
24107 if (CC == X86::COND_E &&
24108 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24109 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24110 DAG.getConstant(CC, DL, MVT::i8), Cond };
24111 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24116 // Fold and/or of setcc's to double CMOV:
24117 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24118 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24120 // This combine lets us generate:
24121 // cmovcc1 (jcc1 if we don't have CMOV)
24127 // cmovne (jne if we don't have CMOV)
24128 // When we can't use the CMOV instruction, it might increase branch
24130 // When we can use CMOV, or when there is no mispredict, this improves
24131 // throughput and reduces register pressure.
24133 if (CC == X86::COND_NE) {
24135 X86::CondCode CC0, CC1;
24137 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24139 std::swap(FalseOp, TrueOp);
24140 CC0 = X86::GetOppositeBranchCondition(CC0);
24141 CC1 = X86::GetOppositeBranchCondition(CC1);
24144 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24146 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24147 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24148 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24149 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24157 /// PerformMulCombine - Optimize a single multiply with constant into two
24158 /// in order to implement it with two cheaper instructions, e.g.
24159 /// LEA + SHL, LEA + LEA.
24160 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24161 TargetLowering::DAGCombinerInfo &DCI) {
24162 // An imul is usually smaller than the alternative sequence.
24163 if (DAG.getMachineFunction().getFunction()->optForMinSize())
24166 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24169 EVT VT = N->getValueType(0);
24170 if (VT != MVT::i64 && VT != MVT::i32)
24173 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24176 uint64_t MulAmt = C->getZExtValue();
24177 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24180 uint64_t MulAmt1 = 0;
24181 uint64_t MulAmt2 = 0;
24182 if ((MulAmt % 9) == 0) {
24184 MulAmt2 = MulAmt / 9;
24185 } else if ((MulAmt % 5) == 0) {
24187 MulAmt2 = MulAmt / 5;
24188 } else if ((MulAmt % 3) == 0) {
24190 MulAmt2 = MulAmt / 3;
24193 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24196 if (isPowerOf2_64(MulAmt2) &&
24197 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24198 // If second multiplifer is pow2, issue it first. We want the multiply by
24199 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24201 std::swap(MulAmt1, MulAmt2);
24204 if (isPowerOf2_64(MulAmt1))
24205 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24206 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24208 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24209 DAG.getConstant(MulAmt1, DL, VT));
24211 if (isPowerOf2_64(MulAmt2))
24212 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24213 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24215 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24216 DAG.getConstant(MulAmt2, DL, VT));
24218 // Do not add new nodes to DAG combiner worklist.
24219 DCI.CombineTo(N, NewMul, false);
24224 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24225 SDValue N0 = N->getOperand(0);
24226 SDValue N1 = N->getOperand(1);
24227 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24228 EVT VT = N0.getValueType();
24230 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24231 // since the result of setcc_c is all zero's or all ones.
24232 if (VT.isInteger() && !VT.isVector() &&
24233 N1C && N0.getOpcode() == ISD::AND &&
24234 N0.getOperand(1).getOpcode() == ISD::Constant) {
24235 SDValue N00 = N0.getOperand(0);
24236 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24237 APInt ShAmt = N1C->getAPIntValue();
24238 Mask = Mask.shl(ShAmt);
24239 bool MaskOK = false;
24240 // We can handle cases concerning bit-widening nodes containing setcc_c if
24241 // we carefully interrogate the mask to make sure we are semantics
24243 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24244 // of the underlying setcc_c operation if the setcc_c was zero extended.
24245 // Consider the following example:
24246 // zext(setcc_c) -> i32 0x0000FFFF
24247 // c1 -> i32 0x0000FFFF
24248 // c2 -> i32 0x00000001
24249 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24250 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
24251 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24253 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24254 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24256 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24257 N00.getOpcode() == ISD::ANY_EXTEND) &&
24258 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24259 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24261 if (MaskOK && Mask != 0) {
24263 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24267 // Hardware support for vector shifts is sparse which makes us scalarize the
24268 // vector operations in many cases. Also, on sandybridge ADD is faster than
24270 // (shl V, 1) -> add V,V
24271 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24272 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24273 assert(N0.getValueType().isVector() && "Invalid vector shift type");
24274 // We shift all of the values by one. In many cases we do not have
24275 // hardware support for this operation. This is better expressed as an ADD
24277 if (N1SplatC->getAPIntValue() == 1)
24278 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24284 /// \brief Returns a vector of 0s if the node in input is a vector logical
24285 /// shift by a constant amount which is known to be bigger than or equal
24286 /// to the vector element size in bits.
24287 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24288 const X86Subtarget *Subtarget) {
24289 EVT VT = N->getValueType(0);
24291 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24292 (!Subtarget->hasInt256() ||
24293 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24296 SDValue Amt = N->getOperand(1);
24298 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24299 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24300 APInt ShiftAmt = AmtSplat->getAPIntValue();
24301 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24303 // SSE2/AVX2 logical shifts always return a vector of 0s
24304 // if the shift amount is bigger than or equal to
24305 // the element size. The constant shift amount will be
24306 // encoded as a 8-bit immediate.
24307 if (ShiftAmt.trunc(8).uge(MaxAmount))
24308 return getZeroVector(VT, Subtarget, DAG, DL);
24314 /// PerformShiftCombine - Combine shifts.
24315 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24316 TargetLowering::DAGCombinerInfo &DCI,
24317 const X86Subtarget *Subtarget) {
24318 if (N->getOpcode() == ISD::SHL)
24319 if (SDValue V = PerformSHLCombine(N, DAG))
24322 // Try to fold this logical shift into a zero vector.
24323 if (N->getOpcode() != ISD::SRA)
24324 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24330 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
24331 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24332 // and friends. Likewise for OR -> CMPNEQSS.
24333 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24334 TargetLowering::DAGCombinerInfo &DCI,
24335 const X86Subtarget *Subtarget) {
24338 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24339 // we're requiring SSE2 for both.
24340 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24341 SDValue N0 = N->getOperand(0);
24342 SDValue N1 = N->getOperand(1);
24343 SDValue CMP0 = N0->getOperand(1);
24344 SDValue CMP1 = N1->getOperand(1);
24347 // The SETCCs should both refer to the same CMP.
24348 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24351 SDValue CMP00 = CMP0->getOperand(0);
24352 SDValue CMP01 = CMP0->getOperand(1);
24353 EVT VT = CMP00.getValueType();
24355 if (VT == MVT::f32 || VT == MVT::f64) {
24356 bool ExpectingFlags = false;
24357 // Check for any users that want flags:
24358 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24359 !ExpectingFlags && UI != UE; ++UI)
24360 switch (UI->getOpcode()) {
24365 ExpectingFlags = true;
24367 case ISD::CopyToReg:
24368 case ISD::SIGN_EXTEND:
24369 case ISD::ZERO_EXTEND:
24370 case ISD::ANY_EXTEND:
24374 if (!ExpectingFlags) {
24375 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24376 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24378 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24379 X86::CondCode tmp = cc0;
24384 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
24385 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24386 // FIXME: need symbolic constants for these magic numbers.
24387 // See X86ATTInstPrinter.cpp:printSSECC().
24388 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24389 if (Subtarget->hasAVX512()) {
24390 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24392 DAG.getConstant(x86cc, DL, MVT::i8));
24393 if (N->getValueType(0) != MVT::i1)
24394 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24398 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24399 CMP00.getValueType(), CMP00, CMP01,
24400 DAG.getConstant(x86cc, DL,
24403 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24404 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24406 if (is64BitFP && !Subtarget->is64Bit()) {
24407 // On a 32-bit target, we cannot bitcast the 64-bit float to a
24408 // 64-bit integer, since that's not a legal type. Since
24409 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24410 // bits, but can do this little dance to extract the lowest 32 bits
24411 // and work with those going forward.
24412 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24414 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24415 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24416 Vector32, DAG.getIntPtrConstant(0, DL));
24420 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24421 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24422 DAG.getConstant(1, DL, IntVT));
24423 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24425 return OneBitOfTruth;
24433 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24434 /// so it can be folded inside ANDNP.
24435 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24436 EVT VT = N->getValueType(0);
24438 // Match direct AllOnes for 128 and 256-bit vectors
24439 if (ISD::isBuildVectorAllOnes(N))
24442 // Look through a bit convert.
24443 if (N->getOpcode() == ISD::BITCAST)
24444 N = N->getOperand(0).getNode();
24446 // Sometimes the operand may come from a insert_subvector building a 256-bit
24448 if (VT.is256BitVector() &&
24449 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24450 SDValue V1 = N->getOperand(0);
24451 SDValue V2 = N->getOperand(1);
24453 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24454 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24455 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24456 ISD::isBuildVectorAllOnes(V2.getNode()))
24463 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24464 // register. In most cases we actually compare or select YMM-sized registers
24465 // and mixing the two types creates horrible code. This method optimizes
24466 // some of the transition sequences.
24467 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24468 TargetLowering::DAGCombinerInfo &DCI,
24469 const X86Subtarget *Subtarget) {
24470 EVT VT = N->getValueType(0);
24471 if (!VT.is256BitVector())
24474 assert((N->getOpcode() == ISD::ANY_EXTEND ||
24475 N->getOpcode() == ISD::ZERO_EXTEND ||
24476 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24478 SDValue Narrow = N->getOperand(0);
24479 EVT NarrowVT = Narrow->getValueType(0);
24480 if (!NarrowVT.is128BitVector())
24483 if (Narrow->getOpcode() != ISD::XOR &&
24484 Narrow->getOpcode() != ISD::AND &&
24485 Narrow->getOpcode() != ISD::OR)
24488 SDValue N0 = Narrow->getOperand(0);
24489 SDValue N1 = Narrow->getOperand(1);
24492 // The Left side has to be a trunc.
24493 if (N0.getOpcode() != ISD::TRUNCATE)
24496 // The type of the truncated inputs.
24497 EVT WideVT = N0->getOperand(0)->getValueType(0);
24501 // The right side has to be a 'trunc' or a constant vector.
24502 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24503 ConstantSDNode *RHSConstSplat = nullptr;
24504 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24505 RHSConstSplat = RHSBV->getConstantSplatNode();
24506 if (!RHSTrunc && !RHSConstSplat)
24509 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24511 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24514 // Set N0 and N1 to hold the inputs to the new wide operation.
24515 N0 = N0->getOperand(0);
24516 if (RHSConstSplat) {
24517 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24518 SDValue(RHSConstSplat, 0));
24519 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24520 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24521 } else if (RHSTrunc) {
24522 N1 = N1->getOperand(0);
24525 // Generate the wide operation.
24526 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24527 unsigned Opcode = N->getOpcode();
24529 case ISD::ANY_EXTEND:
24531 case ISD::ZERO_EXTEND: {
24532 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24533 APInt Mask = APInt::getAllOnesValue(InBits);
24534 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24535 return DAG.getNode(ISD::AND, DL, VT,
24536 Op, DAG.getConstant(Mask, DL, VT));
24538 case ISD::SIGN_EXTEND:
24539 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24540 Op, DAG.getValueType(NarrowVT));
24542 llvm_unreachable("Unexpected opcode");
24546 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24547 TargetLowering::DAGCombinerInfo &DCI,
24548 const X86Subtarget *Subtarget) {
24549 SDValue N0 = N->getOperand(0);
24550 SDValue N1 = N->getOperand(1);
24553 // A vector zext_in_reg may be represented as a shuffle,
24554 // feeding into a bitcast (this represents anyext) feeding into
24555 // an and with a mask.
24556 // We'd like to try to combine that into a shuffle with zero
24557 // plus a bitcast, removing the and.
24558 if (N0.getOpcode() != ISD::BITCAST ||
24559 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24562 // The other side of the AND should be a splat of 2^C, where C
24563 // is the number of bits in the source type.
24564 if (N1.getOpcode() == ISD::BITCAST)
24565 N1 = N1.getOperand(0);
24566 if (N1.getOpcode() != ISD::BUILD_VECTOR)
24568 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24570 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24571 EVT SrcType = Shuffle->getValueType(0);
24573 // We expect a single-source shuffle
24574 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24577 unsigned SrcSize = SrcType.getScalarSizeInBits();
24579 APInt SplatValue, SplatUndef;
24580 unsigned SplatBitSize;
24582 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24583 SplatBitSize, HasAnyUndefs))
24586 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24587 // Make sure the splat matches the mask we expect
24588 if (SplatBitSize > ResSize ||
24589 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24592 // Make sure the input and output size make sense
24593 if (SrcSize >= ResSize || ResSize % SrcSize)
24596 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24597 // The number of u's between each two values depends on the ratio between
24598 // the source and dest type.
24599 unsigned ZextRatio = ResSize / SrcSize;
24600 bool IsZext = true;
24601 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24602 if (i % ZextRatio) {
24603 if (Shuffle->getMaskElt(i) > 0) {
24609 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24610 // Expected element number
24620 // Ok, perform the transformation - replace the shuffle with
24621 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24622 // (instead of undef) where the k elements come from the zero vector.
24623 SmallVector<int, 8> Mask;
24624 unsigned NumElems = SrcType.getVectorNumElements();
24625 for (unsigned i = 0; i < NumElems; ++i)
24627 Mask.push_back(NumElems);
24629 Mask.push_back(i / ZextRatio);
24631 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24632 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24633 return DAG.getBitcast(N0.getValueType(), NewShuffle);
24636 /// If both input operands of a logic op are being cast from floating point
24637 /// types, try to convert this into a floating point logic node to avoid
24638 /// unnecessary moves from SSE to integer registers.
24639 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24640 const X86Subtarget *Subtarget) {
24641 unsigned FPOpcode = ISD::DELETED_NODE;
24642 if (N->getOpcode() == ISD::AND)
24643 FPOpcode = X86ISD::FAND;
24644 else if (N->getOpcode() == ISD::OR)
24645 FPOpcode = X86ISD::FOR;
24646 else if (N->getOpcode() == ISD::XOR)
24647 FPOpcode = X86ISD::FXOR;
24649 assert(FPOpcode != ISD::DELETED_NODE &&
24650 "Unexpected input node for FP logic conversion");
24652 EVT VT = N->getValueType(0);
24653 SDValue N0 = N->getOperand(0);
24654 SDValue N1 = N->getOperand(1);
24656 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24657 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24658 (Subtarget->hasSSE2() && VT == MVT::i64))) {
24659 SDValue N00 = N0.getOperand(0);
24660 SDValue N10 = N1.getOperand(0);
24661 EVT N00Type = N00.getValueType();
24662 EVT N10Type = N10.getValueType();
24663 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24664 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24665 return DAG.getBitcast(VT, FPLogic);
24671 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24672 TargetLowering::DAGCombinerInfo &DCI,
24673 const X86Subtarget *Subtarget) {
24674 if (DCI.isBeforeLegalizeOps())
24677 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24680 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24683 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24686 EVT VT = N->getValueType(0);
24687 SDValue N0 = N->getOperand(0);
24688 SDValue N1 = N->getOperand(1);
24691 // Create BEXTR instructions
24692 // BEXTR is ((X >> imm) & (2**size-1))
24693 if (VT == MVT::i32 || VT == MVT::i64) {
24694 // Check for BEXTR.
24695 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24696 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24697 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24698 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24699 if (MaskNode && ShiftNode) {
24700 uint64_t Mask = MaskNode->getZExtValue();
24701 uint64_t Shift = ShiftNode->getZExtValue();
24702 if (isMask_64(Mask)) {
24703 uint64_t MaskSize = countPopulation(Mask);
24704 if (Shift + MaskSize <= VT.getSizeInBits())
24705 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24706 DAG.getConstant(Shift | (MaskSize << 8), DL,
24715 // Want to form ANDNP nodes:
24716 // 1) In the hopes of then easily combining them with OR and AND nodes
24717 // to form PBLEND/PSIGN.
24718 // 2) To match ANDN packed intrinsics
24719 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24722 // Check LHS for vnot
24723 if (N0.getOpcode() == ISD::XOR &&
24724 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24725 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24726 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24728 // Check RHS for vnot
24729 if (N1.getOpcode() == ISD::XOR &&
24730 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24731 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24732 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24737 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24738 TargetLowering::DAGCombinerInfo &DCI,
24739 const X86Subtarget *Subtarget) {
24740 if (DCI.isBeforeLegalizeOps())
24743 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24746 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24749 SDValue N0 = N->getOperand(0);
24750 SDValue N1 = N->getOperand(1);
24751 EVT VT = N->getValueType(0);
24753 // look for psign/blend
24754 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24755 if (!Subtarget->hasSSSE3() ||
24756 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24759 // Canonicalize pandn to RHS
24760 if (N0.getOpcode() == X86ISD::ANDNP)
24762 // or (and (m, y), (pandn m, x))
24763 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24764 SDValue Mask = N1.getOperand(0);
24765 SDValue X = N1.getOperand(1);
24767 if (N0.getOperand(0) == Mask)
24768 Y = N0.getOperand(1);
24769 if (N0.getOperand(1) == Mask)
24770 Y = N0.getOperand(0);
24772 // Check to see if the mask appeared in both the AND and ANDNP and
24776 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24777 // Look through mask bitcast.
24778 if (Mask.getOpcode() == ISD::BITCAST)
24779 Mask = Mask.getOperand(0);
24780 if (X.getOpcode() == ISD::BITCAST)
24781 X = X.getOperand(0);
24782 if (Y.getOpcode() == ISD::BITCAST)
24783 Y = Y.getOperand(0);
24785 EVT MaskVT = Mask.getValueType();
24787 // Validate that the Mask operand is a vector sra node.
24788 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24789 // there is no psrai.b
24790 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24791 unsigned SraAmt = ~0;
24792 if (Mask.getOpcode() == ISD::SRA) {
24793 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24794 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24795 SraAmt = AmtConst->getZExtValue();
24796 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24797 SDValue SraC = Mask.getOperand(1);
24798 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24800 if ((SraAmt + 1) != EltBits)
24805 // Now we know we at least have a plendvb with the mask val. See if
24806 // we can form a psignb/w/d.
24807 // psign = x.type == y.type == mask.type && y = sub(0, x);
24808 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24809 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24810 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24811 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24812 "Unsupported VT for PSIGN");
24813 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24814 return DAG.getBitcast(VT, Mask);
24816 // PBLENDVB only available on SSE 4.1
24817 if (!Subtarget->hasSSE41())
24820 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24822 X = DAG.getBitcast(BlendVT, X);
24823 Y = DAG.getBitcast(BlendVT, Y);
24824 Mask = DAG.getBitcast(BlendVT, Mask);
24825 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24826 return DAG.getBitcast(VT, Mask);
24830 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24833 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24834 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24836 // SHLD/SHRD instructions have lower register pressure, but on some
24837 // platforms they have higher latency than the equivalent
24838 // series of shifts/or that would otherwise be generated.
24839 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24840 // have higher latencies and we are not optimizing for size.
24841 if (!OptForSize && Subtarget->isSHLDSlow())
24844 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24846 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24848 if (!N0.hasOneUse() || !N1.hasOneUse())
24851 SDValue ShAmt0 = N0.getOperand(1);
24852 if (ShAmt0.getValueType() != MVT::i8)
24854 SDValue ShAmt1 = N1.getOperand(1);
24855 if (ShAmt1.getValueType() != MVT::i8)
24857 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24858 ShAmt0 = ShAmt0.getOperand(0);
24859 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24860 ShAmt1 = ShAmt1.getOperand(0);
24863 unsigned Opc = X86ISD::SHLD;
24864 SDValue Op0 = N0.getOperand(0);
24865 SDValue Op1 = N1.getOperand(0);
24866 if (ShAmt0.getOpcode() == ISD::SUB) {
24867 Opc = X86ISD::SHRD;
24868 std::swap(Op0, Op1);
24869 std::swap(ShAmt0, ShAmt1);
24872 unsigned Bits = VT.getSizeInBits();
24873 if (ShAmt1.getOpcode() == ISD::SUB) {
24874 SDValue Sum = ShAmt1.getOperand(0);
24875 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24876 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24877 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24878 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24879 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24880 return DAG.getNode(Opc, DL, VT,
24882 DAG.getNode(ISD::TRUNCATE, DL,
24885 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24886 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24888 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24889 return DAG.getNode(Opc, DL, VT,
24890 N0.getOperand(0), N1.getOperand(0),
24891 DAG.getNode(ISD::TRUNCATE, DL,
24898 // Generate NEG and CMOV for integer abs.
24899 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24900 EVT VT = N->getValueType(0);
24902 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24903 // 8-bit integer abs to NEG and CMOV.
24904 if (VT.isInteger() && VT.getSizeInBits() == 8)
24907 SDValue N0 = N->getOperand(0);
24908 SDValue N1 = N->getOperand(1);
24911 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24912 // and change it to SUB and CMOV.
24913 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24914 N0.getOpcode() == ISD::ADD &&
24915 N0.getOperand(1) == N1 &&
24916 N1.getOpcode() == ISD::SRA &&
24917 N1.getOperand(0) == N0.getOperand(0))
24918 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24919 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24920 // Generate SUB & CMOV.
24921 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24922 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24924 SDValue Ops[] = { N0.getOperand(0), Neg,
24925 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24926 SDValue(Neg.getNode(), 1) };
24927 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24932 // Try to turn tests against the signbit in the form of:
24933 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24936 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24937 // This is only worth doing if the output type is i8.
24938 if (N->getValueType(0) != MVT::i8)
24941 SDValue N0 = N->getOperand(0);
24942 SDValue N1 = N->getOperand(1);
24944 // We should be performing an xor against a truncated shift.
24945 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24948 // Make sure we are performing an xor against one.
24949 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24952 // SetCC on x86 zero extends so only act on this if it's a logical shift.
24953 SDValue Shift = N0.getOperand(0);
24954 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24957 // Make sure we are truncating from one of i16, i32 or i64.
24958 EVT ShiftTy = Shift.getValueType();
24959 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24962 // Make sure the shift amount extracts the sign bit.
24963 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24964 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24967 // Create a greater-than comparison against -1.
24968 // N.B. Using SETGE against 0 works but we want a canonical looking
24969 // comparison, using SETGT matches up with what TranslateX86CC.
24971 SDValue ShiftOp = Shift.getOperand(0);
24972 EVT ShiftOpTy = ShiftOp.getValueType();
24973 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24974 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24978 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24979 TargetLowering::DAGCombinerInfo &DCI,
24980 const X86Subtarget *Subtarget) {
24981 if (DCI.isBeforeLegalizeOps())
24984 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24987 if (Subtarget->hasCMov())
24988 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24991 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24997 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24998 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24999 TargetLowering::DAGCombinerInfo &DCI,
25000 const X86Subtarget *Subtarget) {
25001 LoadSDNode *Ld = cast<LoadSDNode>(N);
25002 EVT RegVT = Ld->getValueType(0);
25003 EVT MemVT = Ld->getMemoryVT();
25005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25007 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25008 // into two 16-byte operations.
25009 ISD::LoadExtType Ext = Ld->getExtensionType();
25011 unsigned AddressSpace = Ld->getAddressSpace();
25012 unsigned Alignment = Ld->getAlignment();
25013 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25014 Ext == ISD::NON_EXTLOAD &&
25015 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25016 AddressSpace, Alignment, &Fast) && !Fast) {
25017 unsigned NumElems = RegVT.getVectorNumElements();
25021 SDValue Ptr = Ld->getBasePtr();
25022 SDValue Increment =
25023 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25025 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25027 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25028 Ld->getPointerInfo(), Ld->isVolatile(),
25029 Ld->isNonTemporal(), Ld->isInvariant(),
25031 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25032 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25033 Ld->getPointerInfo(), Ld->isVolatile(),
25034 Ld->isNonTemporal(), Ld->isInvariant(),
25035 std::min(16U, Alignment));
25036 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25038 Load2.getValue(1));
25040 SDValue NewVec = DAG.getUNDEF(RegVT);
25041 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25042 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25043 return DCI.CombineTo(N, NewVec, TF, true);
25049 /// PerformMLOADCombine - Resolve extending loads
25050 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25051 TargetLowering::DAGCombinerInfo &DCI,
25052 const X86Subtarget *Subtarget) {
25053 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25054 if (Mld->getExtensionType() != ISD::SEXTLOAD)
25057 EVT VT = Mld->getValueType(0);
25058 unsigned NumElems = VT.getVectorNumElements();
25059 EVT LdVT = Mld->getMemoryVT();
25062 assert(LdVT != VT && "Cannot extend to the same type");
25063 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25064 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25065 // From, To sizes and ElemCount must be pow of two
25066 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25067 "Unexpected size for extending masked load");
25069 unsigned SizeRatio = ToSz / FromSz;
25070 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25072 // Create a type on which we perform the shuffle
25073 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25074 LdVT.getScalarType(), NumElems*SizeRatio);
25075 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25077 // Convert Src0 value
25078 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25079 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25080 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25081 for (unsigned i = 0; i != NumElems; ++i)
25082 ShuffleVec[i] = i * SizeRatio;
25084 // Can't shuffle using an illegal type.
25085 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25086 "WideVecVT should be legal");
25087 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25088 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25090 // Prepare the new mask
25092 SDValue Mask = Mld->getMask();
25093 if (Mask.getValueType() == VT) {
25094 // Mask and original value have the same type
25095 NewMask = DAG.getBitcast(WideVecVT, Mask);
25096 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25097 for (unsigned i = 0; i != NumElems; ++i)
25098 ShuffleVec[i] = i * SizeRatio;
25099 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25100 ShuffleVec[i] = NumElems*SizeRatio;
25101 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25102 DAG.getConstant(0, dl, WideVecVT),
25106 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25107 unsigned WidenNumElts = NumElems*SizeRatio;
25108 unsigned MaskNumElts = VT.getVectorNumElements();
25109 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
25112 unsigned NumConcat = WidenNumElts / MaskNumElts;
25113 SmallVector<SDValue, 16> Ops(NumConcat);
25114 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25116 for (unsigned i = 1; i != NumConcat; ++i)
25119 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25122 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25123 Mld->getBasePtr(), NewMask, WideSrc0,
25124 Mld->getMemoryVT(), Mld->getMemOperand(),
25126 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25127 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25129 /// PerformMSTORECombine - Resolve truncating stores
25130 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25131 const X86Subtarget *Subtarget) {
25132 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25133 if (!Mst->isTruncatingStore())
25136 EVT VT = Mst->getValue().getValueType();
25137 unsigned NumElems = VT.getVectorNumElements();
25138 EVT StVT = Mst->getMemoryVT();
25141 assert(StVT != VT && "Cannot truncate to the same type");
25142 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25143 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25145 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25147 // The truncating store is legal in some cases. For example
25148 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25149 // are designated for truncate store.
25150 // In this case we don't need any further transformations.
25151 if (TLI.isTruncStoreLegal(VT, StVT))
25154 // From, To sizes and ElemCount must be pow of two
25155 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25156 "Unexpected size for truncating masked store");
25157 // We are going to use the original vector elt for storing.
25158 // Accumulated smaller vector elements must be a multiple of the store size.
25159 assert (((NumElems * FromSz) % ToSz) == 0 &&
25160 "Unexpected ratio for truncating masked store");
25162 unsigned SizeRatio = FromSz / ToSz;
25163 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25165 // Create a type on which we perform the shuffle
25166 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25167 StVT.getScalarType(), NumElems*SizeRatio);
25169 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25171 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25172 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25173 for (unsigned i = 0; i != NumElems; ++i)
25174 ShuffleVec[i] = i * SizeRatio;
25176 // Can't shuffle using an illegal type.
25177 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25178 "WideVecVT should be legal");
25180 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25181 DAG.getUNDEF(WideVecVT),
25185 SDValue Mask = Mst->getMask();
25186 if (Mask.getValueType() == VT) {
25187 // Mask and original value have the same type
25188 NewMask = DAG.getBitcast(WideVecVT, Mask);
25189 for (unsigned i = 0; i != NumElems; ++i)
25190 ShuffleVec[i] = i * SizeRatio;
25191 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25192 ShuffleVec[i] = NumElems*SizeRatio;
25193 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25194 DAG.getConstant(0, dl, WideVecVT),
25198 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25199 unsigned WidenNumElts = NumElems*SizeRatio;
25200 unsigned MaskNumElts = VT.getVectorNumElements();
25201 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
25204 unsigned NumConcat = WidenNumElts / MaskNumElts;
25205 SmallVector<SDValue, 16> Ops(NumConcat);
25206 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25208 for (unsigned i = 1; i != NumConcat; ++i)
25211 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25214 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25215 NewMask, StVT, Mst->getMemOperand(), false);
25217 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25218 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25219 const X86Subtarget *Subtarget) {
25220 StoreSDNode *St = cast<StoreSDNode>(N);
25221 EVT VT = St->getValue().getValueType();
25222 EVT StVT = St->getMemoryVT();
25224 SDValue StoredVal = St->getOperand(1);
25225 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25227 // If we are saving a concatenation of two XMM registers and 32-byte stores
25228 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25230 unsigned AddressSpace = St->getAddressSpace();
25231 unsigned Alignment = St->getAlignment();
25232 if (VT.is256BitVector() && StVT == VT &&
25233 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25234 AddressSpace, Alignment, &Fast) && !Fast) {
25235 unsigned NumElems = VT.getVectorNumElements();
25239 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25240 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25243 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25244 SDValue Ptr0 = St->getBasePtr();
25245 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25247 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25248 St->getPointerInfo(), St->isVolatile(),
25249 St->isNonTemporal(), Alignment);
25250 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25251 St->getPointerInfo(), St->isVolatile(),
25252 St->isNonTemporal(),
25253 std::min(16U, Alignment));
25254 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25257 // Optimize trunc store (of multiple scalars) to shuffle and store.
25258 // First, pack all of the elements in one place. Next, store to memory
25259 // in fewer chunks.
25260 if (St->isTruncatingStore() && VT.isVector()) {
25261 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25262 unsigned NumElems = VT.getVectorNumElements();
25263 assert(StVT != VT && "Cannot truncate to the same type");
25264 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25265 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25267 // The truncating store is legal in some cases. For example
25268 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25269 // are designated for truncate store.
25270 // In this case we don't need any further transformations.
25271 if (TLI.isTruncStoreLegal(VT, StVT))
25274 // From, To sizes and ElemCount must be pow of two
25275 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25276 // We are going to use the original vector elt for storing.
25277 // Accumulated smaller vector elements must be a multiple of the store size.
25278 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25280 unsigned SizeRatio = FromSz / ToSz;
25282 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25284 // Create a type on which we perform the shuffle
25285 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25286 StVT.getScalarType(), NumElems*SizeRatio);
25288 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25290 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25291 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25292 for (unsigned i = 0; i != NumElems; ++i)
25293 ShuffleVec[i] = i * SizeRatio;
25295 // Can't shuffle using an illegal type.
25296 if (!TLI.isTypeLegal(WideVecVT))
25299 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25300 DAG.getUNDEF(WideVecVT),
25302 // At this point all of the data is stored at the bottom of the
25303 // register. We now need to save it to mem.
25305 // Find the largest store unit
25306 MVT StoreType = MVT::i8;
25307 for (MVT Tp : MVT::integer_valuetypes()) {
25308 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25312 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25313 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25314 (64 <= NumElems * ToSz))
25315 StoreType = MVT::f64;
25317 // Bitcast the original vector into a vector of store-size units
25318 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25319 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25320 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25321 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25322 SmallVector<SDValue, 8> Chains;
25323 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25324 TLI.getPointerTy(DAG.getDataLayout()));
25325 SDValue Ptr = St->getBasePtr();
25327 // Perform one or more big stores into memory.
25328 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25329 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25330 StoreType, ShuffWide,
25331 DAG.getIntPtrConstant(i, dl));
25332 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25333 St->getPointerInfo(), St->isVolatile(),
25334 St->isNonTemporal(), St->getAlignment());
25335 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25336 Chains.push_back(Ch);
25339 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25342 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
25343 // the FP state in cases where an emms may be missing.
25344 // A preferable solution to the general problem is to figure out the right
25345 // places to insert EMMS. This qualifies as a quick hack.
25347 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25348 if (VT.getSizeInBits() != 64)
25351 const Function *F = DAG.getMachineFunction().getFunction();
25352 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25354 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25355 if ((VT.isVector() ||
25356 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25357 isa<LoadSDNode>(St->getValue()) &&
25358 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25359 St->getChain().hasOneUse() && !St->isVolatile()) {
25360 SDNode* LdVal = St->getValue().getNode();
25361 LoadSDNode *Ld = nullptr;
25362 int TokenFactorIndex = -1;
25363 SmallVector<SDValue, 8> Ops;
25364 SDNode* ChainVal = St->getChain().getNode();
25365 // Must be a store of a load. We currently handle two cases: the load
25366 // is a direct child, and it's under an intervening TokenFactor. It is
25367 // possible to dig deeper under nested TokenFactors.
25368 if (ChainVal == LdVal)
25369 Ld = cast<LoadSDNode>(St->getChain());
25370 else if (St->getValue().hasOneUse() &&
25371 ChainVal->getOpcode() == ISD::TokenFactor) {
25372 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25373 if (ChainVal->getOperand(i).getNode() == LdVal) {
25374 TokenFactorIndex = i;
25375 Ld = cast<LoadSDNode>(St->getValue());
25377 Ops.push_back(ChainVal->getOperand(i));
25381 if (!Ld || !ISD::isNormalLoad(Ld))
25384 // If this is not the MMX case, i.e. we are just turning i64 load/store
25385 // into f64 load/store, avoid the transformation if there are multiple
25386 // uses of the loaded value.
25387 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25392 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25393 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25395 if (Subtarget->is64Bit() || F64IsLegal) {
25396 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25397 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25398 Ld->getPointerInfo(), Ld->isVolatile(),
25399 Ld->isNonTemporal(), Ld->isInvariant(),
25400 Ld->getAlignment());
25401 SDValue NewChain = NewLd.getValue(1);
25402 if (TokenFactorIndex != -1) {
25403 Ops.push_back(NewChain);
25404 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25406 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25407 St->getPointerInfo(),
25408 St->isVolatile(), St->isNonTemporal(),
25409 St->getAlignment());
25412 // Otherwise, lower to two pairs of 32-bit loads / stores.
25413 SDValue LoAddr = Ld->getBasePtr();
25414 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25415 DAG.getConstant(4, LdDL, MVT::i32));
25417 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25418 Ld->getPointerInfo(),
25419 Ld->isVolatile(), Ld->isNonTemporal(),
25420 Ld->isInvariant(), Ld->getAlignment());
25421 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25422 Ld->getPointerInfo().getWithOffset(4),
25423 Ld->isVolatile(), Ld->isNonTemporal(),
25425 MinAlign(Ld->getAlignment(), 4));
25427 SDValue NewChain = LoLd.getValue(1);
25428 if (TokenFactorIndex != -1) {
25429 Ops.push_back(LoLd);
25430 Ops.push_back(HiLd);
25431 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25434 LoAddr = St->getBasePtr();
25435 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25436 DAG.getConstant(4, StDL, MVT::i32));
25438 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25439 St->getPointerInfo(),
25440 St->isVolatile(), St->isNonTemporal(),
25441 St->getAlignment());
25442 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25443 St->getPointerInfo().getWithOffset(4),
25445 St->isNonTemporal(),
25446 MinAlign(St->getAlignment(), 4));
25447 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25450 // This is similar to the above case, but here we handle a scalar 64-bit
25451 // integer store that is extracted from a vector on a 32-bit target.
25452 // If we have SSE2, then we can treat it like a floating-point double
25453 // to get past legalization. The execution dependencies fixup pass will
25454 // choose the optimal machine instruction for the store if this really is
25455 // an integer or v2f32 rather than an f64.
25456 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25457 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25458 SDValue OldExtract = St->getOperand(1);
25459 SDValue ExtOp0 = OldExtract.getOperand(0);
25460 unsigned VecSize = ExtOp0.getValueSizeInBits();
25461 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25462 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25463 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25464 BitCast, OldExtract.getOperand(1));
25465 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25466 St->getPointerInfo(), St->isVolatile(),
25467 St->isNonTemporal(), St->getAlignment());
25473 /// Return 'true' if this vector operation is "horizontal"
25474 /// and return the operands for the horizontal operation in LHS and RHS. A
25475 /// horizontal operation performs the binary operation on successive elements
25476 /// of its first operand, then on successive elements of its second operand,
25477 /// returning the resulting values in a vector. For example, if
25478 /// A = < float a0, float a1, float a2, float a3 >
25480 /// B = < float b0, float b1, float b2, float b3 >
25481 /// then the result of doing a horizontal operation on A and B is
25482 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25483 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25484 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25485 /// set to A, RHS to B, and the routine returns 'true'.
25486 /// Note that the binary operation should have the property that if one of the
25487 /// operands is UNDEF then the result is UNDEF.
25488 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25489 // Look for the following pattern: if
25490 // A = < float a0, float a1, float a2, float a3 >
25491 // B = < float b0, float b1, float b2, float b3 >
25493 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25494 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25495 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25496 // which is A horizontal-op B.
25498 // At least one of the operands should be a vector shuffle.
25499 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25500 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25503 MVT VT = LHS.getSimpleValueType();
25505 assert((VT.is128BitVector() || VT.is256BitVector()) &&
25506 "Unsupported vector type for horizontal add/sub");
25508 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25509 // operate independently on 128-bit lanes.
25510 unsigned NumElts = VT.getVectorNumElements();
25511 unsigned NumLanes = VT.getSizeInBits()/128;
25512 unsigned NumLaneElts = NumElts / NumLanes;
25513 assert((NumLaneElts % 2 == 0) &&
25514 "Vector type should have an even number of elements in each lane");
25515 unsigned HalfLaneElts = NumLaneElts/2;
25517 // View LHS in the form
25518 // LHS = VECTOR_SHUFFLE A, B, LMask
25519 // If LHS is not a shuffle then pretend it is the shuffle
25520 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25521 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25524 SmallVector<int, 16> LMask(NumElts);
25525 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25526 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25527 A = LHS.getOperand(0);
25528 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25529 B = LHS.getOperand(1);
25530 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25531 std::copy(Mask.begin(), Mask.end(), LMask.begin());
25533 if (LHS.getOpcode() != ISD::UNDEF)
25535 for (unsigned i = 0; i != NumElts; ++i)
25539 // Likewise, view RHS in the form
25540 // RHS = VECTOR_SHUFFLE C, D, RMask
25542 SmallVector<int, 16> RMask(NumElts);
25543 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25544 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25545 C = RHS.getOperand(0);
25546 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25547 D = RHS.getOperand(1);
25548 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25549 std::copy(Mask.begin(), Mask.end(), RMask.begin());
25551 if (RHS.getOpcode() != ISD::UNDEF)
25553 for (unsigned i = 0; i != NumElts; ++i)
25557 // Check that the shuffles are both shuffling the same vectors.
25558 if (!(A == C && B == D) && !(A == D && B == C))
25561 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25562 if (!A.getNode() && !B.getNode())
25565 // If A and B occur in reverse order in RHS, then "swap" them (which means
25566 // rewriting the mask).
25568 ShuffleVectorSDNode::commuteMask(RMask);
25570 // At this point LHS and RHS are equivalent to
25571 // LHS = VECTOR_SHUFFLE A, B, LMask
25572 // RHS = VECTOR_SHUFFLE A, B, RMask
25573 // Check that the masks correspond to performing a horizontal operation.
25574 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25575 for (unsigned i = 0; i != NumLaneElts; ++i) {
25576 int LIdx = LMask[i+l], RIdx = RMask[i+l];
25578 // Ignore any UNDEF components.
25579 if (LIdx < 0 || RIdx < 0 ||
25580 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25581 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25584 // Check that successive elements are being operated on. If not, this is
25585 // not a horizontal operation.
25586 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25587 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25588 if (!(LIdx == Index && RIdx == Index + 1) &&
25589 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25594 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25595 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25599 /// Do target-specific dag combines on floating point adds.
25600 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25601 const X86Subtarget *Subtarget) {
25602 EVT VT = N->getValueType(0);
25603 SDValue LHS = N->getOperand(0);
25604 SDValue RHS = N->getOperand(1);
25606 // Try to synthesize horizontal adds from adds of shuffles.
25607 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25608 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25609 isHorizontalBinOp(LHS, RHS, true))
25610 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25614 /// Do target-specific dag combines on floating point subs.
25615 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25616 const X86Subtarget *Subtarget) {
25617 EVT VT = N->getValueType(0);
25618 SDValue LHS = N->getOperand(0);
25619 SDValue RHS = N->getOperand(1);
25621 // Try to synthesize horizontal subs from subs of shuffles.
25622 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25623 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25624 isHorizontalBinOp(LHS, RHS, false))
25625 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25629 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25630 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25631 const X86Subtarget *Subtarget) {
25632 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25634 // F[X]OR(0.0, x) -> x
25635 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25636 if (C->getValueAPF().isPosZero())
25637 return N->getOperand(1);
25639 // F[X]OR(x, 0.0) -> x
25640 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25641 if (C->getValueAPF().isPosZero())
25642 return N->getOperand(0);
25644 EVT VT = N->getValueType(0);
25645 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25647 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25648 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25650 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25651 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25652 unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25653 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25654 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25659 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25660 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25661 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25663 // Only perform optimizations if UnsafeMath is used.
25664 if (!DAG.getTarget().Options.UnsafeFPMath)
25667 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25668 // into FMINC and FMAXC, which are Commutative operations.
25669 unsigned NewOp = 0;
25670 switch (N->getOpcode()) {
25671 default: llvm_unreachable("unknown opcode");
25672 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
25673 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
25676 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25677 N->getOperand(0), N->getOperand(1));
25680 /// Do target-specific dag combines on X86ISD::FAND nodes.
25681 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25682 // FAND(0.0, x) -> 0.0
25683 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25684 if (C->getValueAPF().isPosZero())
25685 return N->getOperand(0);
25687 // FAND(x, 0.0) -> 0.0
25688 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25689 if (C->getValueAPF().isPosZero())
25690 return N->getOperand(1);
25695 /// Do target-specific dag combines on X86ISD::FANDN nodes
25696 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25697 // FANDN(0.0, x) -> x
25698 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25699 if (C->getValueAPF().isPosZero())
25700 return N->getOperand(1);
25702 // FANDN(x, 0.0) -> 0.0
25703 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25704 if (C->getValueAPF().isPosZero())
25705 return N->getOperand(1);
25710 static SDValue PerformBTCombine(SDNode *N,
25712 TargetLowering::DAGCombinerInfo &DCI) {
25713 // BT ignores high bits in the bit index operand.
25714 SDValue Op1 = N->getOperand(1);
25715 if (Op1.hasOneUse()) {
25716 unsigned BitWidth = Op1.getValueSizeInBits();
25717 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25718 APInt KnownZero, KnownOne;
25719 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25720 !DCI.isBeforeLegalizeOps());
25721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25722 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25723 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25724 DCI.CommitTargetLoweringOpt(TLO);
25729 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25730 SDValue Op = N->getOperand(0);
25731 if (Op.getOpcode() == ISD::BITCAST)
25732 Op = Op.getOperand(0);
25733 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25734 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25735 VT.getVectorElementType().getSizeInBits() ==
25736 OpVT.getVectorElementType().getSizeInBits()) {
25737 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25742 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25743 const X86Subtarget *Subtarget) {
25744 EVT VT = N->getValueType(0);
25745 if (!VT.isVector())
25748 SDValue N0 = N->getOperand(0);
25749 SDValue N1 = N->getOperand(1);
25750 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25753 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25754 // both SSE and AVX2 since there is no sign-extended shift right
25755 // operation on a vector with 64-bit elements.
25756 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25757 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25758 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25759 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25760 SDValue N00 = N0.getOperand(0);
25762 // EXTLOAD has a better solution on AVX2,
25763 // it may be replaced with X86ISD::VSEXT node.
25764 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25765 if (!ISD::isNormalLoad(N00.getNode()))
25768 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25769 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25771 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25777 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25778 TargetLowering::DAGCombinerInfo &DCI,
25779 const X86Subtarget *Subtarget) {
25780 SDValue N0 = N->getOperand(0);
25781 EVT VT = N->getValueType(0);
25782 EVT SVT = VT.getScalarType();
25783 EVT InVT = N0.getValueType();
25784 EVT InSVT = InVT.getScalarType();
25787 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25788 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25789 // This exposes the sext to the sdivrem lowering, so that it directly extends
25790 // from AH (which we otherwise need to do contortions to access).
25791 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25792 InVT == MVT::i8 && VT == MVT::i32) {
25793 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25794 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25795 N0.getOperand(0), N0.getOperand(1));
25796 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25797 return R.getValue(1);
25800 if (!DCI.isBeforeLegalizeOps()) {
25801 if (InVT == MVT::i1) {
25802 SDValue Zero = DAG.getConstant(0, DL, VT);
25804 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25805 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25810 if (VT.isVector() && Subtarget->hasSSE2()) {
25811 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25812 EVT InVT = N.getValueType();
25813 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25814 Size / InVT.getScalarSizeInBits());
25815 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25816 DAG.getUNDEF(InVT));
25818 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25821 // If target-size is less than 128-bits, extend to a type that would extend
25822 // to 128 bits, extend that and extract the original target vector.
25823 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25824 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25825 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25826 unsigned Scale = 128 / VT.getSizeInBits();
25828 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25829 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25830 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25831 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25832 DAG.getIntPtrConstant(0, DL));
25835 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25836 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25837 if (VT.getSizeInBits() == 128 &&
25838 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25839 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25840 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25841 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25844 // On pre-AVX2 targets, split into 128-bit nodes of
25845 // ISD::SIGN_EXTEND_VECTOR_INREG.
25846 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25847 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25848 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25849 unsigned NumVecs = VT.getSizeInBits() / 128;
25850 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25851 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25852 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25854 SmallVector<SDValue, 8> Opnds;
25855 for (unsigned i = 0, Offset = 0; i != NumVecs;
25856 ++i, Offset += NumSubElts) {
25857 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25858 DAG.getIntPtrConstant(Offset, DL));
25859 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25860 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25861 Opnds.push_back(SrcVec);
25863 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25867 if (Subtarget->hasAVX() && VT.isVector() && VT.getSizeInBits() == 256)
25868 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25874 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25875 const X86Subtarget* Subtarget) {
25877 EVT VT = N->getValueType(0);
25879 // Let legalize expand this if it isn't a legal type yet.
25880 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25883 EVT ScalarVT = VT.getScalarType();
25884 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25885 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25886 !Subtarget->hasAVX512()))
25889 SDValue A = N->getOperand(0);
25890 SDValue B = N->getOperand(1);
25891 SDValue C = N->getOperand(2);
25893 bool NegA = (A.getOpcode() == ISD::FNEG);
25894 bool NegB = (B.getOpcode() == ISD::FNEG);
25895 bool NegC = (C.getOpcode() == ISD::FNEG);
25897 // Negative multiplication when NegA xor NegB
25898 bool NegMul = (NegA != NegB);
25900 A = A.getOperand(0);
25902 B = B.getOperand(0);
25904 C = C.getOperand(0);
25908 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25910 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25912 return DAG.getNode(Opcode, dl, VT, A, B, C);
25915 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25916 TargetLowering::DAGCombinerInfo &DCI,
25917 const X86Subtarget *Subtarget) {
25918 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25919 // (and (i32 x86isd::setcc_carry), 1)
25920 // This eliminates the zext. This transformation is necessary because
25921 // ISD::SETCC is always legalized to i8.
25923 SDValue N0 = N->getOperand(0);
25924 EVT VT = N->getValueType(0);
25926 if (N0.getOpcode() == ISD::AND &&
25928 N0.getOperand(0).hasOneUse()) {
25929 SDValue N00 = N0.getOperand(0);
25930 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25931 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25932 if (!C || C->getZExtValue() != 1)
25934 return DAG.getNode(ISD::AND, dl, VT,
25935 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25936 N00.getOperand(0), N00.getOperand(1)),
25937 DAG.getConstant(1, dl, VT));
25941 if (N0.getOpcode() == ISD::TRUNCATE &&
25943 N0.getOperand(0).hasOneUse()) {
25944 SDValue N00 = N0.getOperand(0);
25945 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25946 return DAG.getNode(ISD::AND, dl, VT,
25947 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25948 N00.getOperand(0), N00.getOperand(1)),
25949 DAG.getConstant(1, dl, VT));
25953 if (VT.is256BitVector())
25954 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25957 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25958 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25959 // This exposes the zext to the udivrem lowering, so that it directly extends
25960 // from AH (which we otherwise need to do contortions to access).
25961 if (N0.getOpcode() == ISD::UDIVREM &&
25962 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25963 (VT == MVT::i32 || VT == MVT::i64)) {
25964 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25965 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25966 N0.getOperand(0), N0.getOperand(1));
25967 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25968 return R.getValue(1);
25974 // Optimize x == -y --> x+y == 0
25975 // x != -y --> x+y != 0
25976 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25977 const X86Subtarget* Subtarget) {
25978 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25979 SDValue LHS = N->getOperand(0);
25980 SDValue RHS = N->getOperand(1);
25981 EVT VT = N->getValueType(0);
25984 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25985 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25986 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25987 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25988 LHS.getOperand(1));
25989 return DAG.getSetCC(DL, N->getValueType(0), addV,
25990 DAG.getConstant(0, DL, addV.getValueType()), CC);
25992 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25993 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25994 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25995 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25996 RHS.getOperand(1));
25997 return DAG.getSetCC(DL, N->getValueType(0), addV,
25998 DAG.getConstant(0, DL, addV.getValueType()), CC);
26001 if (VT.getScalarType() == MVT::i1 &&
26002 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26004 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26005 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26006 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26008 if (!IsSEXT0 || !IsVZero1) {
26009 // Swap the operands and update the condition code.
26010 std::swap(LHS, RHS);
26011 CC = ISD::getSetCCSwappedOperands(CC);
26013 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26014 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26015 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26018 if (IsSEXT0 && IsVZero1) {
26019 assert(VT == LHS.getOperand(0).getValueType() &&
26020 "Uexpected operand type");
26021 if (CC == ISD::SETGT)
26022 return DAG.getConstant(0, DL, VT);
26023 if (CC == ISD::SETLE)
26024 return DAG.getConstant(1, DL, VT);
26025 if (CC == ISD::SETEQ || CC == ISD::SETGE)
26026 return DAG.getNOT(DL, LHS.getOperand(0), VT);
26028 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26029 "Unexpected condition code!");
26030 return LHS.getOperand(0);
26037 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
26038 SelectionDAG &DAG) {
26040 MVT VT = Load->getSimpleValueType(0);
26041 MVT EVT = VT.getVectorElementType();
26042 SDValue Addr = Load->getOperand(1);
26043 SDValue NewAddr = DAG.getNode(
26044 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
26045 DAG.getConstant(Index * EVT.getStoreSize(), dl,
26046 Addr.getSimpleValueType()));
26049 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
26050 DAG.getMachineFunction().getMachineMemOperand(
26051 Load->getMemOperand(), 0, EVT.getStoreSize()));
26055 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
26056 const X86Subtarget *Subtarget) {
26058 MVT VT = N->getOperand(1)->getSimpleValueType(0);
26059 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
26060 "X86insertps is only defined for v4x32");
26062 SDValue Ld = N->getOperand(1);
26063 if (MayFoldLoad(Ld)) {
26064 // Extract the countS bits from the immediate so we can get the proper
26065 // address when narrowing the vector load to a specific element.
26066 // When the second source op is a memory address, insertps doesn't use
26067 // countS and just gets an f32 from that address.
26068 unsigned DestIndex =
26069 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
26071 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
26073 // Create this as a scalar to vector to match the instruction pattern.
26074 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
26075 // countS bits are ignored when loading from memory on insertps, which
26076 // means we don't need to explicitly set them to 0.
26077 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
26078 LoadScalarToVector, N->getOperand(2));
26083 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26084 SDValue V0 = N->getOperand(0);
26085 SDValue V1 = N->getOperand(1);
26087 EVT VT = N->getValueType(0);
26089 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26090 // operands and changing the mask to 1. This saves us a bunch of
26091 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26092 // x86InstrInfo knows how to commute this back after instruction selection
26093 // if it would help register allocation.
26095 // TODO: If optimizing for size or a processor that doesn't suffer from
26096 // partial register update stalls, this should be transformed into a MOVSD
26097 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26099 if (VT == MVT::v2f64)
26100 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26101 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26102 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26103 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26109 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26110 // as "sbb reg,reg", since it can be extended without zext and produces
26111 // an all-ones bit which is more useful than 0/1 in some cases.
26112 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26115 return DAG.getNode(ISD::AND, DL, VT,
26116 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26117 DAG.getConstant(X86::COND_B, DL, MVT::i8),
26119 DAG.getConstant(1, DL, VT));
26120 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26121 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26122 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26123 DAG.getConstant(X86::COND_B, DL, MVT::i8),
26127 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26128 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26129 TargetLowering::DAGCombinerInfo &DCI,
26130 const X86Subtarget *Subtarget) {
26132 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26133 SDValue EFLAGS = N->getOperand(1);
26135 if (CC == X86::COND_A) {
26136 // Try to convert COND_A into COND_B in an attempt to facilitate
26137 // materializing "setb reg".
26139 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26140 // cannot take an immediate as its first operand.
26142 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26143 EFLAGS.getValueType().isInteger() &&
26144 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26145 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26146 EFLAGS.getNode()->getVTList(),
26147 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26148 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26149 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26153 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26154 // a zext and produces an all-ones bit which is more useful than 0/1 in some
26156 if (CC == X86::COND_B)
26157 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26159 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26160 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26161 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26167 // Optimize branch condition evaluation.
26169 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26170 TargetLowering::DAGCombinerInfo &DCI,
26171 const X86Subtarget *Subtarget) {
26173 SDValue Chain = N->getOperand(0);
26174 SDValue Dest = N->getOperand(1);
26175 SDValue EFLAGS = N->getOperand(3);
26176 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26178 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26179 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26180 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26187 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26188 SelectionDAG &DAG) {
26189 // Take advantage of vector comparisons producing 0 or -1 in each lane to
26190 // optimize away operation when it's from a constant.
26192 // The general transformation is:
26193 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26194 // AND(VECTOR_CMP(x,y), constant2)
26195 // constant2 = UNARYOP(constant)
26197 // Early exit if this isn't a vector operation, the operand of the
26198 // unary operation isn't a bitwise AND, or if the sizes of the operations
26199 // aren't the same.
26200 EVT VT = N->getValueType(0);
26201 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26202 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26203 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26206 // Now check that the other operand of the AND is a constant. We could
26207 // make the transformation for non-constant splats as well, but it's unclear
26208 // that would be a benefit as it would not eliminate any operations, just
26209 // perform one more step in scalar code before moving to the vector unit.
26210 if (BuildVectorSDNode *BV =
26211 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26212 // Bail out if the vector isn't a constant.
26213 if (!BV->isConstant())
26216 // Everything checks out. Build up the new and improved node.
26218 EVT IntVT = BV->getValueType(0);
26219 // Create a new constant of the appropriate type for the transformed
26221 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26222 // The AND node needs bitcasts to/from an integer vector type around it.
26223 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26224 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26225 N->getOperand(0)->getOperand(0), MaskConst);
26226 SDValue Res = DAG.getBitcast(VT, NewAnd);
26233 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26234 const X86Subtarget *Subtarget) {
26235 SDValue Op0 = N->getOperand(0);
26236 EVT VT = N->getValueType(0);
26237 EVT InVT = Op0.getValueType();
26238 EVT InSVT = InVT.getScalarType();
26239 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26241 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26242 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26243 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26245 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26246 InVT.getVectorNumElements());
26247 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26249 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26250 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26252 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26258 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26259 const X86Subtarget *Subtarget) {
26260 // First try to optimize away the conversion entirely when it's
26261 // conditionally from a constant. Vectors only.
26262 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26265 // Now move on to more general possibilities.
26266 SDValue Op0 = N->getOperand(0);
26267 EVT VT = N->getValueType(0);
26268 EVT InVT = Op0.getValueType();
26269 EVT InSVT = InVT.getScalarType();
26271 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26272 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26273 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26275 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26276 InVT.getVectorNumElements());
26277 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26278 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26281 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26282 // a 32-bit target where SSE doesn't support i64->FP operations.
26283 if (Op0.getOpcode() == ISD::LOAD) {
26284 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26285 EVT LdVT = Ld->getValueType(0);
26287 // This transformation is not supported if the result type is f16
26288 if (VT == MVT::f16)
26291 if (!Ld->isVolatile() && !VT.isVector() &&
26292 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26293 !Subtarget->is64Bit() && LdVT == MVT::i64) {
26294 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26295 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26296 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26303 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26304 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26305 X86TargetLowering::DAGCombinerInfo &DCI) {
26306 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26307 // the result is either zero or one (depending on the input carry bit).
26308 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26309 if (X86::isZeroNode(N->getOperand(0)) &&
26310 X86::isZeroNode(N->getOperand(1)) &&
26311 // We don't have a good way to replace an EFLAGS use, so only do this when
26313 SDValue(N, 1).use_empty()) {
26315 EVT VT = N->getValueType(0);
26316 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26317 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26318 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26319 DAG.getConstant(X86::COND_B, DL,
26322 DAG.getConstant(1, DL, VT));
26323 return DCI.CombineTo(N, Res1, CarryOut);
26329 // fold (add Y, (sete X, 0)) -> adc 0, Y
26330 // (add Y, (setne X, 0)) -> sbb -1, Y
26331 // (sub (sete X, 0), Y) -> sbb 0, Y
26332 // (sub (setne X, 0), Y) -> adc -1, Y
26333 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26336 // Look through ZExts.
26337 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26338 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26341 SDValue SetCC = Ext.getOperand(0);
26342 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26345 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26346 if (CC != X86::COND_E && CC != X86::COND_NE)
26349 SDValue Cmp = SetCC.getOperand(1);
26350 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26351 !X86::isZeroNode(Cmp.getOperand(1)) ||
26352 !Cmp.getOperand(0).getValueType().isInteger())
26355 SDValue CmpOp0 = Cmp.getOperand(0);
26356 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26357 DAG.getConstant(1, DL, CmpOp0.getValueType()));
26359 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26360 if (CC == X86::COND_NE)
26361 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26362 DL, OtherVal.getValueType(), OtherVal,
26363 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26365 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26366 DL, OtherVal.getValueType(), OtherVal,
26367 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26370 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26371 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26372 const X86Subtarget *Subtarget) {
26373 EVT VT = N->getValueType(0);
26374 SDValue Op0 = N->getOperand(0);
26375 SDValue Op1 = N->getOperand(1);
26377 // Try to synthesize horizontal adds from adds of shuffles.
26378 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26379 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26380 isHorizontalBinOp(Op0, Op1, true))
26381 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26383 return OptimizeConditionalInDecrement(N, DAG);
26386 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26387 const X86Subtarget *Subtarget) {
26388 SDValue Op0 = N->getOperand(0);
26389 SDValue Op1 = N->getOperand(1);
26391 // X86 can't encode an immediate LHS of a sub. See if we can push the
26392 // negation into a preceding instruction.
26393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26394 // If the RHS of the sub is a XOR with one use and a constant, invert the
26395 // immediate. Then add one to the LHS of the sub so we can turn
26396 // X-Y -> X+~Y+1, saving one register.
26397 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26398 isa<ConstantSDNode>(Op1.getOperand(1))) {
26399 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26400 EVT VT = Op0.getValueType();
26401 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26403 DAG.getConstant(~XorC, SDLoc(Op1), VT));
26404 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26405 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26409 // Try to synthesize horizontal adds from adds of shuffles.
26410 EVT VT = N->getValueType(0);
26411 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26412 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26413 isHorizontalBinOp(Op0, Op1, true))
26414 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26416 return OptimizeConditionalInDecrement(N, DAG);
26419 /// performVZEXTCombine - Performs build vector combines
26420 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26421 TargetLowering::DAGCombinerInfo &DCI,
26422 const X86Subtarget *Subtarget) {
26424 MVT VT = N->getSimpleValueType(0);
26425 SDValue Op = N->getOperand(0);
26426 MVT OpVT = Op.getSimpleValueType();
26427 MVT OpEltVT = OpVT.getVectorElementType();
26428 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26430 // (vzext (bitcast (vzext (x)) -> (vzext x)
26432 while (V.getOpcode() == ISD::BITCAST)
26433 V = V.getOperand(0);
26435 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26436 MVT InnerVT = V.getSimpleValueType();
26437 MVT InnerEltVT = InnerVT.getVectorElementType();
26439 // If the element sizes match exactly, we can just do one larger vzext. This
26440 // is always an exact type match as vzext operates on integer types.
26441 if (OpEltVT == InnerEltVT) {
26442 assert(OpVT == InnerVT && "Types must match for vzext!");
26443 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26446 // The only other way we can combine them is if only a single element of the
26447 // inner vzext is used in the input to the outer vzext.
26448 if (InnerEltVT.getSizeInBits() < InputBits)
26451 // In this case, the inner vzext is completely dead because we're going to
26452 // only look at bits inside of the low element. Just do the outer vzext on
26453 // a bitcast of the input to the inner.
26454 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26457 // Check if we can bypass extracting and re-inserting an element of an input
26458 // vector. Essentially:
26459 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26460 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26461 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26462 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26463 SDValue ExtractedV = V.getOperand(0);
26464 SDValue OrigV = ExtractedV.getOperand(0);
26465 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26466 if (ExtractIdx->getZExtValue() == 0) {
26467 MVT OrigVT = OrigV.getSimpleValueType();
26468 // Extract a subvector if necessary...
26469 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26470 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26471 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26472 OrigVT.getVectorNumElements() / Ratio);
26473 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26474 DAG.getIntPtrConstant(0, DL));
26476 Op = DAG.getBitcast(OpVT, OrigV);
26477 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26484 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26485 DAGCombinerInfo &DCI) const {
26486 SelectionDAG &DAG = DCI.DAG;
26487 switch (N->getOpcode()) {
26489 case ISD::EXTRACT_VECTOR_ELT:
26490 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26493 case X86ISD::SHRUNKBLEND:
26494 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26495 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
26496 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26497 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
26498 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
26499 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
26500 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
26503 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
26504 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
26505 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
26506 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
26507 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
26508 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26509 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
26510 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
26511 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26512 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26513 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
26514 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
26516 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
26518 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
26519 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
26520 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
26521 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
26522 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
26523 case ISD::ANY_EXTEND:
26524 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
26525 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
26526 case ISD::SIGN_EXTEND_INREG:
26527 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26528 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
26529 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26530 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26531 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
26532 case X86ISD::SHUFP: // Handle all target specific shuffles
26533 case X86ISD::PALIGNR:
26534 case X86ISD::UNPCKH:
26535 case X86ISD::UNPCKL:
26536 case X86ISD::MOVHLPS:
26537 case X86ISD::MOVLHPS:
26538 case X86ISD::PSHUFB:
26539 case X86ISD::PSHUFD:
26540 case X86ISD::PSHUFHW:
26541 case X86ISD::PSHUFLW:
26542 case X86ISD::MOVSS:
26543 case X86ISD::MOVSD:
26544 case X86ISD::VPERMILPI:
26545 case X86ISD::VPERM2X128:
26546 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26547 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
26548 case X86ISD::INSERTPS: {
26549 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26550 return PerformINSERTPSCombine(N, DAG, Subtarget);
26553 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
26559 /// isTypeDesirableForOp - Return true if the target has native support for
26560 /// the specified value type and it is 'desirable' to use the type for the
26561 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26562 /// instruction encodings are longer and some i16 instructions are slow.
26563 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26564 if (!isTypeLegal(VT))
26566 if (VT != MVT::i16)
26573 case ISD::SIGN_EXTEND:
26574 case ISD::ZERO_EXTEND:
26575 case ISD::ANY_EXTEND:
26588 /// IsDesirableToPromoteOp - This method query the target whether it is
26589 /// beneficial for dag combiner to promote the specified node. If true, it
26590 /// should return the desired promotion type by reference.
26591 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26592 EVT VT = Op.getValueType();
26593 if (VT != MVT::i16)
26596 bool Promote = false;
26597 bool Commute = false;
26598 switch (Op.getOpcode()) {
26601 LoadSDNode *LD = cast<LoadSDNode>(Op);
26602 // If the non-extending load has a single use and it's not live out, then it
26603 // might be folded.
26604 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26605 Op.hasOneUse()*/) {
26606 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26607 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26608 // The only case where we'd want to promote LOAD (rather then it being
26609 // promoted as an operand is when it's only use is liveout.
26610 if (UI->getOpcode() != ISD::CopyToReg)
26617 case ISD::SIGN_EXTEND:
26618 case ISD::ZERO_EXTEND:
26619 case ISD::ANY_EXTEND:
26624 SDValue N0 = Op.getOperand(0);
26625 // Look out for (store (shl (load), x)).
26626 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26639 SDValue N0 = Op.getOperand(0);
26640 SDValue N1 = Op.getOperand(1);
26641 if (!Commute && MayFoldLoad(N1))
26643 // Avoid disabling potential load folding opportunities.
26644 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26646 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26656 //===----------------------------------------------------------------------===//
26657 // X86 Inline Assembly Support
26658 //===----------------------------------------------------------------------===//
26660 // Helper to match a string separated by whitespace.
26661 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26662 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26664 for (StringRef Piece : Pieces) {
26665 if (!S.startswith(Piece)) // Check if the piece matches.
26668 S = S.substr(Piece.size());
26669 StringRef::size_type Pos = S.find_first_not_of(" \t");
26670 if (Pos == 0) // We matched a prefix.
26679 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26681 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26682 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26683 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26684 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26686 if (AsmPieces.size() == 3)
26688 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26695 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26696 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26698 std::string AsmStr = IA->getAsmString();
26700 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26701 if (!Ty || Ty->getBitWidth() % 16 != 0)
26704 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26705 SmallVector<StringRef, 4> AsmPieces;
26706 SplitString(AsmStr, AsmPieces, ";\n");
26708 switch (AsmPieces.size()) {
26709 default: return false;
26711 // FIXME: this should verify that we are targeting a 486 or better. If not,
26712 // we will turn this bswap into something that will be lowered to logical
26713 // ops instead of emitting the bswap asm. For now, we don't support 486 or
26714 // lower so don't worry about this.
26716 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26717 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26718 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26719 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26720 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26721 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26722 // No need to check constraints, nothing other than the equivalent of
26723 // "=r,0" would be valid here.
26724 return IntrinsicLowering::LowerToByteSwap(CI);
26727 // rorw $$8, ${0:w} --> llvm.bswap.i16
26728 if (CI->getType()->isIntegerTy(16) &&
26729 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26730 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26731 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26733 StringRef ConstraintsStr = IA->getConstraintString();
26734 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26735 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26736 if (clobbersFlagRegisters(AsmPieces))
26737 return IntrinsicLowering::LowerToByteSwap(CI);
26741 if (CI->getType()->isIntegerTy(32) &&
26742 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26743 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26744 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26745 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26747 StringRef ConstraintsStr = IA->getConstraintString();
26748 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26749 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26750 if (clobbersFlagRegisters(AsmPieces))
26751 return IntrinsicLowering::LowerToByteSwap(CI);
26754 if (CI->getType()->isIntegerTy(64)) {
26755 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26756 if (Constraints.size() >= 2 &&
26757 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26758 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26759 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26760 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26761 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26762 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26763 return IntrinsicLowering::LowerToByteSwap(CI);
26771 /// getConstraintType - Given a constraint letter, return the type of
26772 /// constraint it is for this target.
26773 X86TargetLowering::ConstraintType
26774 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26775 if (Constraint.size() == 1) {
26776 switch (Constraint[0]) {
26787 return C_RegisterClass;
26811 return TargetLowering::getConstraintType(Constraint);
26814 /// Examine constraint type and operand type and determine a weight value.
26815 /// This object must already have been set up with the operand type
26816 /// and the current alternative constraint selected.
26817 TargetLowering::ConstraintWeight
26818 X86TargetLowering::getSingleConstraintMatchWeight(
26819 AsmOperandInfo &info, const char *constraint) const {
26820 ConstraintWeight weight = CW_Invalid;
26821 Value *CallOperandVal = info.CallOperandVal;
26822 // If we don't have a value, we can't do a match,
26823 // but allow it at the lowest weight.
26824 if (!CallOperandVal)
26826 Type *type = CallOperandVal->getType();
26827 // Look at the constraint type.
26828 switch (*constraint) {
26830 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26841 if (CallOperandVal->getType()->isIntegerTy())
26842 weight = CW_SpecificReg;
26847 if (type->isFloatingPointTy())
26848 weight = CW_SpecificReg;
26851 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26852 weight = CW_SpecificReg;
26856 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26857 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26858 weight = CW_Register;
26861 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26862 if (C->getZExtValue() <= 31)
26863 weight = CW_Constant;
26867 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26868 if (C->getZExtValue() <= 63)
26869 weight = CW_Constant;
26873 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26874 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26875 weight = CW_Constant;
26879 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26880 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26881 weight = CW_Constant;
26885 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26886 if (C->getZExtValue() <= 3)
26887 weight = CW_Constant;
26891 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26892 if (C->getZExtValue() <= 0xff)
26893 weight = CW_Constant;
26898 if (isa<ConstantFP>(CallOperandVal)) {
26899 weight = CW_Constant;
26903 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26904 if ((C->getSExtValue() >= -0x80000000LL) &&
26905 (C->getSExtValue() <= 0x7fffffffLL))
26906 weight = CW_Constant;
26910 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26911 if (C->getZExtValue() <= 0xffffffff)
26912 weight = CW_Constant;
26919 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26920 /// with another that has more specific requirements based on the type of the
26921 /// corresponding operand.
26922 const char *X86TargetLowering::
26923 LowerXConstraint(EVT ConstraintVT) const {
26924 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26925 // 'f' like normal targets.
26926 if (ConstraintVT.isFloatingPoint()) {
26927 if (Subtarget->hasSSE2())
26929 if (Subtarget->hasSSE1())
26933 return TargetLowering::LowerXConstraint(ConstraintVT);
26936 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26937 /// vector. If it is invalid, don't add anything to Ops.
26938 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26939 std::string &Constraint,
26940 std::vector<SDValue>&Ops,
26941 SelectionDAG &DAG) const {
26944 // Only support length 1 constraints for now.
26945 if (Constraint.length() > 1) return;
26947 char ConstraintLetter = Constraint[0];
26948 switch (ConstraintLetter) {
26951 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26952 if (C->getZExtValue() <= 31) {
26953 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26954 Op.getValueType());
26960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26961 if (C->getZExtValue() <= 63) {
26962 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26963 Op.getValueType());
26969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26970 if (isInt<8>(C->getSExtValue())) {
26971 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26972 Op.getValueType());
26978 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26979 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26980 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26981 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26982 Op.getValueType());
26988 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26989 if (C->getZExtValue() <= 3) {
26990 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26991 Op.getValueType());
26997 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26998 if (C->getZExtValue() <= 255) {
26999 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27000 Op.getValueType());
27006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27007 if (C->getZExtValue() <= 127) {
27008 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27009 Op.getValueType());
27015 // 32-bit signed value
27016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27017 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27018 C->getSExtValue())) {
27019 // Widen to 64 bits here to get it sign extended.
27020 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27023 // FIXME gcc accepts some relocatable values here too, but only in certain
27024 // memory models; it's complicated.
27029 // 32-bit unsigned value
27030 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27031 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27032 C->getZExtValue())) {
27033 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27034 Op.getValueType());
27038 // FIXME gcc accepts some relocatable values here too, but only in certain
27039 // memory models; it's complicated.
27043 // Literal immediates are always ok.
27044 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27045 // Widen to 64 bits here to get it sign extended.
27046 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27050 // In any sort of PIC mode addresses need to be computed at runtime by
27051 // adding in a register or some sort of table lookup. These can't
27052 // be used as immediates.
27053 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27056 // If we are in non-pic codegen mode, we allow the address of a global (with
27057 // an optional displacement) to be used with 'i'.
27058 GlobalAddressSDNode *GA = nullptr;
27059 int64_t Offset = 0;
27061 // Match either (GA), (GA+C), (GA+C1+C2), etc.
27063 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27064 Offset += GA->getOffset();
27066 } else if (Op.getOpcode() == ISD::ADD) {
27067 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27068 Offset += C->getZExtValue();
27069 Op = Op.getOperand(0);
27072 } else if (Op.getOpcode() == ISD::SUB) {
27073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27074 Offset += -C->getZExtValue();
27075 Op = Op.getOperand(0);
27080 // Otherwise, this isn't something we can handle, reject it.
27084 const GlobalValue *GV = GA->getGlobal();
27085 // If we require an extra load to get this address, as in PIC mode, we
27086 // can't accept it.
27087 if (isGlobalStubReference(
27088 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27091 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27092 GA->getValueType(0), Offset);
27097 if (Result.getNode()) {
27098 Ops.push_back(Result);
27101 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27104 std::pair<unsigned, const TargetRegisterClass *>
27105 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27106 StringRef Constraint,
27108 // First, see if this is a constraint that directly corresponds to an LLVM
27110 if (Constraint.size() == 1) {
27111 // GCC Constraint Letters
27112 switch (Constraint[0]) {
27114 // TODO: Slight differences here in allocation order and leaving
27115 // RIP in the class. Do they matter any more here than they do
27116 // in the normal allocation?
27117 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27118 if (Subtarget->is64Bit()) {
27119 if (VT == MVT::i32 || VT == MVT::f32)
27120 return std::make_pair(0U, &X86::GR32RegClass);
27121 if (VT == MVT::i16)
27122 return std::make_pair(0U, &X86::GR16RegClass);
27123 if (VT == MVT::i8 || VT == MVT::i1)
27124 return std::make_pair(0U, &X86::GR8RegClass);
27125 if (VT == MVT::i64 || VT == MVT::f64)
27126 return std::make_pair(0U, &X86::GR64RegClass);
27129 // 32-bit fallthrough
27130 case 'Q': // Q_REGS
27131 if (VT == MVT::i32 || VT == MVT::f32)
27132 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27133 if (VT == MVT::i16)
27134 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27135 if (VT == MVT::i8 || VT == MVT::i1)
27136 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27137 if (VT == MVT::i64)
27138 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27140 case 'r': // GENERAL_REGS
27141 case 'l': // INDEX_REGS
27142 if (VT == MVT::i8 || VT == MVT::i1)
27143 return std::make_pair(0U, &X86::GR8RegClass);
27144 if (VT == MVT::i16)
27145 return std::make_pair(0U, &X86::GR16RegClass);
27146 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27147 return std::make_pair(0U, &X86::GR32RegClass);
27148 return std::make_pair(0U, &X86::GR64RegClass);
27149 case 'R': // LEGACY_REGS
27150 if (VT == MVT::i8 || VT == MVT::i1)
27151 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27152 if (VT == MVT::i16)
27153 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27154 if (VT == MVT::i32 || !Subtarget->is64Bit())
27155 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27156 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27157 case 'f': // FP Stack registers.
27158 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27159 // value to the correct fpstack register class.
27160 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27161 return std::make_pair(0U, &X86::RFP32RegClass);
27162 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27163 return std::make_pair(0U, &X86::RFP64RegClass);
27164 return std::make_pair(0U, &X86::RFP80RegClass);
27165 case 'y': // MMX_REGS if MMX allowed.
27166 if (!Subtarget->hasMMX()) break;
27167 return std::make_pair(0U, &X86::VR64RegClass);
27168 case 'Y': // SSE_REGS if SSE2 allowed
27169 if (!Subtarget->hasSSE2()) break;
27171 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27172 if (!Subtarget->hasSSE1()) break;
27174 switch (VT.SimpleTy) {
27176 // Scalar SSE types.
27179 return std::make_pair(0U, &X86::FR32RegClass);
27182 return std::make_pair(0U, &X86::FR64RegClass);
27190 return std::make_pair(0U, &X86::VR128RegClass);
27198 return std::make_pair(0U, &X86::VR256RegClass);
27203 return std::make_pair(0U, &X86::VR512RegClass);
27209 // Use the default implementation in TargetLowering to convert the register
27210 // constraint into a member of a register class.
27211 std::pair<unsigned, const TargetRegisterClass*> Res;
27212 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27214 // Not found as a standard register?
27216 // Map st(0) -> st(7) -> ST0
27217 if (Constraint.size() == 7 && Constraint[0] == '{' &&
27218 tolower(Constraint[1]) == 's' &&
27219 tolower(Constraint[2]) == 't' &&
27220 Constraint[3] == '(' &&
27221 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27222 Constraint[5] == ')' &&
27223 Constraint[6] == '}') {
27225 Res.first = X86::FP0+Constraint[4]-'0';
27226 Res.second = &X86::RFP80RegClass;
27230 // GCC allows "st(0)" to be called just plain "st".
27231 if (StringRef("{st}").equals_lower(Constraint)) {
27232 Res.first = X86::FP0;
27233 Res.second = &X86::RFP80RegClass;
27238 if (StringRef("{flags}").equals_lower(Constraint)) {
27239 Res.first = X86::EFLAGS;
27240 Res.second = &X86::CCRRegClass;
27244 // 'A' means EAX + EDX.
27245 if (Constraint == "A") {
27246 Res.first = X86::EAX;
27247 Res.second = &X86::GR32_ADRegClass;
27253 // Otherwise, check to see if this is a register class of the wrong value
27254 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27255 // turn into {ax},{dx}.
27256 // MVT::Other is used to specify clobber names.
27257 if (Res.second->hasType(VT) || VT == MVT::Other)
27258 return Res; // Correct type already, nothing to do.
27260 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27261 // return "eax". This should even work for things like getting 64bit integer
27262 // registers when given an f64 type.
27263 const TargetRegisterClass *Class = Res.second;
27264 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27265 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27266 unsigned Size = VT.getSizeInBits();
27267 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27268 : Size == 16 ? MVT::i16
27269 : Size == 32 ? MVT::i32
27270 : Size == 64 ? MVT::i64
27272 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27274 Res.first = DestReg;
27275 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27276 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27277 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27278 : &X86::GR64RegClass;
27279 assert(Res.second->contains(Res.first) && "Register in register class");
27281 // No register found/type mismatch.
27283 Res.second = nullptr;
27285 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27286 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27287 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27288 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27289 Class == &X86::VR512RegClass) {
27290 // Handle references to XMM physical registers that got mapped into the
27291 // wrong class. This can happen with constraints like {xmm0} where the
27292 // target independent register mapper will just pick the first match it can
27293 // find, ignoring the required type.
27295 if (VT == MVT::f32 || VT == MVT::i32)
27296 Res.second = &X86::FR32RegClass;
27297 else if (VT == MVT::f64 || VT == MVT::i64)
27298 Res.second = &X86::FR64RegClass;
27299 else if (X86::VR128RegClass.hasType(VT))
27300 Res.second = &X86::VR128RegClass;
27301 else if (X86::VR256RegClass.hasType(VT))
27302 Res.second = &X86::VR256RegClass;
27303 else if (X86::VR512RegClass.hasType(VT))
27304 Res.second = &X86::VR512RegClass;
27306 // Type mismatch and not a clobber: Return an error;
27308 Res.second = nullptr;
27315 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27316 const AddrMode &AM, Type *Ty,
27317 unsigned AS) const {
27318 // Scaling factors are not free at all.
27319 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27320 // will take 2 allocations in the out of order engine instead of 1
27321 // for plain addressing mode, i.e. inst (reg1).
27323 // vaddps (%rsi,%drx), %ymm0, %ymm1
27324 // Requires two allocations (one for the load, one for the computation)
27326 // vaddps (%rsi), %ymm0, %ymm1
27327 // Requires just 1 allocation, i.e., freeing allocations for other operations
27328 // and having less micro operations to execute.
27330 // For some X86 architectures, this is even worse because for instance for
27331 // stores, the complex addressing mode forces the instruction to use the
27332 // "load" ports instead of the dedicated "store" port.
27333 // E.g., on Haswell:
27334 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27335 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27336 if (isLegalAddressingMode(DL, AM, Ty, AS))
27337 // Scale represents reg2 * scale, thus account for 1
27338 // as soon as we use a second register.
27339 return AM.Scale != 0;
27343 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27344 // Integer division on x86 is expensive. However, when aggressively optimizing
27345 // for code size, we prefer to use a div instruction, as it is usually smaller
27346 // than the alternative sequence.
27347 // The exception to this is vector division. Since x86 doesn't have vector
27348 // integer division, leaving the division as-is is a loss even in terms of
27349 // size, because it will have to be scalarized, while the alternative code
27350 // sequence can be performed in vector form.
27351 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27352 Attribute::MinSize);
27353 return OptSize && !VT.isVector();