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 "X86ShuffleDecodeConstantPool.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
62 #define DEBUG_TYPE "x86-isel"
64 STATISTIC(NumTailCalls, "Number of tail calls");
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67 "x86-experimental-vector-widening-legalization", cl::init(false),
68 cl::desc("Enable an experimental vector type legalization through widening "
69 "rather than promotion."),
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73 const X86Subtarget &STI)
74 : TargetLowering(TM), Subtarget(&STI) {
75 X86ScalarSSEf64 = Subtarget->hasSSE2();
76 X86ScalarSSEf32 = Subtarget->hasSSE1();
77 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
79 // Set up the TargetLowering object.
81 // X86 is weird. It always uses i8 for shift amounts and setcc results.
82 setBooleanContents(ZeroOrOneBooleanContent);
83 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
86 // For 64-bit, since we have so many registers, use the ILP scheduler.
87 // For 32-bit, use the register pressure specific scheduling.
88 // For Atom, always use ILP scheduling.
89 if (Subtarget->isAtom())
90 setSchedulingPreference(Sched::ILP);
91 else if (Subtarget->is64Bit())
92 setSchedulingPreference(Sched::ILP);
94 setSchedulingPreference(Sched::RegPressure);
95 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
96 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
98 // Bypass expensive divides on Atom when compiling with O2.
99 if (TM.getOptLevel() >= CodeGenOpt::Default) {
100 if (Subtarget->hasSlowDivide32())
101 addBypassSlowDiv(32, 8);
102 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
103 addBypassSlowDiv(64, 16);
106 if (Subtarget->isTargetKnownWindowsMSVC()) {
107 // Setup Windows compiler runtime calls.
108 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
109 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
110 setLibcallName(RTLIB::SREM_I64, "_allrem");
111 setLibcallName(RTLIB::UREM_I64, "_aullrem");
112 setLibcallName(RTLIB::MUL_I64, "_allmul");
113 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
117 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
120 if (Subtarget->isTargetDarwin()) {
121 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
122 setUseUnderscoreSetJmp(false);
123 setUseUnderscoreLongJmp(false);
124 } else if (Subtarget->isTargetWindowsGNU()) {
125 // MS runtime is weird: it exports _setjmp, but longjmp!
126 setUseUnderscoreSetJmp(true);
127 setUseUnderscoreLongJmp(false);
129 setUseUnderscoreSetJmp(true);
130 setUseUnderscoreLongJmp(true);
133 // Set up the register classes.
134 addRegisterClass(MVT::i8, &X86::GR8RegClass);
135 addRegisterClass(MVT::i16, &X86::GR16RegClass);
136 addRegisterClass(MVT::i32, &X86::GR32RegClass);
137 if (Subtarget->is64Bit())
138 addRegisterClass(MVT::i64, &X86::GR64RegClass);
140 for (MVT VT : MVT::integer_valuetypes())
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
143 // We don't accept any truncstore of integer registers.
144 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
146 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
147 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
148 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
149 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
151 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
153 // SETOEQ and SETUNE require checking two conditions.
154 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
156 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
159 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
161 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
163 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
165 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
167 if (Subtarget->is64Bit()) {
168 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
169 // f32/f64 are legal, f80 is custom.
170 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
173 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
174 } else if (!Subtarget->useSoftFloat()) {
175 // We have an algorithm for SSE2->double, and we turn this into a
176 // 64-bit FILD followed by conditional FADD for other targets.
177 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
178 // We have an algorithm for SSE2, and we turn this into a 64-bit
179 // FILD or VCVTUSI2SS/SD for other targets.
180 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
183 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
185 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
186 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
188 if (!Subtarget->useSoftFloat()) {
189 // SSE has no i16 to fp conversion, only i32
190 if (X86ScalarSSEf32) {
191 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
192 // f32 and f64 cases are Legal, f80 case is not
193 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
196 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
200 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
203 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
205 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
208 if (!Subtarget->useSoftFloat()) {
209 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
210 // are Legal, f80 is custom lowered.
211 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
214 if (X86ScalarSSEf32) {
215 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
216 // f32 and f64 cases are Legal, f80 case is not
217 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
219 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
220 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
225 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
228 // Handle FP_TO_UINT by promoting the destination to a larger signed
230 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
234 if (Subtarget->is64Bit()) {
235 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
236 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
237 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
238 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
240 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
241 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
243 } else if (!Subtarget->useSoftFloat()) {
244 // Since AVX is a superset of SSE3, only check for SSE here.
245 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246 // Expand FP_TO_UINT into a select.
247 // FIXME: We would like to use a Custom expander here eventually to do
248 // the optimal thing for SSE vs. the default expansion in the legalizer.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
251 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
252 // With SSE3 we can use fisttpll to convert to a signed i64; without
253 // SSE, we're stuck with a fistpll.
254 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
256 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
259 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
260 if (!X86ScalarSSEf64) {
261 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
262 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
263 if (Subtarget->is64Bit()) {
264 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
265 // Without SSE, i64->f64 goes through memory.
266 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
268 } else if (!Subtarget->is64Bit())
269 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
271 // Scalar integer divide and remainder are lowered to use operations that
272 // produce two results, to match the available instructions. This exposes
273 // the two-result form to trivial CSE, which is able to combine x/y and x%y
274 // into a single instruction.
276 // Scalar integer multiply-high is also lowered to use two-result
277 // operations, to match the available instructions. However, plain multiply
278 // (low) operations are left as Legal, as there are single-result
279 // instructions for this in x86. Using the two-result multiply instructions
280 // when both high and low results are needed must be arranged by dagcombine.
281 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
282 setOperationAction(ISD::MULHS, VT, Expand);
283 setOperationAction(ISD::MULHU, VT, Expand);
284 setOperationAction(ISD::SDIV, VT, Expand);
285 setOperationAction(ISD::UDIV, VT, Expand);
286 setOperationAction(ISD::SREM, VT, Expand);
287 setOperationAction(ISD::UREM, VT, Expand);
289 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
290 setOperationAction(ISD::ADDC, VT, Custom);
291 setOperationAction(ISD::ADDE, VT, Custom);
292 setOperationAction(ISD::SUBC, VT, Custom);
293 setOperationAction(ISD::SUBE, VT, Custom);
296 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
297 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
298 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
299 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
300 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
301 setOperationAction(ISD::BR_CC , MVT::f128, Expand);
302 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
303 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
304 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
305 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::f128, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
312 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
313 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
314 if (Subtarget->is64Bit())
315 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
317 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
318 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
319 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
321 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
322 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
323 // is. We should promote the value to 64-bits to solve this.
324 // This is what the CRT headers do - `fmodf` is an inline header
325 // function casting to f64 and calling `fmod`.
326 setOperationAction(ISD::FREM , MVT::f32 , Promote);
328 setOperationAction(ISD::FREM , MVT::f32 , Expand);
331 setOperationAction(ISD::FREM , MVT::f64 , Expand);
332 setOperationAction(ISD::FREM , MVT::f80 , Expand);
333 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
335 // Promote the i8 variants and force them on up to i32 which has a shorter
337 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
338 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
339 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
340 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
341 if (Subtarget->hasBMI()) {
342 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
344 if (Subtarget->is64Bit())
345 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
347 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
348 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
349 if (Subtarget->is64Bit())
350 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
353 if (Subtarget->hasLZCNT()) {
354 // When promoting the i8 variants, force them to i32 for a shorter
356 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
357 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
358 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
359 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
362 if (Subtarget->is64Bit())
363 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
365 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
366 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
367 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
368 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
369 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
370 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
371 if (Subtarget->is64Bit()) {
372 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
373 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
377 // Special handling for half-precision floating point conversions.
378 // If we don't have F16C support, then lower half float conversions
379 // into library calls.
380 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
381 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
382 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
385 // There's never any support for operations beyond MVT::f32.
386 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
387 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
388 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
389 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
391 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
392 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
393 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
394 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
395 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
396 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
398 if (Subtarget->hasPOPCNT()) {
399 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
401 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
402 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
403 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
404 if (Subtarget->is64Bit())
405 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
408 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
410 if (!Subtarget->hasMOVBE())
411 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
413 // These should be promoted to a larger select which is supported.
414 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
415 // X86 wants to expand cmov itself.
416 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
417 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
418 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
419 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
421 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
422 setOperationAction(ISD::SELECT , MVT::f128 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
424 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
425 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
428 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
429 setOperationAction(ISD::SETCC , MVT::f128 , Custom);
430 setOperationAction(ISD::SETCCE , MVT::i8 , Custom);
431 setOperationAction(ISD::SETCCE , MVT::i16 , Custom);
432 setOperationAction(ISD::SETCCE , MVT::i32 , Custom);
433 if (Subtarget->is64Bit()) {
434 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
435 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
436 setOperationAction(ISD::SETCCE , MVT::i64 , Custom);
438 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
439 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
440 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
441 // support continuation, user-level threading, and etc.. As a result, no
442 // other SjLj exception interfaces are implemented and please don't build
443 // your own exception handling based on them.
444 // LLVM/Clang supports zero-cost DWARF exception handling.
445 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
446 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
449 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
450 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
451 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
452 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
453 if (Subtarget->is64Bit())
454 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
455 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
456 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
457 if (Subtarget->is64Bit()) {
458 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
459 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
460 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
461 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
462 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
464 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
465 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
466 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
467 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
468 if (Subtarget->is64Bit()) {
469 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
470 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
471 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
474 if (Subtarget->hasSSE1())
475 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
477 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
479 // Expand certain atomics
480 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
481 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
482 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
483 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
486 if (Subtarget->hasCmpxchg16b()) {
487 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
490 // FIXME - use subtarget debug flags
491 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
492 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
493 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
496 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
497 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
499 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
500 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
502 setOperationAction(ISD::TRAP, MVT::Other, Legal);
503 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
505 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
506 setOperationAction(ISD::VASTART , MVT::Other, Custom);
507 setOperationAction(ISD::VAEND , MVT::Other, Expand);
508 if (Subtarget->is64Bit()) {
509 setOperationAction(ISD::VAARG , MVT::Other, Custom);
510 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
512 // TargetInfo::CharPtrBuiltinVaList
513 setOperationAction(ISD::VAARG , MVT::Other, Expand);
514 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
517 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
518 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
520 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
522 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
523 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
524 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
526 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
527 // f32 and f64 use SSE.
528 // Set up the FP register classes.
529 addRegisterClass(MVT::f32, &X86::FR32RegClass);
530 addRegisterClass(MVT::f64, &X86::FR64RegClass);
532 // Use ANDPD to simulate FABS.
533 setOperationAction(ISD::FABS , MVT::f64, Custom);
534 setOperationAction(ISD::FABS , MVT::f32, Custom);
536 // Use XORP to simulate FNEG.
537 setOperationAction(ISD::FNEG , MVT::f64, Custom);
538 setOperationAction(ISD::FNEG , MVT::f32, Custom);
540 // Use ANDPD and ORPD to simulate FCOPYSIGN.
541 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
542 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
544 // Lower this to FGETSIGNx86 plus an AND.
545 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
546 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
548 // We don't support sin/cos/fmod
549 setOperationAction(ISD::FSIN , MVT::f64, Expand);
550 setOperationAction(ISD::FCOS , MVT::f64, Expand);
551 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
552 setOperationAction(ISD::FSIN , MVT::f32, Expand);
553 setOperationAction(ISD::FCOS , MVT::f32, Expand);
554 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
556 // Expand FP immediates into loads from the stack, except for the special
558 addLegalFPImmediate(APFloat(+0.0)); // xorpd
559 addLegalFPImmediate(APFloat(+0.0f)); // xorps
560 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
561 // Use SSE for f32, x87 for f64.
562 // Set up the FP register classes.
563 addRegisterClass(MVT::f32, &X86::FR32RegClass);
564 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
566 // Use ANDPS to simulate FABS.
567 setOperationAction(ISD::FABS , MVT::f32, Custom);
569 // Use XORP to simulate FNEG.
570 setOperationAction(ISD::FNEG , MVT::f32, Custom);
572 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
574 // Use ANDPS and ORPS to simulate FCOPYSIGN.
575 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
576 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
578 // We don't support sin/cos/fmod
579 setOperationAction(ISD::FSIN , MVT::f32, Expand);
580 setOperationAction(ISD::FCOS , MVT::f32, Expand);
581 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
583 // Special cases we handle for FP constants.
584 addLegalFPImmediate(APFloat(+0.0f)); // xorps
585 addLegalFPImmediate(APFloat(+0.0)); // FLD0
586 addLegalFPImmediate(APFloat(+1.0)); // FLD1
587 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
588 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
590 if (!TM.Options.UnsafeFPMath) {
591 setOperationAction(ISD::FSIN , MVT::f64, Expand);
592 setOperationAction(ISD::FCOS , MVT::f64, Expand);
593 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
595 } else if (!Subtarget->useSoftFloat()) {
596 // f32 and f64 in x87.
597 // Set up the FP register classes.
598 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
599 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
601 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
602 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
603 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
604 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
606 if (!TM.Options.UnsafeFPMath) {
607 setOperationAction(ISD::FSIN , MVT::f64, Expand);
608 setOperationAction(ISD::FSIN , MVT::f32, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FCOS , MVT::f32, Expand);
611 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
612 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
614 addLegalFPImmediate(APFloat(+0.0)); // FLD0
615 addLegalFPImmediate(APFloat(+1.0)); // FLD1
616 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
617 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
618 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
619 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
620 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
621 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
624 // We don't support FMA.
625 setOperationAction(ISD::FMA, MVT::f64, Expand);
626 setOperationAction(ISD::FMA, MVT::f32, Expand);
628 // Long double always uses X87, except f128 in MMX.
629 if (!Subtarget->useSoftFloat()) {
630 if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
631 addRegisterClass(MVT::f128, &X86::FR128RegClass);
632 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
633 setOperationAction(ISD::FABS , MVT::f128, Custom);
634 setOperationAction(ISD::FNEG , MVT::f128, Custom);
635 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
638 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
639 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
640 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
642 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
643 addLegalFPImmediate(TmpFlt); // FLD0
645 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
648 APFloat TmpFlt2(+1.0);
649 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
651 addLegalFPImmediate(TmpFlt2); // FLD1
652 TmpFlt2.changeSign();
653 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
656 if (!TM.Options.UnsafeFPMath) {
657 setOperationAction(ISD::FSIN , MVT::f80, Expand);
658 setOperationAction(ISD::FCOS , MVT::f80, Expand);
659 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
662 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
663 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
664 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
665 setOperationAction(ISD::FRINT, MVT::f80, Expand);
666 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
667 setOperationAction(ISD::FMA, MVT::f80, Expand);
670 // Always use a library call for pow.
671 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
673 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
675 setOperationAction(ISD::FLOG, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP, MVT::f80, Expand);
679 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
681 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
683 // First set operation action for all vector types to either promote
684 // (for widening) or expand (for scalarization). Then we will selectively
685 // turn on ones that can be effectively codegen'd.
686 for (MVT VT : MVT::vector_valuetypes()) {
687 setOperationAction(ISD::ADD , VT, Expand);
688 setOperationAction(ISD::SUB , VT, Expand);
689 setOperationAction(ISD::FADD, VT, Expand);
690 setOperationAction(ISD::FNEG, VT, Expand);
691 setOperationAction(ISD::FSUB, VT, Expand);
692 setOperationAction(ISD::MUL , VT, Expand);
693 setOperationAction(ISD::FMUL, VT, Expand);
694 setOperationAction(ISD::SDIV, VT, Expand);
695 setOperationAction(ISD::UDIV, VT, Expand);
696 setOperationAction(ISD::FDIV, VT, Expand);
697 setOperationAction(ISD::SREM, VT, Expand);
698 setOperationAction(ISD::UREM, VT, Expand);
699 setOperationAction(ISD::LOAD, VT, Expand);
700 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
703 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
704 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
705 setOperationAction(ISD::FABS, VT, Expand);
706 setOperationAction(ISD::FSIN, VT, Expand);
707 setOperationAction(ISD::FSINCOS, VT, Expand);
708 setOperationAction(ISD::FCOS, VT, Expand);
709 setOperationAction(ISD::FSINCOS, VT, Expand);
710 setOperationAction(ISD::FREM, VT, Expand);
711 setOperationAction(ISD::FMA, VT, Expand);
712 setOperationAction(ISD::FPOWI, VT, Expand);
713 setOperationAction(ISD::FSQRT, VT, Expand);
714 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
715 setOperationAction(ISD::FFLOOR, VT, Expand);
716 setOperationAction(ISD::FCEIL, VT, Expand);
717 setOperationAction(ISD::FTRUNC, VT, Expand);
718 setOperationAction(ISD::FRINT, VT, Expand);
719 setOperationAction(ISD::FNEARBYINT, VT, Expand);
720 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
721 setOperationAction(ISD::MULHS, VT, Expand);
722 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
723 setOperationAction(ISD::MULHU, VT, Expand);
724 setOperationAction(ISD::SDIVREM, VT, Expand);
725 setOperationAction(ISD::UDIVREM, VT, Expand);
726 setOperationAction(ISD::FPOW, VT, Expand);
727 setOperationAction(ISD::CTPOP, VT, Expand);
728 setOperationAction(ISD::CTTZ, VT, Expand);
729 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
730 setOperationAction(ISD::CTLZ, VT, Expand);
731 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
732 setOperationAction(ISD::SHL, VT, Expand);
733 setOperationAction(ISD::SRA, VT, Expand);
734 setOperationAction(ISD::SRL, VT, Expand);
735 setOperationAction(ISD::ROTL, VT, Expand);
736 setOperationAction(ISD::ROTR, VT, Expand);
737 setOperationAction(ISD::BSWAP, VT, Expand);
738 setOperationAction(ISD::SETCC, VT, Expand);
739 setOperationAction(ISD::FLOG, VT, Expand);
740 setOperationAction(ISD::FLOG2, VT, Expand);
741 setOperationAction(ISD::FLOG10, VT, Expand);
742 setOperationAction(ISD::FEXP, VT, Expand);
743 setOperationAction(ISD::FEXP2, VT, Expand);
744 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
745 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
746 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
747 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
748 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
749 setOperationAction(ISD::TRUNCATE, VT, Expand);
750 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
751 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
752 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
753 setOperationAction(ISD::VSELECT, VT, Expand);
754 setOperationAction(ISD::SELECT_CC, VT, Expand);
755 for (MVT InnerVT : MVT::vector_valuetypes()) {
756 setTruncStoreAction(InnerVT, VT, Expand);
758 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
759 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
761 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
762 // types, we have to deal with them whether we ask for Expansion or not.
763 // Setting Expand causes its own optimisation problems though, so leave
765 if (VT.getVectorElementType() == MVT::i1)
766 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
768 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
769 // split/scalarized right now.
770 if (VT.getVectorElementType() == MVT::f16)
771 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
775 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
776 // with -msoft-float, disable use of MMX as well.
777 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
778 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
779 // No operations on x86mmx supported, everything uses intrinsics.
782 // MMX-sized vectors (other than x86mmx) are expected to be expanded
783 // into smaller operations.
784 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
785 setOperationAction(ISD::MULHS, MMXTy, Expand);
786 setOperationAction(ISD::AND, MMXTy, Expand);
787 setOperationAction(ISD::OR, MMXTy, Expand);
788 setOperationAction(ISD::XOR, MMXTy, Expand);
789 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
790 setOperationAction(ISD::SELECT, MMXTy, Expand);
791 setOperationAction(ISD::BITCAST, MMXTy, Expand);
793 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
795 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
796 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
798 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
799 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
800 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
801 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
802 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
803 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
804 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
805 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
806 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
807 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
808 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
810 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
811 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
814 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
815 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
817 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
818 // registers cannot be used even for integer operations.
819 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
820 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
821 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
822 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
824 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
825 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
826 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
827 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
828 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
829 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
830 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
831 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
832 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
833 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
834 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
835 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
836 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
837 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
838 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
839 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
840 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
841 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
842 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
843 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
844 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
845 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
846 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
848 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
849 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
850 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
851 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
853 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
854 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
855 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
856 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
858 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
859 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
861 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
862 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
864 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
865 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
866 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
867 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
869 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
870 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
871 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
872 // ISD::CTTZ v2i64 - scalarization is faster.
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
874 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
875 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
876 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
878 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
879 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
880 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
881 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
882 setOperationAction(ISD::VSELECT, VT, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
886 // We support custom legalizing of sext and anyext loads for specific
887 // memory vector types which we can load as a scalar (or sequence of
888 // scalars) and extend in-register to a legal 128-bit vector type. For sext
889 // loads these must work with a single scalar load.
890 for (MVT VT : MVT::integer_vector_valuetypes()) {
891 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
892 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
893 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
894 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
895 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
896 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
897 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
898 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
899 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
902 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
903 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
905 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
906 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
907 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
908 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
909 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
911 if (Subtarget->is64Bit()) {
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
913 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
916 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
917 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
918 setOperationAction(ISD::AND, VT, Promote);
919 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
920 setOperationAction(ISD::OR, VT, Promote);
921 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
922 setOperationAction(ISD::XOR, VT, Promote);
923 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
924 setOperationAction(ISD::LOAD, VT, Promote);
925 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
926 setOperationAction(ISD::SELECT, VT, Promote);
927 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
930 // Custom lower v2i64 and v2f64 selects.
931 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
932 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
933 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
934 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
936 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
937 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
939 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
941 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
942 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
943 // As there is no 64-bit GPR available, we need build a special custom
944 // sequence to convert from v2i32 to v2f32.
945 if (!Subtarget->is64Bit())
946 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
948 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
949 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
951 for (MVT VT : MVT::fp_vector_valuetypes())
952 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
954 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
955 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
956 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
959 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
960 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
961 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
962 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
963 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
964 setOperationAction(ISD::FRINT, RoundedTy, Legal);
965 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
968 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
969 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
970 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
971 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
972 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
973 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
974 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
975 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
977 // FIXME: Do we need to handle scalar-to-vector here?
978 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
980 // We directly match byte blends in the backend as they match the VSELECT
982 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
984 // SSE41 brings specific instructions for doing vector sign extend even in
985 // cases where we don't have SRA.
986 for (MVT VT : MVT::integer_vector_valuetypes()) {
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
988 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
989 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
992 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
997 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
998 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1004 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1005 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1007 // i8 and i16 vectors are custom because the source register and source
1008 // source memory operand types are not the same width. f32 vectors are
1009 // custom since the immediate controlling the insert encodes additional
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1013 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1014 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1018 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1021 // FIXME: these should be Legal, but that's only for the case where
1022 // the index is constant. For now custom expand to deal with that.
1023 if (Subtarget->is64Bit()) {
1024 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1025 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1029 if (Subtarget->hasSSE2()) {
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1031 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1032 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1034 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1035 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1037 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1038 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1040 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1041 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1043 // In the customized shift lowering, the legal cases in AVX2 will be
1045 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1046 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1048 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1049 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1051 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1052 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1055 if (Subtarget->hasXOP()) {
1056 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1057 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1058 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1059 setOperationAction(ISD::ROTL, MVT::v2i64, Custom);
1060 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1061 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1062 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1063 setOperationAction(ISD::ROTL, MVT::v4i64, Custom);
1066 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1067 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1068 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1069 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1070 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1071 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1072 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1074 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1075 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1076 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1078 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1079 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1080 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1081 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1082 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1083 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1084 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1085 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1086 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1087 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1088 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1089 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1091 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1092 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1093 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1094 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1095 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1096 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1097 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1098 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1099 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1100 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1101 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1102 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1104 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1105 // even though v8i16 is a legal type.
1106 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1107 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1108 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1110 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1111 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1112 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1114 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1115 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1117 for (MVT VT : MVT::fp_vector_valuetypes())
1118 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1120 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1121 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1123 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1124 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1126 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1127 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1129 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1130 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1131 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1132 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1134 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1135 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1136 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1138 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1139 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1140 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1141 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1142 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1143 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1144 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1145 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1146 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1147 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1148 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1149 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1151 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1152 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1153 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1154 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1156 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1157 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1158 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1159 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1161 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1162 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1163 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1165 if (Subtarget->hasAnyFMA()) {
1166 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1167 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1168 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1169 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1170 setOperationAction(ISD::FMA, MVT::f32, Legal);
1171 setOperationAction(ISD::FMA, MVT::f64, Legal);
1174 if (Subtarget->hasInt256()) {
1175 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1176 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1177 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1178 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1180 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1181 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1182 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1183 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1185 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1186 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1187 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1188 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1190 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1191 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1192 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1193 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1195 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1196 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1197 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1198 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1199 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1200 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1201 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1202 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1203 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1204 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1205 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1206 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1208 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1209 // when we have a 256bit-wide blend with immediate.
1210 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1212 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1213 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1214 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1215 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1216 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1217 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1218 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1220 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1221 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1222 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1223 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1224 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1225 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1227 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1228 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1229 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1230 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1232 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1233 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1234 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1235 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1237 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1238 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1239 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1240 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1242 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1243 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1244 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1245 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1246 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1247 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1248 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1249 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1250 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1251 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1252 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1253 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1256 // In the customized shift lowering, the legal cases in AVX2 will be
1258 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1259 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1261 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1262 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1264 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1265 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1267 // Custom lower several nodes for 256-bit types.
1268 for (MVT VT : MVT::vector_valuetypes()) {
1269 if (VT.getScalarSizeInBits() >= 32) {
1270 setOperationAction(ISD::MLOAD, VT, Legal);
1271 setOperationAction(ISD::MSTORE, VT, Legal);
1273 // Extract subvector is special because the value type
1274 // (result) is 128-bit but the source is 256-bit wide.
1275 if (VT.is128BitVector()) {
1276 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1278 // Do not attempt to custom lower other non-256-bit vectors
1279 if (!VT.is256BitVector())
1282 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1283 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1284 setOperationAction(ISD::VSELECT, VT, Custom);
1285 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1286 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1287 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1288 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1289 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1292 if (Subtarget->hasInt256())
1293 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1295 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1296 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1297 setOperationAction(ISD::AND, VT, Promote);
1298 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1299 setOperationAction(ISD::OR, VT, Promote);
1300 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1301 setOperationAction(ISD::XOR, VT, Promote);
1302 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1303 setOperationAction(ISD::LOAD, VT, Promote);
1304 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1305 setOperationAction(ISD::SELECT, VT, Promote);
1306 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1310 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1311 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1314 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1316 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1317 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1318 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1320 for (MVT VT : MVT::fp_vector_valuetypes())
1321 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1323 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1325 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1327 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1329 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1330 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1331 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1332 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1333 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1334 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1336 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1337 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1338 setOperationAction(ISD::SETCCE, MVT::i1, Custom);
1339 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1340 setOperationAction(ISD::XOR, MVT::i1, Legal);
1341 setOperationAction(ISD::OR, MVT::i1, Legal);
1342 setOperationAction(ISD::AND, MVT::i1, Legal);
1343 setOperationAction(ISD::SUB, MVT::i1, Custom);
1344 setOperationAction(ISD::ADD, MVT::i1, Custom);
1345 setOperationAction(ISD::MUL, MVT::i1, Custom);
1346 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1348 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1349 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1350 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1352 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1356 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1357 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1358 setOperationAction(ISD::FABS, MVT::v16f32, Custom);
1360 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1363 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1364 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1365 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1366 setOperationAction(ISD::FABS, MVT::v8f64, Custom);
1367 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1368 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1370 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1373 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1376 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1378 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1381 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1382 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1384 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1385 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1387 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1388 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1389 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1390 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1391 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1392 if (Subtarget->hasVLX()){
1393 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1394 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1395 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1396 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1397 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1399 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1400 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1401 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1402 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1403 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1405 setOperationAction(ISD::MLOAD, MVT::v8i32, Custom);
1406 setOperationAction(ISD::MLOAD, MVT::v8f32, Custom);
1407 setOperationAction(ISD::MSTORE, MVT::v8i32, Custom);
1408 setOperationAction(ISD::MSTORE, MVT::v8f32, Custom);
1410 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1411 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1412 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1413 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1414 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1415 if (Subtarget->hasDQI()) {
1416 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1417 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1419 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1421 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1422 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1423 if (Subtarget->hasVLX()) {
1424 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1425 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1426 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1427 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1428 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1429 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1430 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1431 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1434 if (Subtarget->hasVLX()) {
1435 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1436 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1437 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1438 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1439 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1440 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1441 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1442 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1444 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1445 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1446 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1447 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1448 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1449 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1450 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1451 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1452 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1453 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1454 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1455 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1456 if (Subtarget->hasDQI()) {
1457 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1458 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1460 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1461 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1462 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1463 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1464 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1465 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1466 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1467 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1468 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1469 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1471 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1474 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1475 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1477 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1478 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1480 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1482 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1483 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1484 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1485 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1486 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1487 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1488 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1489 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1491 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1492 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1493 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1495 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1496 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1497 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1498 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1499 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1500 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1501 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1502 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1504 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1505 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1507 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1508 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1510 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1512 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1513 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1515 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1516 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1518 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1519 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1521 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1522 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1523 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1524 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1525 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1526 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1528 if (Subtarget->hasCDI()) {
1529 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1530 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1531 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Expand);
1532 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Expand);
1534 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1535 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1536 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1537 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1538 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i16, Expand);
1539 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i8, Expand);
1540 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i16, Expand);
1541 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i8, Expand);
1543 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1544 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1546 if (Subtarget->hasVLX()) {
1547 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1548 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1549 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1550 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1551 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1552 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1553 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1554 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1557 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1558 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1559 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1561 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1562 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1563 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1564 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1566 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1567 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1568 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1570 } // Subtarget->hasCDI()
1572 if (Subtarget->hasDQI()) {
1573 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1574 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1575 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1577 // Custom lower several nodes.
1578 for (MVT VT : MVT::vector_valuetypes()) {
1579 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1581 setOperationAction(ISD::AND, VT, Legal);
1582 setOperationAction(ISD::OR, VT, Legal);
1583 setOperationAction(ISD::XOR, VT, Legal);
1585 if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1586 setOperationAction(ISD::MGATHER, VT, Custom);
1587 setOperationAction(ISD::MSCATTER, VT, Custom);
1589 // Extract subvector is special because the value type
1590 // (result) is 256/128-bit but the source is 512-bit wide.
1591 if (VT.is128BitVector() || VT.is256BitVector()) {
1592 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1594 if (VT.getVectorElementType() == MVT::i1)
1595 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1597 // Do not attempt to custom lower other non-512-bit vectors
1598 if (!VT.is512BitVector())
1601 if (EltSize >= 32) {
1602 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1603 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1604 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1605 setOperationAction(ISD::VSELECT, VT, Legal);
1606 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1607 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1608 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1609 setOperationAction(ISD::MLOAD, VT, Legal);
1610 setOperationAction(ISD::MSTORE, VT, Legal);
1611 setOperationAction(ISD::MGATHER, VT, Legal);
1612 setOperationAction(ISD::MSCATTER, VT, Custom);
1615 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1616 setOperationAction(ISD::SELECT, VT, Promote);
1617 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1621 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1622 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1623 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1625 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1626 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1628 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1629 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1630 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1631 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1632 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1633 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1634 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1635 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1636 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1637 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1638 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1639 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1640 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1641 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1642 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1643 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1644 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1645 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1646 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1648 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1649 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1650 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1651 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1652 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1653 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1654 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1657 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1658 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1659 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1660 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1661 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1662 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1663 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1664 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1665 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1666 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1667 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1669 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1671 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1672 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1673 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1674 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1675 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1676 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1677 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1678 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1680 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1681 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1682 if (Subtarget->hasVLX())
1683 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1685 if (Subtarget->hasCDI()) {
1686 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1687 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1689 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8, Expand);
1692 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1693 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1694 setOperationAction(ISD::VSELECT, VT, Legal);
1695 setOperationAction(ISD::SRL, VT, Custom);
1696 setOperationAction(ISD::SHL, VT, Custom);
1697 setOperationAction(ISD::SRA, VT, Custom);
1699 setOperationAction(ISD::AND, VT, Promote);
1700 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1701 setOperationAction(ISD::OR, VT, Promote);
1702 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1703 setOperationAction(ISD::XOR, VT, Promote);
1704 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1708 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1709 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1710 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1712 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1713 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1714 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1715 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1716 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1717 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1718 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1719 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1720 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1721 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1722 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1723 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1725 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1726 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1727 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1728 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1729 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1730 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1731 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1732 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1734 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1735 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1736 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1737 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1738 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1739 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1740 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1741 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1744 // We want to custom lower some of our intrinsics.
1745 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1746 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1747 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1748 if (!Subtarget->is64Bit()) {
1749 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1750 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1753 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1754 // handle type legalization for these operations here.
1756 // FIXME: We really should do custom legalization for addition and
1757 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1758 // than generic legalization for 64-bit multiplication-with-overflow, though.
1759 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1760 if (VT == MVT::i64 && !Subtarget->is64Bit())
1762 // Add/Sub/Mul with overflow operations are custom lowered.
1763 setOperationAction(ISD::SADDO, VT, Custom);
1764 setOperationAction(ISD::UADDO, VT, Custom);
1765 setOperationAction(ISD::SSUBO, VT, Custom);
1766 setOperationAction(ISD::USUBO, VT, Custom);
1767 setOperationAction(ISD::SMULO, VT, Custom);
1768 setOperationAction(ISD::UMULO, VT, Custom);
1771 if (!Subtarget->is64Bit()) {
1772 // These libcalls are not available in 32-bit.
1773 setLibcallName(RTLIB::SHL_I128, nullptr);
1774 setLibcallName(RTLIB::SRL_I128, nullptr);
1775 setLibcallName(RTLIB::SRA_I128, nullptr);
1778 // Combine sin / cos into one node or libcall if possible.
1779 if (Subtarget->hasSinCos()) {
1780 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1781 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1782 if (Subtarget->isTargetDarwin()) {
1783 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1784 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1785 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1786 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1790 if (Subtarget->isTargetWin64()) {
1791 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1792 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1793 setOperationAction(ISD::SREM, MVT::i128, Custom);
1794 setOperationAction(ISD::UREM, MVT::i128, Custom);
1795 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1796 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1799 // We have target-specific dag combine patterns for the following nodes:
1800 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1801 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1802 setTargetDAGCombine(ISD::BITCAST);
1803 setTargetDAGCombine(ISD::VSELECT);
1804 setTargetDAGCombine(ISD::SELECT);
1805 setTargetDAGCombine(ISD::SHL);
1806 setTargetDAGCombine(ISD::SRA);
1807 setTargetDAGCombine(ISD::SRL);
1808 setTargetDAGCombine(ISD::OR);
1809 setTargetDAGCombine(ISD::AND);
1810 setTargetDAGCombine(ISD::ADD);
1811 setTargetDAGCombine(ISD::FADD);
1812 setTargetDAGCombine(ISD::FSUB);
1813 setTargetDAGCombine(ISD::FNEG);
1814 setTargetDAGCombine(ISD::FMA);
1815 setTargetDAGCombine(ISD::FMINNUM);
1816 setTargetDAGCombine(ISD::FMAXNUM);
1817 setTargetDAGCombine(ISD::SUB);
1818 setTargetDAGCombine(ISD::LOAD);
1819 setTargetDAGCombine(ISD::MLOAD);
1820 setTargetDAGCombine(ISD::STORE);
1821 setTargetDAGCombine(ISD::MSTORE);
1822 setTargetDAGCombine(ISD::TRUNCATE);
1823 setTargetDAGCombine(ISD::ZERO_EXTEND);
1824 setTargetDAGCombine(ISD::ANY_EXTEND);
1825 setTargetDAGCombine(ISD::SIGN_EXTEND);
1826 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1827 setTargetDAGCombine(ISD::SINT_TO_FP);
1828 setTargetDAGCombine(ISD::UINT_TO_FP);
1829 setTargetDAGCombine(ISD::SETCC);
1830 setTargetDAGCombine(ISD::BUILD_VECTOR);
1831 setTargetDAGCombine(ISD::MUL);
1832 setTargetDAGCombine(ISD::XOR);
1833 setTargetDAGCombine(ISD::MSCATTER);
1834 setTargetDAGCombine(ISD::MGATHER);
1836 computeRegisterProperties(Subtarget->getRegisterInfo());
1838 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1839 MaxStoresPerMemsetOptSize = 8;
1840 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1841 MaxStoresPerMemcpyOptSize = 4;
1842 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1843 MaxStoresPerMemmoveOptSize = 4;
1844 setPrefLoopAlignment(4); // 2^4 bytes.
1846 // A predictable cmov does not hurt on an in-order CPU.
1847 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1848 PredictableSelectIsExpensive = !Subtarget->isAtom();
1849 EnableExtLdPromotion = true;
1850 setPrefFunctionAlignment(4); // 2^4 bytes.
1852 verifyIntrinsicTables();
1855 // This has so far only been implemented for 64-bit MachO.
1856 bool X86TargetLowering::useLoadStackGuardNode() const {
1857 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1860 TargetLoweringBase::LegalizeTypeAction
1861 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1862 if (ExperimentalVectorWideningLegalization &&
1863 VT.getVectorNumElements() != 1 &&
1864 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1865 return TypeWidenVector;
1867 return TargetLoweringBase::getPreferredVectorAction(VT);
1870 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1873 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1875 if (VT.isSimple()) {
1876 MVT VVT = VT.getSimpleVT();
1877 const unsigned NumElts = VVT.getVectorNumElements();
1878 const MVT EltVT = VVT.getVectorElementType();
1879 if (VVT.is512BitVector()) {
1880 if (Subtarget->hasAVX512())
1881 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1882 EltVT == MVT::f32 || EltVT == MVT::f64)
1884 case 8: return MVT::v8i1;
1885 case 16: return MVT::v16i1;
1887 if (Subtarget->hasBWI())
1888 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1890 case 32: return MVT::v32i1;
1891 case 64: return MVT::v64i1;
1895 if (VVT.is256BitVector() || VVT.is128BitVector()) {
1896 if (Subtarget->hasVLX())
1897 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1898 EltVT == MVT::f32 || EltVT == MVT::f64)
1900 case 2: return MVT::v2i1;
1901 case 4: return MVT::v4i1;
1902 case 8: return MVT::v8i1;
1904 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1905 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1907 case 8: return MVT::v8i1;
1908 case 16: return MVT::v16i1;
1909 case 32: return MVT::v32i1;
1914 return VT.changeVectorElementTypeToInteger();
1917 /// Helper for getByValTypeAlignment to determine
1918 /// the desired ByVal argument alignment.
1919 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1922 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1923 if (VTy->getBitWidth() == 128)
1925 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1926 unsigned EltAlign = 0;
1927 getMaxByValAlign(ATy->getElementType(), EltAlign);
1928 if (EltAlign > MaxAlign)
1929 MaxAlign = EltAlign;
1930 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1931 for (auto *EltTy : STy->elements()) {
1932 unsigned EltAlign = 0;
1933 getMaxByValAlign(EltTy, EltAlign);
1934 if (EltAlign > MaxAlign)
1935 MaxAlign = EltAlign;
1942 /// Return the desired alignment for ByVal aggregate
1943 /// function arguments in the caller parameter area. For X86, aggregates
1944 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1945 /// are at 4-byte boundaries.
1946 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1947 const DataLayout &DL) const {
1948 if (Subtarget->is64Bit()) {
1949 // Max of 8 and alignment of type.
1950 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1957 if (Subtarget->hasSSE1())
1958 getMaxByValAlign(Ty, Align);
1962 /// Returns the target specific optimal type for load
1963 /// and store operations as a result of memset, memcpy, and memmove
1964 /// lowering. If DstAlign is zero that means it's safe to destination
1965 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1966 /// means there isn't a need to check it against alignment requirement,
1967 /// probably because the source does not need to be loaded. If 'IsMemset' is
1968 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1969 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1970 /// source is constant so it does not need to be loaded.
1971 /// It returns EVT::Other if the type should be determined using generic
1972 /// target-independent logic.
1974 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1975 unsigned DstAlign, unsigned SrcAlign,
1976 bool IsMemset, bool ZeroMemset,
1978 MachineFunction &MF) const {
1979 const Function *F = MF.getFunction();
1980 if ((!IsMemset || ZeroMemset) &&
1981 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1983 (!Subtarget->isUnalignedMem16Slow() ||
1984 ((DstAlign == 0 || DstAlign >= 16) &&
1985 (SrcAlign == 0 || SrcAlign >= 16)))) {
1987 // FIXME: Check if unaligned 32-byte accesses are slow.
1988 if (Subtarget->hasInt256())
1990 if (Subtarget->hasFp256())
1993 if (Subtarget->hasSSE2())
1995 if (Subtarget->hasSSE1())
1997 } else if (!MemcpyStrSrc && Size >= 8 &&
1998 !Subtarget->is64Bit() &&
1999 Subtarget->hasSSE2()) {
2000 // Do not use f64 to lower memcpy if source is string constant. It's
2001 // better to use i32 to avoid the loads.
2005 // This is a compromise. If we reach here, unaligned accesses may be slow on
2006 // this target. However, creating smaller, aligned accesses could be even
2007 // slower and would certainly be a lot more code.
2008 if (Subtarget->is64Bit() && Size >= 8)
2013 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2015 return X86ScalarSSEf32;
2016 else if (VT == MVT::f64)
2017 return X86ScalarSSEf64;
2022 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2027 switch (VT.getSizeInBits()) {
2029 // 8-byte and under are always assumed to be fast.
2033 *Fast = !Subtarget->isUnalignedMem16Slow();
2036 *Fast = !Subtarget->isUnalignedMem32Slow();
2038 // TODO: What about AVX-512 (512-bit) accesses?
2041 // Misaligned accesses of any size are always allowed.
2045 /// Return the entry encoding for a jump table in the
2046 /// current function. The returned value is a member of the
2047 /// MachineJumpTableInfo::JTEntryKind enum.
2048 unsigned X86TargetLowering::getJumpTableEncoding() const {
2049 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2051 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2052 Subtarget->isPICStyleGOT())
2053 return MachineJumpTableInfo::EK_Custom32;
2055 // Otherwise, use the normal jump table encoding heuristics.
2056 return TargetLowering::getJumpTableEncoding();
2059 bool X86TargetLowering::useSoftFloat() const {
2060 return Subtarget->useSoftFloat();
2064 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2065 const MachineBasicBlock *MBB,
2066 unsigned uid,MCContext &Ctx) const{
2067 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2068 Subtarget->isPICStyleGOT());
2069 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2071 return MCSymbolRefExpr::create(MBB->getSymbol(),
2072 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2075 /// Returns relocation base for the given PIC jumptable.
2076 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2077 SelectionDAG &DAG) const {
2078 if (!Subtarget->is64Bit())
2079 // This doesn't have SDLoc associated with it, but is not really the
2080 // same as a Register.
2081 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2082 getPointerTy(DAG.getDataLayout()));
2086 /// This returns the relocation base for the given PIC jumptable,
2087 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2088 const MCExpr *X86TargetLowering::
2089 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2090 MCContext &Ctx) const {
2091 // X86-64 uses RIP relative addressing based on the jump table label.
2092 if (Subtarget->isPICStyleRIPRel())
2093 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2095 // Otherwise, the reference is relative to the PIC base.
2096 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2099 std::pair<const TargetRegisterClass *, uint8_t>
2100 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2102 const TargetRegisterClass *RRC = nullptr;
2104 switch (VT.SimpleTy) {
2106 return TargetLowering::findRepresentativeClass(TRI, VT);
2107 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2108 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2111 RRC = &X86::VR64RegClass;
2113 case MVT::f32: case MVT::f64:
2114 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2115 case MVT::v4f32: case MVT::v2f64:
2116 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2118 RRC = &X86::VR128RegClass;
2121 return std::make_pair(RRC, Cost);
2124 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2125 unsigned &Offset) const {
2126 if (!Subtarget->isTargetLinux())
2129 if (Subtarget->is64Bit()) {
2130 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2132 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2144 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2145 if (!Subtarget->isTargetAndroid())
2146 return TargetLowering::getSafeStackPointerLocation(IRB);
2148 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2149 // definition of TLS_SLOT_SAFESTACK in
2150 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2151 unsigned AddressSpace, Offset;
2152 if (Subtarget->is64Bit()) {
2153 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2155 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2165 return ConstantExpr::getIntToPtr(
2166 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2167 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2170 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2171 unsigned DestAS) const {
2172 assert(SrcAS != DestAS && "Expected different address spaces!");
2174 return SrcAS < 256 && DestAS < 256;
2177 //===----------------------------------------------------------------------===//
2178 // Return Value Calling Convention Implementation
2179 //===----------------------------------------------------------------------===//
2181 #include "X86GenCallingConv.inc"
2183 bool X86TargetLowering::CanLowerReturn(
2184 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2185 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2186 SmallVector<CCValAssign, 16> RVLocs;
2187 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2188 return CCInfo.CheckReturn(Outs, RetCC_X86);
2191 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2192 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2197 X86TargetLowering::LowerReturn(SDValue Chain,
2198 CallingConv::ID CallConv, bool isVarArg,
2199 const SmallVectorImpl<ISD::OutputArg> &Outs,
2200 const SmallVectorImpl<SDValue> &OutVals,
2201 SDLoc dl, SelectionDAG &DAG) const {
2202 MachineFunction &MF = DAG.getMachineFunction();
2203 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2205 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2206 report_fatal_error("X86 interrupts may not return any value");
2208 SmallVector<CCValAssign, 16> RVLocs;
2209 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2210 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2213 SmallVector<SDValue, 6> RetOps;
2214 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2215 // Operand #1 = Bytes To Pop
2216 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2219 // Copy the result values into the output registers.
2220 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2221 CCValAssign &VA = RVLocs[i];
2222 assert(VA.isRegLoc() && "Can only return in registers!");
2223 SDValue ValToCopy = OutVals[i];
2224 EVT ValVT = ValToCopy.getValueType();
2226 // Promote values to the appropriate types.
2227 if (VA.getLocInfo() == CCValAssign::SExt)
2228 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2229 else if (VA.getLocInfo() == CCValAssign::ZExt)
2230 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2231 else if (VA.getLocInfo() == CCValAssign::AExt) {
2232 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2233 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2235 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2237 else if (VA.getLocInfo() == CCValAssign::BCvt)
2238 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2240 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2241 "Unexpected FP-extend for return value.");
2243 // If this is x86-64, and we disabled SSE, we can't return FP values,
2244 // or SSE or MMX vectors.
2245 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2246 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2247 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2248 report_fatal_error("SSE register return with SSE disabled");
2250 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2251 // llvm-gcc has never done it right and no one has noticed, so this
2252 // should be OK for now.
2253 if (ValVT == MVT::f64 &&
2254 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2255 report_fatal_error("SSE2 register return with SSE2 disabled");
2257 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2258 // the RET instruction and handled by the FP Stackifier.
2259 if (VA.getLocReg() == X86::FP0 ||
2260 VA.getLocReg() == X86::FP1) {
2261 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2262 // change the value to the FP stack register class.
2263 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2264 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2265 RetOps.push_back(ValToCopy);
2266 // Don't emit a copytoreg.
2270 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2271 // which is returned in RAX / RDX.
2272 if (Subtarget->is64Bit()) {
2273 if (ValVT == MVT::x86mmx) {
2274 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2275 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2276 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2278 // If we don't have SSE2 available, convert to v4f32 so the generated
2279 // register is legal.
2280 if (!Subtarget->hasSSE2())
2281 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2286 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2287 Flag = Chain.getValue(1);
2288 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2291 // All x86 ABIs require that for returning structs by value we copy
2292 // the sret argument into %rax/%eax (depending on ABI) for the return.
2293 // We saved the argument into a virtual register in the entry block,
2294 // so now we copy the value out and into %rax/%eax.
2296 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2297 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2298 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2299 // either case FuncInfo->setSRetReturnReg() will have been called.
2300 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2301 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2302 getPointerTy(MF.getDataLayout()));
2305 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2306 X86::RAX : X86::EAX;
2307 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2308 Flag = Chain.getValue(1);
2310 // RAX/EAX now acts like a return value.
2312 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2315 const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
2316 const MCPhysReg *I =
2317 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2320 if (X86::GR64RegClass.contains(*I))
2321 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2323 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2327 RetOps[0] = Chain; // Update chain.
2329 // Add the flag if we have it.
2331 RetOps.push_back(Flag);
2333 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2334 if (CallConv == CallingConv::X86_INTR)
2335 opcode = X86ISD::IRET;
2336 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2339 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2340 if (N->getNumValues() != 1)
2342 if (!N->hasNUsesOfValue(1, 0))
2345 SDValue TCChain = Chain;
2346 SDNode *Copy = *N->use_begin();
2347 if (Copy->getOpcode() == ISD::CopyToReg) {
2348 // If the copy has a glue operand, we conservatively assume it isn't safe to
2349 // perform a tail call.
2350 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2352 TCChain = Copy->getOperand(0);
2353 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2356 bool HasRet = false;
2357 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2359 if (UI->getOpcode() != X86ISD::RET_FLAG)
2361 // If we are returning more than one value, we can definitely
2362 // not make a tail call see PR19530
2363 if (UI->getNumOperands() > 4)
2365 if (UI->getNumOperands() == 4 &&
2366 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2379 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2380 ISD::NodeType ExtendKind) const {
2382 // TODO: Is this also valid on 32-bit?
2383 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2384 ReturnMVT = MVT::i8;
2386 ReturnMVT = MVT::i32;
2388 EVT MinVT = getRegisterType(Context, ReturnMVT);
2389 return VT.bitsLT(MinVT) ? MinVT : VT;
2392 /// Lower the result values of a call into the
2393 /// appropriate copies out of appropriate physical registers.
2396 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2397 CallingConv::ID CallConv, bool isVarArg,
2398 const SmallVectorImpl<ISD::InputArg> &Ins,
2399 SDLoc dl, SelectionDAG &DAG,
2400 SmallVectorImpl<SDValue> &InVals) const {
2402 // Assign locations to each value returned by this call.
2403 SmallVector<CCValAssign, 16> RVLocs;
2404 bool Is64Bit = Subtarget->is64Bit();
2405 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2407 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2409 // Copy all of the result registers out of their specified physreg.
2410 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2411 CCValAssign &VA = RVLocs[i];
2412 EVT CopyVT = VA.getLocVT();
2414 // If this is x86-64, and we disabled SSE, we can't return FP values
2415 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2416 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2417 report_fatal_error("SSE register return with SSE disabled");
2420 // If we prefer to use the value in xmm registers, copy it out as f80 and
2421 // use a truncate to move it from fp stack reg to xmm reg.
2422 bool RoundAfterCopy = false;
2423 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2424 isScalarFPTypeInSSEReg(VA.getValVT())) {
2426 RoundAfterCopy = (CopyVT != VA.getLocVT());
2429 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2430 CopyVT, InFlag).getValue(1);
2431 SDValue Val = Chain.getValue(0);
2434 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2435 // This truncation won't change the value.
2436 DAG.getIntPtrConstant(1, dl));
2438 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2439 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2441 InFlag = Chain.getValue(2);
2442 InVals.push_back(Val);
2448 //===----------------------------------------------------------------------===//
2449 // C & StdCall & Fast Calling Convention implementation
2450 //===----------------------------------------------------------------------===//
2451 // StdCall calling convention seems to be standard for many Windows' API
2452 // routines and around. It differs from C calling convention just a little:
2453 // callee should clean up the stack, not caller. Symbols should be also
2454 // decorated in some fancy way :) It doesn't support any vector arguments.
2455 // For info on fast calling convention see Fast Calling Convention (tail call)
2456 // implementation LowerX86_32FastCCCallTo.
2458 /// CallIsStructReturn - Determines whether a call uses struct return
2460 enum StructReturnType {
2465 static StructReturnType
2466 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2468 return NotStructReturn;
2470 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2471 if (!Flags.isSRet())
2472 return NotStructReturn;
2473 if (Flags.isInReg() || IsMCU)
2474 return RegStructReturn;
2475 return StackStructReturn;
2478 /// Determines whether a function uses struct return semantics.
2479 static StructReturnType
2480 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2482 return NotStructReturn;
2484 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2485 if (!Flags.isSRet())
2486 return NotStructReturn;
2487 if (Flags.isInReg() || IsMCU)
2488 return RegStructReturn;
2489 return StackStructReturn;
2492 /// Make a copy of an aggregate at address specified by "Src" to address
2493 /// "Dst" with size and alignment information specified by the specific
2494 /// parameter attribute. The copy will be passed as a byval function parameter.
2496 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2497 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2499 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2501 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2502 /*isVolatile*/false, /*AlwaysInline=*/true,
2503 /*isTailCall*/false,
2504 MachinePointerInfo(), MachinePointerInfo());
2507 /// Return true if the calling convention is one that we can guarantee TCO for.
2508 static bool canGuaranteeTCO(CallingConv::ID CC) {
2509 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2510 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2513 /// Return true if we might ever do TCO for calls with this calling convention.
2514 static bool mayTailCallThisCC(CallingConv::ID CC) {
2516 // C calling conventions:
2517 case CallingConv::C:
2518 case CallingConv::X86_64_Win64:
2519 case CallingConv::X86_64_SysV:
2520 // Callee pop conventions:
2521 case CallingConv::X86_ThisCall:
2522 case CallingConv::X86_StdCall:
2523 case CallingConv::X86_VectorCall:
2524 case CallingConv::X86_FastCall:
2527 return canGuaranteeTCO(CC);
2531 /// Return true if the function is being made into a tailcall target by
2532 /// changing its ABI.
2533 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2534 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2537 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2539 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2540 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2544 CallingConv::ID CalleeCC = CS.getCallingConv();
2545 if (!mayTailCallThisCC(CalleeCC))
2552 X86TargetLowering::LowerMemArgument(SDValue Chain,
2553 CallingConv::ID CallConv,
2554 const SmallVectorImpl<ISD::InputArg> &Ins,
2555 SDLoc dl, SelectionDAG &DAG,
2556 const CCValAssign &VA,
2557 MachineFrameInfo *MFI,
2559 // Create the nodes corresponding to a load from this parameter slot.
2560 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2561 bool AlwaysUseMutable = shouldGuaranteeTCO(
2562 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2563 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2566 // If value is passed by pointer we have address passed instead of the value
2568 bool ExtendedInMem = VA.isExtInLoc() &&
2569 VA.getValVT().getScalarType() == MVT::i1;
2571 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2572 ValVT = VA.getLocVT();
2574 ValVT = VA.getValVT();
2576 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2577 // taken by a return address.
2579 if (CallConv == CallingConv::X86_INTR) {
2580 const X86Subtarget& Subtarget =
2581 static_cast<const X86Subtarget&>(DAG.getSubtarget());
2582 // X86 interrupts may take one or two arguments.
2583 // On the stack there will be no return address as in regular call.
2584 // Offset of last argument need to be set to -4/-8 bytes.
2585 // Where offset of the first argument out of two, should be set to 0 bytes.
2586 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2589 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2590 // changed with more analysis.
2591 // In case of tail call optimization mark all arguments mutable. Since they
2592 // could be overwritten by lowering of arguments in case of a tail call.
2593 if (Flags.isByVal()) {
2594 unsigned Bytes = Flags.getByValSize();
2595 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2596 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2597 // Adjust SP offset of interrupt parameter.
2598 if (CallConv == CallingConv::X86_INTR) {
2599 MFI->setObjectOffset(FI, Offset);
2601 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2603 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2604 VA.getLocMemOffset(), isImmutable);
2605 // Adjust SP offset of interrupt parameter.
2606 if (CallConv == CallingConv::X86_INTR) {
2607 MFI->setObjectOffset(FI, Offset);
2610 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2611 SDValue Val = DAG.getLoad(
2612 ValVT, dl, Chain, FIN,
2613 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2615 return ExtendedInMem ?
2616 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2620 // FIXME: Get this from tablegen.
2621 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2622 const X86Subtarget *Subtarget) {
2623 assert(Subtarget->is64Bit());
2625 if (Subtarget->isCallingConvWin64(CallConv)) {
2626 static const MCPhysReg GPR64ArgRegsWin64[] = {
2627 X86::RCX, X86::RDX, X86::R8, X86::R9
2629 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2632 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2633 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2635 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2638 // FIXME: Get this from tablegen.
2639 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2640 CallingConv::ID CallConv,
2641 const X86Subtarget *Subtarget) {
2642 assert(Subtarget->is64Bit());
2643 if (Subtarget->isCallingConvWin64(CallConv)) {
2644 // The XMM registers which might contain var arg parameters are shadowed
2645 // in their paired GPR. So we only need to save the GPR to their home
2647 // TODO: __vectorcall will change this.
2651 const Function *Fn = MF.getFunction();
2652 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2653 bool isSoftFloat = Subtarget->useSoftFloat();
2654 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2655 "SSE register cannot be used when SSE is disabled!");
2656 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2657 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2661 static const MCPhysReg XMMArgRegs64Bit[] = {
2662 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2663 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2665 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2668 SDValue X86TargetLowering::LowerFormalArguments(
2669 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2670 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2671 SmallVectorImpl<SDValue> &InVals) const {
2672 MachineFunction &MF = DAG.getMachineFunction();
2673 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2674 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2676 const Function* Fn = MF.getFunction();
2677 if (Fn->hasExternalLinkage() &&
2678 Subtarget->isTargetCygMing() &&
2679 Fn->getName() == "main")
2680 FuncInfo->setForceFramePointer(true);
2682 MachineFrameInfo *MFI = MF.getFrameInfo();
2683 bool Is64Bit = Subtarget->is64Bit();
2684 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2686 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2687 "Var args not supported with calling convention fastcc, ghc or hipe");
2689 if (CallConv == CallingConv::X86_INTR) {
2690 bool isLegal = Ins.size() == 1 ||
2691 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2692 (!Is64Bit && Ins[1].VT == MVT::i32)));
2694 report_fatal_error("X86 interrupts may take one or two arguments");
2697 // Assign locations to all of the incoming arguments.
2698 SmallVector<CCValAssign, 16> ArgLocs;
2699 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2701 // Allocate shadow area for Win64
2703 CCInfo.AllocateStack(32, 8);
2705 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2707 unsigned LastVal = ~0U;
2709 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2710 CCValAssign &VA = ArgLocs[i];
2711 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2713 assert(VA.getValNo() != LastVal &&
2714 "Don't support value assigned to multiple locs yet");
2716 LastVal = VA.getValNo();
2718 if (VA.isRegLoc()) {
2719 EVT RegVT = VA.getLocVT();
2720 const TargetRegisterClass *RC;
2721 if (RegVT == MVT::i32)
2722 RC = &X86::GR32RegClass;
2723 else if (Is64Bit && RegVT == MVT::i64)
2724 RC = &X86::GR64RegClass;
2725 else if (RegVT == MVT::f32)
2726 RC = &X86::FR32RegClass;
2727 else if (RegVT == MVT::f64)
2728 RC = &X86::FR64RegClass;
2729 else if (RegVT == MVT::f128)
2730 RC = &X86::FR128RegClass;
2731 else if (RegVT.is512BitVector())
2732 RC = &X86::VR512RegClass;
2733 else if (RegVT.is256BitVector())
2734 RC = &X86::VR256RegClass;
2735 else if (RegVT.is128BitVector())
2736 RC = &X86::VR128RegClass;
2737 else if (RegVT == MVT::x86mmx)
2738 RC = &X86::VR64RegClass;
2739 else if (RegVT == MVT::i1)
2740 RC = &X86::VK1RegClass;
2741 else if (RegVT == MVT::v8i1)
2742 RC = &X86::VK8RegClass;
2743 else if (RegVT == MVT::v16i1)
2744 RC = &X86::VK16RegClass;
2745 else if (RegVT == MVT::v32i1)
2746 RC = &X86::VK32RegClass;
2747 else if (RegVT == MVT::v64i1)
2748 RC = &X86::VK64RegClass;
2750 llvm_unreachable("Unknown argument type!");
2752 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2753 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2755 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2756 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2758 if (VA.getLocInfo() == CCValAssign::SExt)
2759 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2760 DAG.getValueType(VA.getValVT()));
2761 else if (VA.getLocInfo() == CCValAssign::ZExt)
2762 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2763 DAG.getValueType(VA.getValVT()));
2764 else if (VA.getLocInfo() == CCValAssign::BCvt)
2765 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2767 if (VA.isExtInLoc()) {
2768 // Handle MMX values passed in XMM regs.
2769 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2770 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2772 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2775 assert(VA.isMemLoc());
2776 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2779 // If value is passed via pointer - do a load.
2780 if (VA.getLocInfo() == CCValAssign::Indirect)
2781 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2782 MachinePointerInfo(), false, false, false, 0);
2784 InVals.push_back(ArgValue);
2787 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2788 // All x86 ABIs require that for returning structs by value we copy the
2789 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2790 // the argument into a virtual register so that we can access it from the
2792 if (Ins[i].Flags.isSRet()) {
2793 unsigned Reg = FuncInfo->getSRetReturnReg();
2795 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2796 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2797 FuncInfo->setSRetReturnReg(Reg);
2799 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2800 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2805 unsigned StackSize = CCInfo.getNextStackOffset();
2806 // Align stack specially for tail calls.
2807 if (shouldGuaranteeTCO(CallConv,
2808 MF.getTarget().Options.GuaranteedTailCallOpt))
2809 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2811 // If the function takes variable number of arguments, make a frame index for
2812 // the start of the first vararg value... for expansion of llvm.va_start. We
2813 // can skip this if there are no va_start calls.
2814 if (MFI->hasVAStart() &&
2815 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2816 CallConv != CallingConv::X86_ThisCall))) {
2817 FuncInfo->setVarArgsFrameIndex(
2818 MFI->CreateFixedObject(1, StackSize, true));
2821 // Figure out if XMM registers are in use.
2822 assert(!(Subtarget->useSoftFloat() &&
2823 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2824 "SSE register cannot be used when SSE is disabled!");
2826 // 64-bit calling conventions support varargs and register parameters, so we
2827 // have to do extra work to spill them in the prologue.
2828 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2829 // Find the first unallocated argument registers.
2830 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2831 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2832 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2833 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2834 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2835 "SSE register cannot be used when SSE is disabled!");
2837 // Gather all the live in physical registers.
2838 SmallVector<SDValue, 6> LiveGPRs;
2839 SmallVector<SDValue, 8> LiveXMMRegs;
2841 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2842 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2844 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2846 if (!ArgXMMs.empty()) {
2847 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2848 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2849 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2850 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2851 LiveXMMRegs.push_back(
2852 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2857 // Get to the caller-allocated home save location. Add 8 to account
2858 // for the return address.
2859 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2860 FuncInfo->setRegSaveFrameIndex(
2861 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2862 // Fixup to set vararg frame on shadow area (4 x i64).
2864 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2866 // For X86-64, if there are vararg parameters that are passed via
2867 // registers, then we must store them to their spots on the stack so
2868 // they may be loaded by deferencing the result of va_next.
2869 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2870 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2871 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2872 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2875 // Store the integer parameter registers.
2876 SmallVector<SDValue, 8> MemOps;
2877 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2878 getPointerTy(DAG.getDataLayout()));
2879 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2880 for (SDValue Val : LiveGPRs) {
2881 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2882 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2884 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2885 MachinePointerInfo::getFixedStack(
2886 DAG.getMachineFunction(),
2887 FuncInfo->getRegSaveFrameIndex(), Offset),
2889 MemOps.push_back(Store);
2893 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2894 // Now store the XMM (fp + vector) parameter registers.
2895 SmallVector<SDValue, 12> SaveXMMOps;
2896 SaveXMMOps.push_back(Chain);
2897 SaveXMMOps.push_back(ALVal);
2898 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2899 FuncInfo->getRegSaveFrameIndex(), dl));
2900 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2901 FuncInfo->getVarArgsFPOffset(), dl));
2902 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2904 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2905 MVT::Other, SaveXMMOps));
2908 if (!MemOps.empty())
2909 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2912 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2913 // Find the largest legal vector type.
2914 MVT VecVT = MVT::Other;
2915 // FIXME: Only some x86_32 calling conventions support AVX512.
2916 if (Subtarget->hasAVX512() &&
2917 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2918 CallConv == CallingConv::Intel_OCL_BI)))
2919 VecVT = MVT::v16f32;
2920 else if (Subtarget->hasAVX())
2922 else if (Subtarget->hasSSE2())
2925 // We forward some GPRs and some vector types.
2926 SmallVector<MVT, 2> RegParmTypes;
2927 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2928 RegParmTypes.push_back(IntVT);
2929 if (VecVT != MVT::Other)
2930 RegParmTypes.push_back(VecVT);
2932 // Compute the set of forwarded registers. The rest are scratch.
2933 SmallVectorImpl<ForwardedRegister> &Forwards =
2934 FuncInfo->getForwardedMustTailRegParms();
2935 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2937 // Conservatively forward AL on x86_64, since it might be used for varargs.
2938 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2939 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2940 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2943 // Copy all forwards from physical to virtual registers.
2944 for (ForwardedRegister &F : Forwards) {
2945 // FIXME: Can we use a less constrained schedule?
2946 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2947 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2948 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2952 // Some CCs need callee pop.
2953 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2954 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2955 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2956 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2957 // X86 interrupts must pop the error code if present
2958 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2960 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2961 // If this is an sret function, the return should pop the hidden pointer.
2962 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2963 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2964 argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2965 FuncInfo->setBytesToPopOnReturn(4);
2969 // RegSaveFrameIndex is X86-64 only.
2970 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2971 if (CallConv == CallingConv::X86_FastCall ||
2972 CallConv == CallingConv::X86_ThisCall)
2973 // fastcc functions can't have varargs.
2974 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2977 FuncInfo->setArgumentStackSize(StackSize);
2979 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2980 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2981 if (Personality == EHPersonality::CoreCLR) {
2983 // TODO: Add a mechanism to frame lowering that will allow us to indicate
2984 // that we'd prefer this slot be allocated towards the bottom of the frame
2985 // (i.e. near the stack pointer after allocating the frame). Every
2986 // funclet needs a copy of this slot in its (mostly empty) frame, and the
2987 // offset from the bottom of this and each funclet's frame must be the
2988 // same, so the size of funclets' (mostly empty) frames is dictated by
2989 // how far this slot is from the bottom (since they allocate just enough
2990 // space to accomodate holding this slot at the correct offset).
2991 int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2992 EHInfo->PSPSymFrameIdx = PSPSymFI;
3000 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
3001 SDValue StackPtr, SDValue Arg,
3002 SDLoc dl, SelectionDAG &DAG,
3003 const CCValAssign &VA,
3004 ISD::ArgFlagsTy Flags) const {
3005 unsigned LocMemOffset = VA.getLocMemOffset();
3006 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3007 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3009 if (Flags.isByVal())
3010 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3012 return DAG.getStore(
3013 Chain, dl, Arg, PtrOff,
3014 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3018 /// Emit a load of return address if tail call
3019 /// optimization is performed and it is required.
3021 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3022 SDValue &OutRetAddr, SDValue Chain,
3023 bool IsTailCall, bool Is64Bit,
3024 int FPDiff, SDLoc dl) const {
3025 // Adjust the Return address stack slot.
3026 EVT VT = getPointerTy(DAG.getDataLayout());
3027 OutRetAddr = getReturnAddressFrameIndex(DAG);
3029 // Load the "old" Return address.
3030 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3031 false, false, false, 0);
3032 return SDValue(OutRetAddr.getNode(), 1);
3035 /// Emit a store of the return address if tail call
3036 /// optimization is performed and it is required (FPDiff!=0).
3037 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3038 SDValue Chain, SDValue RetAddrFrIdx,
3039 EVT PtrVT, unsigned SlotSize,
3040 int FPDiff, SDLoc dl) {
3041 // Store the return address to the appropriate stack slot.
3042 if (!FPDiff) return Chain;
3043 // Calculate the new stack slot for the return address.
3044 int NewReturnAddrFI =
3045 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3047 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3048 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3049 MachinePointerInfo::getFixedStack(
3050 DAG.getMachineFunction(), NewReturnAddrFI),
3055 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3056 /// operation of specified width.
3057 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3059 unsigned NumElems = VT.getVectorNumElements();
3060 SmallVector<int, 8> Mask;
3061 Mask.push_back(NumElems);
3062 for (unsigned i = 1; i != NumElems; ++i)
3064 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3068 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3069 SmallVectorImpl<SDValue> &InVals) const {
3070 SelectionDAG &DAG = CLI.DAG;
3072 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3073 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3074 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3075 SDValue Chain = CLI.Chain;
3076 SDValue Callee = CLI.Callee;
3077 CallingConv::ID CallConv = CLI.CallConv;
3078 bool &isTailCall = CLI.IsTailCall;
3079 bool isVarArg = CLI.IsVarArg;
3081 MachineFunction &MF = DAG.getMachineFunction();
3082 bool Is64Bit = Subtarget->is64Bit();
3083 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
3084 StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3085 bool IsSibcall = false;
3086 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3087 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3089 if (CallConv == CallingConv::X86_INTR)
3090 report_fatal_error("X86 interrupts may not be called directly");
3092 if (Attr.getValueAsString() == "true")
3095 if (Subtarget->isPICStyleGOT() &&
3096 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3097 // If we are using a GOT, disable tail calls to external symbols with
3098 // default visibility. Tail calling such a symbol requires using a GOT
3099 // relocation, which forces early binding of the symbol. This breaks code
3100 // that require lazy function symbol resolution. Using musttail or
3101 // GuaranteedTailCallOpt will override this.
3102 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3103 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3104 G->getGlobal()->hasDefaultVisibility()))
3108 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3110 // Force this to be a tail call. The verifier rules are enough to ensure
3111 // that we can lower this successfully without moving the return address
3114 } else if (isTailCall) {
3115 // Check if it's really possible to do a tail call.
3116 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3117 isVarArg, SR != NotStructReturn,
3118 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3119 Outs, OutVals, Ins, DAG);
3121 // Sibcalls are automatically detected tailcalls which do not require
3123 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3130 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3131 "Var args not supported with calling convention fastcc, ghc or hipe");
3133 // Analyze operands of the call, assigning locations to each operand.
3134 SmallVector<CCValAssign, 16> ArgLocs;
3135 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3137 // Allocate shadow area for Win64
3139 CCInfo.AllocateStack(32, 8);
3141 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3143 // Get a count of how many bytes are to be pushed on the stack.
3144 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3146 // This is a sibcall. The memory operands are available in caller's
3147 // own caller's stack.
3149 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3150 canGuaranteeTCO(CallConv))
3151 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3154 if (isTailCall && !IsSibcall && !IsMustTail) {
3155 // Lower arguments at fp - stackoffset + fpdiff.
3156 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3158 FPDiff = NumBytesCallerPushed - NumBytes;
3160 // Set the delta of movement of the returnaddr stackslot.
3161 // But only set if delta is greater than previous delta.
3162 if (FPDiff < X86Info->getTCReturnAddrDelta())
3163 X86Info->setTCReturnAddrDelta(FPDiff);
3166 unsigned NumBytesToPush = NumBytes;
3167 unsigned NumBytesToPop = NumBytes;
3169 // If we have an inalloca argument, all stack space has already been allocated
3170 // for us and be right at the top of the stack. We don't support multiple
3171 // arguments passed in memory when using inalloca.
3172 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3174 if (!ArgLocs.back().isMemLoc())
3175 report_fatal_error("cannot use inalloca attribute on a register "
3177 if (ArgLocs.back().getLocMemOffset() != 0)
3178 report_fatal_error("any parameter with the inalloca attribute must be "
3179 "the only memory argument");
3183 Chain = DAG.getCALLSEQ_START(
3184 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3186 SDValue RetAddrFrIdx;
3187 // Load return address for tail calls.
3188 if (isTailCall && FPDiff)
3189 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3190 Is64Bit, FPDiff, dl);
3192 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3193 SmallVector<SDValue, 8> MemOpChains;
3196 // Walk the register/memloc assignments, inserting copies/loads. In the case
3197 // of tail call optimization arguments are handle later.
3198 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3199 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3200 // Skip inalloca arguments, they have already been written.
3201 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3202 if (Flags.isInAlloca())
3205 CCValAssign &VA = ArgLocs[i];
3206 EVT RegVT = VA.getLocVT();
3207 SDValue Arg = OutVals[i];
3208 bool isByVal = Flags.isByVal();
3210 // Promote the value if needed.
3211 switch (VA.getLocInfo()) {
3212 default: llvm_unreachable("Unknown loc info!");
3213 case CCValAssign::Full: break;
3214 case CCValAssign::SExt:
3215 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3217 case CCValAssign::ZExt:
3218 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3220 case CCValAssign::AExt:
3221 if (Arg.getValueType().isVector() &&
3222 Arg.getValueType().getVectorElementType() == MVT::i1)
3223 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3224 else if (RegVT.is128BitVector()) {
3225 // Special case: passing MMX values in XMM registers.
3226 Arg = DAG.getBitcast(MVT::i64, Arg);
3227 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3228 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3230 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3232 case CCValAssign::BCvt:
3233 Arg = DAG.getBitcast(RegVT, Arg);
3235 case CCValAssign::Indirect: {
3236 // Store the argument.
3237 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3238 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3239 Chain = DAG.getStore(
3240 Chain, dl, Arg, SpillSlot,
3241 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3248 if (VA.isRegLoc()) {
3249 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3250 if (isVarArg && IsWin64) {
3251 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3252 // shadow reg if callee is a varargs function.
3253 unsigned ShadowReg = 0;
3254 switch (VA.getLocReg()) {
3255 case X86::XMM0: ShadowReg = X86::RCX; break;
3256 case X86::XMM1: ShadowReg = X86::RDX; break;
3257 case X86::XMM2: ShadowReg = X86::R8; break;
3258 case X86::XMM3: ShadowReg = X86::R9; break;
3261 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3263 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3264 assert(VA.isMemLoc());
3265 if (!StackPtr.getNode())
3266 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3267 getPointerTy(DAG.getDataLayout()));
3268 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3269 dl, DAG, VA, Flags));
3273 if (!MemOpChains.empty())
3274 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3276 if (Subtarget->isPICStyleGOT()) {
3277 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3280 RegsToPass.push_back(std::make_pair(
3281 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3282 getPointerTy(DAG.getDataLayout()))));
3284 // If we are tail calling and generating PIC/GOT style code load the
3285 // address of the callee into ECX. The value in ecx is used as target of
3286 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3287 // for tail calls on PIC/GOT architectures. Normally we would just put the
3288 // address of GOT into ebx and then call target@PLT. But for tail calls
3289 // ebx would be restored (since ebx is callee saved) before jumping to the
3292 // Note: The actual moving to ECX is done further down.
3293 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3294 if (G && !G->getGlobal()->hasLocalLinkage() &&
3295 G->getGlobal()->hasDefaultVisibility())
3296 Callee = LowerGlobalAddress(Callee, DAG);
3297 else if (isa<ExternalSymbolSDNode>(Callee))
3298 Callee = LowerExternalSymbol(Callee, DAG);
3302 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3303 // From AMD64 ABI document:
3304 // For calls that may call functions that use varargs or stdargs
3305 // (prototype-less calls or calls to functions containing ellipsis (...) in
3306 // the declaration) %al is used as hidden argument to specify the number
3307 // of SSE registers used. The contents of %al do not need to match exactly
3308 // the number of registers, but must be an ubound on the number of SSE
3309 // registers used and is in the range 0 - 8 inclusive.
3311 // Count the number of XMM registers allocated.
3312 static const MCPhysReg XMMArgRegs[] = {
3313 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3314 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3316 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3317 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3318 && "SSE registers cannot be used when SSE is disabled");
3320 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3321 DAG.getConstant(NumXMMRegs, dl,
3325 if (isVarArg && IsMustTail) {
3326 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3327 for (const auto &F : Forwards) {
3328 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3329 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3333 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3334 // don't need this because the eligibility check rejects calls that require
3335 // shuffling arguments passed in memory.
3336 if (!IsSibcall && isTailCall) {
3337 // Force all the incoming stack arguments to be loaded from the stack
3338 // before any new outgoing arguments are stored to the stack, because the
3339 // outgoing stack slots may alias the incoming argument stack slots, and
3340 // the alias isn't otherwise explicit. This is slightly more conservative
3341 // than necessary, because it means that each store effectively depends
3342 // on every argument instead of just those arguments it would clobber.
3343 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3345 SmallVector<SDValue, 8> MemOpChains2;
3348 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3349 CCValAssign &VA = ArgLocs[i];
3352 assert(VA.isMemLoc());
3353 SDValue Arg = OutVals[i];
3354 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3355 // Skip inalloca arguments. They don't require any work.
3356 if (Flags.isInAlloca())
3358 // Create frame index.
3359 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3360 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3361 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3362 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3364 if (Flags.isByVal()) {
3365 // Copy relative to framepointer.
3366 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3367 if (!StackPtr.getNode())
3368 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3369 getPointerTy(DAG.getDataLayout()));
3370 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3373 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3377 // Store relative to framepointer.
3378 MemOpChains2.push_back(DAG.getStore(
3379 ArgChain, dl, Arg, FIN,
3380 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3385 if (!MemOpChains2.empty())
3386 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3388 // Store the return address to the appropriate stack slot.
3389 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3390 getPointerTy(DAG.getDataLayout()),
3391 RegInfo->getSlotSize(), FPDiff, dl);
3394 // Build a sequence of copy-to-reg nodes chained together with token chain
3395 // and flag operands which copy the outgoing args into registers.
3397 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3398 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3399 RegsToPass[i].second, InFlag);
3400 InFlag = Chain.getValue(1);
3403 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3404 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3405 // In the 64-bit large code model, we have to make all calls
3406 // through a register, since the call instruction's 32-bit
3407 // pc-relative offset may not be large enough to hold the whole
3409 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3410 // If the callee is a GlobalAddress node (quite common, every direct call
3411 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3413 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3415 // We should use extra load for direct calls to dllimported functions in
3417 const GlobalValue *GV = G->getGlobal();
3418 if (!GV->hasDLLImportStorageClass()) {
3419 unsigned char OpFlags = 0;
3420 bool ExtraLoad = false;
3421 unsigned WrapperKind = ISD::DELETED_NODE;
3423 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3424 // external symbols most go through the PLT in PIC mode. If the symbol
3425 // has hidden or protected visibility, or if it is static or local, then
3426 // we don't need to use the PLT - we can directly call it.
3427 if (Subtarget->isTargetELF() &&
3428 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3429 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3430 OpFlags = X86II::MO_PLT;
3431 } else if (Subtarget->isPICStyleStubAny() &&
3432 !GV->isStrongDefinitionForLinker() &&
3433 (!Subtarget->getTargetTriple().isMacOSX() ||
3434 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3435 // PC-relative references to external symbols should go through $stub,
3436 // unless we're building with the leopard linker or later, which
3437 // automatically synthesizes these stubs.
3438 OpFlags = X86II::MO_DARWIN_STUB;
3439 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3440 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3441 // If the function is marked as non-lazy, generate an indirect call
3442 // which loads from the GOT directly. This avoids runtime overhead
3443 // at the cost of eager binding (and one extra byte of encoding).
3444 OpFlags = X86II::MO_GOTPCREL;
3445 WrapperKind = X86ISD::WrapperRIP;
3449 Callee = DAG.getTargetGlobalAddress(
3450 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3452 // Add a wrapper if needed.
3453 if (WrapperKind != ISD::DELETED_NODE)
3454 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3455 getPointerTy(DAG.getDataLayout()), Callee);
3456 // Add extra indirection if needed.
3458 Callee = DAG.getLoad(
3459 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3460 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3463 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3464 unsigned char OpFlags = 0;
3466 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3467 // external symbols should go through the PLT.
3468 if (Subtarget->isTargetELF() &&
3469 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3470 OpFlags = X86II::MO_PLT;
3471 } else if (Subtarget->isPICStyleStubAny() &&
3472 (!Subtarget->getTargetTriple().isMacOSX() ||
3473 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3474 // PC-relative references to external symbols should go through $stub,
3475 // unless we're building with the leopard linker or later, which
3476 // automatically synthesizes these stubs.
3477 OpFlags = X86II::MO_DARWIN_STUB;
3480 Callee = DAG.getTargetExternalSymbol(
3481 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3482 } else if (Subtarget->isTarget64BitILP32() &&
3483 Callee->getValueType(0) == MVT::i32) {
3484 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3485 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3488 // Returns a chain & a flag for retval copy to use.
3489 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3490 SmallVector<SDValue, 8> Ops;
3492 if (!IsSibcall && isTailCall) {
3493 Chain = DAG.getCALLSEQ_END(Chain,
3494 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3495 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3496 InFlag = Chain.getValue(1);
3499 Ops.push_back(Chain);
3500 Ops.push_back(Callee);
3503 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3505 // Add argument registers to the end of the list so that they are known live
3507 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3508 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3509 RegsToPass[i].second.getValueType()));
3511 // Add a register mask operand representing the call-preserved registers.
3512 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3513 assert(Mask && "Missing call preserved mask for calling convention");
3515 // If this is an invoke in a 32-bit function using a funclet-based
3516 // personality, assume the function clobbers all registers. If an exception
3517 // is thrown, the runtime will not restore CSRs.
3518 // FIXME: Model this more precisely so that we can register allocate across
3519 // the normal edge and spill and fill across the exceptional edge.
3520 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3521 const Function *CallerFn = MF.getFunction();
3522 EHPersonality Pers =
3523 CallerFn->hasPersonalityFn()
3524 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3525 : EHPersonality::Unknown;
3526 if (isFuncletEHPersonality(Pers))
3527 Mask = RegInfo->getNoPreservedMask();
3530 Ops.push_back(DAG.getRegisterMask(Mask));
3532 if (InFlag.getNode())
3533 Ops.push_back(InFlag);
3537 //// If this is the first return lowered for this function, add the regs
3538 //// to the liveout set for the function.
3539 // This isn't right, although it's probably harmless on x86; liveouts
3540 // should be computed from returns not tail calls. Consider a void
3541 // function making a tail call to a function returning int.
3542 MF.getFrameInfo()->setHasTailCall();
3543 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3546 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3547 InFlag = Chain.getValue(1);
3549 // Create the CALLSEQ_END node.
3550 unsigned NumBytesForCalleeToPop;
3551 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3552 DAG.getTarget().Options.GuaranteedTailCallOpt))
3553 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3554 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3555 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3556 SR == StackStructReturn)
3557 // If this is a call to a struct-return function, the callee
3558 // pops the hidden struct pointer, so we have to push it back.
3559 // This is common for Darwin/X86, Linux & Mingw32 targets.
3560 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3561 NumBytesForCalleeToPop = 4;
3563 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3565 // Returns a flag for retval copy to use.
3567 Chain = DAG.getCALLSEQ_END(Chain,
3568 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3569 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3572 InFlag = Chain.getValue(1);
3575 // Handle result values, copying them out of physregs into vregs that we
3577 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3578 Ins, dl, DAG, InVals);
3581 //===----------------------------------------------------------------------===//
3582 // Fast Calling Convention (tail call) implementation
3583 //===----------------------------------------------------------------------===//
3585 // Like std call, callee cleans arguments, convention except that ECX is
3586 // reserved for storing the tail called function address. Only 2 registers are
3587 // free for argument passing (inreg). Tail call optimization is performed
3589 // * tailcallopt is enabled
3590 // * caller/callee are fastcc
3591 // On X86_64 architecture with GOT-style position independent code only local
3592 // (within module) calls are supported at the moment.
3593 // To keep the stack aligned according to platform abi the function
3594 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3595 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3596 // If a tail called function callee has more arguments than the caller the
3597 // caller needs to make sure that there is room to move the RETADDR to. This is
3598 // achieved by reserving an area the size of the argument delta right after the
3599 // original RETADDR, but before the saved framepointer or the spilled registers
3600 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3612 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3615 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3616 SelectionDAG& DAG) const {
3617 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3618 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3619 unsigned StackAlignment = TFI.getStackAlignment();
3620 uint64_t AlignMask = StackAlignment - 1;
3621 int64_t Offset = StackSize;
3622 unsigned SlotSize = RegInfo->getSlotSize();
3623 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3624 // Number smaller than 12 so just add the difference.
3625 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3627 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3628 Offset = ((~AlignMask) & Offset) + StackAlignment +
3629 (StackAlignment-SlotSize);
3634 /// Return true if the given stack call argument is already available in the
3635 /// same position (relatively) of the caller's incoming argument stack.
3637 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3638 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3639 const X86InstrInfo *TII) {
3640 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3642 if (Arg.getOpcode() == ISD::CopyFromReg) {
3643 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3644 if (!TargetRegisterInfo::isVirtualRegister(VR))
3646 MachineInstr *Def = MRI->getVRegDef(VR);
3649 if (!Flags.isByVal()) {
3650 if (!TII->isLoadFromStackSlot(Def, FI))
3653 unsigned Opcode = Def->getOpcode();
3654 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3655 Opcode == X86::LEA64_32r) &&
3656 Def->getOperand(1).isFI()) {
3657 FI = Def->getOperand(1).getIndex();
3658 Bytes = Flags.getByValSize();
3662 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3663 if (Flags.isByVal())
3664 // ByVal argument is passed in as a pointer but it's now being
3665 // dereferenced. e.g.
3666 // define @foo(%struct.X* %A) {
3667 // tail call @bar(%struct.X* byval %A)
3670 SDValue Ptr = Ld->getBasePtr();
3671 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3674 FI = FINode->getIndex();
3675 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3676 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3677 FI = FINode->getIndex();
3678 Bytes = Flags.getByValSize();
3682 assert(FI != INT_MAX);
3683 if (!MFI->isFixedObjectIndex(FI))
3685 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3688 /// Check whether the call is eligible for tail call optimization. Targets
3689 /// that want to do tail call optimization should implement this function.
3690 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3691 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3692 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3693 const SmallVectorImpl<ISD::OutputArg> &Outs,
3694 const SmallVectorImpl<SDValue> &OutVals,
3695 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3696 if (!mayTailCallThisCC(CalleeCC))
3699 // If -tailcallopt is specified, make fastcc functions tail-callable.
3700 MachineFunction &MF = DAG.getMachineFunction();
3701 const Function *CallerF = MF.getFunction();
3703 // If the function return type is x86_fp80 and the callee return type is not,
3704 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3705 // perform a tailcall optimization here.
3706 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3709 CallingConv::ID CallerCC = CallerF->getCallingConv();
3710 bool CCMatch = CallerCC == CalleeCC;
3711 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3712 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3714 // Win64 functions have extra shadow space for argument homing. Don't do the
3715 // sibcall if the caller and callee have mismatched expectations for this
3717 if (IsCalleeWin64 != IsCallerWin64)
3720 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3721 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3726 // Look for obvious safe cases to perform tail call optimization that do not
3727 // require ABI changes. This is what gcc calls sibcall.
3729 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3730 // emit a special epilogue.
3731 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3732 if (RegInfo->needsStackRealignment(MF))
3735 // Also avoid sibcall optimization if either caller or callee uses struct
3736 // return semantics.
3737 if (isCalleeStructRet || isCallerStructRet)
3740 // Do not sibcall optimize vararg calls unless all arguments are passed via
3742 if (isVarArg && !Outs.empty()) {
3743 // Optimizing for varargs on Win64 is unlikely to be safe without
3744 // additional testing.
3745 if (IsCalleeWin64 || IsCallerWin64)
3748 SmallVector<CCValAssign, 16> ArgLocs;
3749 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3752 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3753 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3754 if (!ArgLocs[i].isRegLoc())
3758 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3759 // stack. Therefore, if it's not used by the call it is not safe to optimize
3760 // this into a sibcall.
3761 bool Unused = false;
3762 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3769 SmallVector<CCValAssign, 16> RVLocs;
3770 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3772 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3773 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3774 CCValAssign &VA = RVLocs[i];
3775 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3780 // If the calling conventions do not match, then we'd better make sure the
3781 // results are returned in the same way as what the caller expects.
3783 SmallVector<CCValAssign, 16> RVLocs1;
3784 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3786 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3788 SmallVector<CCValAssign, 16> RVLocs2;
3789 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3791 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3793 if (RVLocs1.size() != RVLocs2.size())
3795 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3796 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3798 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3800 if (RVLocs1[i].isRegLoc()) {
3801 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3804 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3810 unsigned StackArgsSize = 0;
3812 // If the callee takes no arguments then go on to check the results of the
3814 if (!Outs.empty()) {
3815 // Check if stack adjustment is needed. For now, do not do this if any
3816 // argument is passed on the stack.
3817 SmallVector<CCValAssign, 16> ArgLocs;
3818 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3821 // Allocate shadow area for Win64
3823 CCInfo.AllocateStack(32, 8);
3825 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3826 StackArgsSize = CCInfo.getNextStackOffset();
3828 if (CCInfo.getNextStackOffset()) {
3829 // Check if the arguments are already laid out in the right way as
3830 // the caller's fixed stack objects.
3831 MachineFrameInfo *MFI = MF.getFrameInfo();
3832 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3833 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3834 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3835 CCValAssign &VA = ArgLocs[i];
3836 SDValue Arg = OutVals[i];
3837 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3838 if (VA.getLocInfo() == CCValAssign::Indirect)
3840 if (!VA.isRegLoc()) {
3841 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3848 // If the tailcall address may be in a register, then make sure it's
3849 // possible to register allocate for it. In 32-bit, the call address can
3850 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3851 // callee-saved registers are restored. These happen to be the same
3852 // registers used to pass 'inreg' arguments so watch out for those.
3853 if (!Subtarget->is64Bit() &&
3854 ((!isa<GlobalAddressSDNode>(Callee) &&
3855 !isa<ExternalSymbolSDNode>(Callee)) ||
3856 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3857 unsigned NumInRegs = 0;
3858 // In PIC we need an extra register to formulate the address computation
3860 unsigned MaxInRegs =
3861 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3863 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3864 CCValAssign &VA = ArgLocs[i];
3867 unsigned Reg = VA.getLocReg();
3870 case X86::EAX: case X86::EDX: case X86::ECX:
3871 if (++NumInRegs == MaxInRegs)
3879 bool CalleeWillPop =
3880 X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3881 MF.getTarget().Options.GuaranteedTailCallOpt);
3883 if (unsigned BytesToPop =
3884 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3885 // If we have bytes to pop, the callee must pop them.
3886 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3887 if (!CalleePopMatches)
3889 } else if (CalleeWillPop && StackArgsSize > 0) {
3890 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3898 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3899 const TargetLibraryInfo *libInfo) const {
3900 return X86::createFastISel(funcInfo, libInfo);
3903 //===----------------------------------------------------------------------===//
3904 // Other Lowering Hooks
3905 //===----------------------------------------------------------------------===//
3907 static bool MayFoldLoad(SDValue Op) {
3908 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3911 static bool MayFoldIntoStore(SDValue Op) {
3912 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3915 static bool isTargetShuffle(unsigned Opcode) {
3917 default: return false;
3918 case X86ISD::BLENDI:
3919 case X86ISD::PSHUFB:
3920 case X86ISD::PSHUFD:
3921 case X86ISD::PSHUFHW:
3922 case X86ISD::PSHUFLW:
3924 case X86ISD::INSERTPS:
3925 case X86ISD::PALIGNR:
3926 case X86ISD::MOVLHPS:
3927 case X86ISD::MOVLHPD:
3928 case X86ISD::MOVHLPS:
3929 case X86ISD::MOVLPS:
3930 case X86ISD::MOVLPD:
3931 case X86ISD::MOVSHDUP:
3932 case X86ISD::MOVSLDUP:
3933 case X86ISD::MOVDDUP:
3936 case X86ISD::UNPCKL:
3937 case X86ISD::UNPCKH:
3938 case X86ISD::VPERMILPI:
3939 case X86ISD::VPERM2X128:
3940 case X86ISD::VPERMI:
3941 case X86ISD::VPERMV:
3942 case X86ISD::VPERMV3:
3947 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3948 SDValue V1, unsigned TargetMask,
3949 SelectionDAG &DAG) {
3951 default: llvm_unreachable("Unknown x86 shuffle node");
3952 case X86ISD::PSHUFD:
3953 case X86ISD::PSHUFHW:
3954 case X86ISD::PSHUFLW:
3955 case X86ISD::VPERMILPI:
3956 case X86ISD::VPERMI:
3957 return DAG.getNode(Opc, dl, VT, V1,
3958 DAG.getConstant(TargetMask, dl, MVT::i8));
3962 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3963 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3965 default: llvm_unreachable("Unknown x86 shuffle node");
3966 case X86ISD::MOVLHPS:
3967 case X86ISD::MOVLHPD:
3968 case X86ISD::MOVHLPS:
3969 case X86ISD::MOVLPS:
3970 case X86ISD::MOVLPD:
3973 case X86ISD::UNPCKL:
3974 case X86ISD::UNPCKH:
3975 return DAG.getNode(Opc, dl, VT, V1, V2);
3979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3980 MachineFunction &MF = DAG.getMachineFunction();
3981 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3982 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3983 int ReturnAddrIndex = FuncInfo->getRAIndex();
3985 if (ReturnAddrIndex == 0) {
3986 // Set up a frame object for the return address.
3987 unsigned SlotSize = RegInfo->getSlotSize();
3988 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3991 FuncInfo->setRAIndex(ReturnAddrIndex);
3994 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3997 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3998 bool hasSymbolicDisplacement) {
3999 // Offset should fit into 32 bit immediate field.
4000 if (!isInt<32>(Offset))
4003 // If we don't have a symbolic displacement - we don't have any extra
4005 if (!hasSymbolicDisplacement)
4008 // FIXME: Some tweaks might be needed for medium code model.
4009 if (M != CodeModel::Small && M != CodeModel::Kernel)
4012 // For small code model we assume that latest object is 16MB before end of 31
4013 // bits boundary. We may also accept pretty large negative constants knowing
4014 // that all objects are in the positive half of address space.
4015 if (M == CodeModel::Small && Offset < 16*1024*1024)
4018 // For kernel code model we know that all object resist in the negative half
4019 // of 32bits address space. We may not accept negative offsets, since they may
4020 // be just off and we may accept pretty large positive ones.
4021 if (M == CodeModel::Kernel && Offset >= 0)
4027 /// Determines whether the callee is required to pop its own arguments.
4028 /// Callee pop is necessary to support tail calls.
4029 bool X86::isCalleePop(CallingConv::ID CallingConv,
4030 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4031 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4032 // can guarantee TCO.
4033 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4036 switch (CallingConv) {
4039 case CallingConv::X86_StdCall:
4040 case CallingConv::X86_FastCall:
4041 case CallingConv::X86_ThisCall:
4042 case CallingConv::X86_VectorCall:
4047 /// \brief Return true if the condition is an unsigned comparison operation.
4048 static bool isX86CCUnsigned(unsigned X86CC) {
4050 default: llvm_unreachable("Invalid integer condition!");
4051 case X86::COND_E: return true;
4052 case X86::COND_G: return false;
4053 case X86::COND_GE: return false;
4054 case X86::COND_L: return false;
4055 case X86::COND_LE: return false;
4056 case X86::COND_NE: return true;
4057 case X86::COND_B: return true;
4058 case X86::COND_A: return true;
4059 case X86::COND_BE: return true;
4060 case X86::COND_AE: return true;
4064 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4065 switch (SetCCOpcode) {
4066 default: llvm_unreachable("Invalid integer condition!");
4067 case ISD::SETEQ: return X86::COND_E;
4068 case ISD::SETGT: return X86::COND_G;
4069 case ISD::SETGE: return X86::COND_GE;
4070 case ISD::SETLT: return X86::COND_L;
4071 case ISD::SETLE: return X86::COND_LE;
4072 case ISD::SETNE: return X86::COND_NE;
4073 case ISD::SETULT: return X86::COND_B;
4074 case ISD::SETUGT: return X86::COND_A;
4075 case ISD::SETULE: return X86::COND_BE;
4076 case ISD::SETUGE: return X86::COND_AE;
4080 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4081 /// condition code, returning the condition code and the LHS/RHS of the
4082 /// comparison to make.
4083 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4084 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4086 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4087 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4088 // X > -1 -> X == 0, jump !sign.
4089 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4090 return X86::COND_NS;
4092 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4093 // X < 0 -> X == 0, jump on sign.
4096 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4098 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4099 return X86::COND_LE;
4103 return TranslateIntegerX86CC(SetCCOpcode);
4106 // First determine if it is required or is profitable to flip the operands.
4108 // If LHS is a foldable load, but RHS is not, flip the condition.
4109 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4110 !ISD::isNON_EXTLoad(RHS.getNode())) {
4111 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4112 std::swap(LHS, RHS);
4115 switch (SetCCOpcode) {
4121 std::swap(LHS, RHS);
4125 // On a floating point condition, the flags are set as follows:
4127 // 0 | 0 | 0 | X > Y
4128 // 0 | 0 | 1 | X < Y
4129 // 1 | 0 | 0 | X == Y
4130 // 1 | 1 | 1 | unordered
4131 switch (SetCCOpcode) {
4132 default: llvm_unreachable("Condcode should be pre-legalized away");
4134 case ISD::SETEQ: return X86::COND_E;
4135 case ISD::SETOLT: // flipped
4137 case ISD::SETGT: return X86::COND_A;
4138 case ISD::SETOLE: // flipped
4140 case ISD::SETGE: return X86::COND_AE;
4141 case ISD::SETUGT: // flipped
4143 case ISD::SETLT: return X86::COND_B;
4144 case ISD::SETUGE: // flipped
4146 case ISD::SETLE: return X86::COND_BE;
4148 case ISD::SETNE: return X86::COND_NE;
4149 case ISD::SETUO: return X86::COND_P;
4150 case ISD::SETO: return X86::COND_NP;
4152 case ISD::SETUNE: return X86::COND_INVALID;
4156 /// Is there a floating point cmov for the specific X86 condition code?
4157 /// Current x86 isa includes the following FP cmov instructions:
4158 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4159 static bool hasFPCMov(unsigned X86CC) {
4176 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4178 unsigned Intrinsic) const {
4180 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4184 switch (IntrData->Type) {
4187 Info.opc = ISD::INTRINSIC_W_CHAIN;
4188 Info.memVT = MVT::getVT(I.getType());
4189 Info.ptrVal = I.getArgOperand(0);
4191 Info.align = (IntrData->Type == LOADA ? Info.memVT.getSizeInBits()/8 : 1);
4193 Info.readMem = true;
4194 Info.writeMem = false;
4204 /// Returns true if the target can instruction select the
4205 /// specified FP immediate natively. If false, the legalizer will
4206 /// materialize the FP immediate as a load from a constant pool.
4207 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4208 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4209 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4215 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4216 ISD::LoadExtType ExtTy,
4218 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4219 // relocation target a movq or addq instruction: don't let the load shrink.
4220 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4221 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4222 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4223 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4227 /// \brief Returns true if it is beneficial to convert a load of a constant
4228 /// to just the constant itself.
4229 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4231 assert(Ty->isIntegerTy());
4233 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4234 if (BitSize == 0 || BitSize > 64)
4239 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4240 unsigned Index) const {
4241 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4244 return (Index == 0 || Index == ResVT.getVectorNumElements());
4247 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4248 // Speculate cttz only if we can directly use TZCNT.
4249 return Subtarget->hasBMI();
4252 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4253 // Speculate ctlz only if we can directly use LZCNT.
4254 return Subtarget->hasLZCNT();
4257 /// Return true if every element in Mask, beginning
4258 /// from position Pos and ending in Pos+Size is undef.
4259 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4260 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4266 /// Return true if Val is undef or if its value falls within the
4267 /// specified range (L, H].
4268 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4269 return (Val < 0) || (Val >= Low && Val < Hi);
4272 /// Val is either less than zero (undef) or equal to the specified value.
4273 static bool isUndefOrEqual(int Val, int CmpVal) {
4274 return (Val < 0 || Val == CmpVal);
4277 /// Return true if every element in Mask, beginning
4278 /// from position Pos and ending in Pos+Size, falls within the specified
4279 /// sequential range (Low, Low+Size]. or is undef.
4280 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4281 unsigned Pos, unsigned Size, int Low) {
4282 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4283 if (!isUndefOrEqual(Mask[i], Low))
4288 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4289 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4290 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4291 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4292 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4295 // The index should be aligned on a vecWidth-bit boundary.
4297 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4299 MVT VT = N->getSimpleValueType(0);
4300 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4301 bool Result = (Index * ElSize) % vecWidth == 0;
4306 /// Return true if the specified INSERT_SUBVECTOR
4307 /// operand specifies a subvector insert that is suitable for input to
4308 /// insertion of 128 or 256-bit subvectors
4309 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4310 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4311 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4313 // The index should be aligned on a vecWidth-bit boundary.
4315 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4317 MVT VT = N->getSimpleValueType(0);
4318 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4319 bool Result = (Index * ElSize) % vecWidth == 0;
4324 bool X86::isVINSERT128Index(SDNode *N) {
4325 return isVINSERTIndex(N, 128);
4328 bool X86::isVINSERT256Index(SDNode *N) {
4329 return isVINSERTIndex(N, 256);
4332 bool X86::isVEXTRACT128Index(SDNode *N) {
4333 return isVEXTRACTIndex(N, 128);
4336 bool X86::isVEXTRACT256Index(SDNode *N) {
4337 return isVEXTRACTIndex(N, 256);
4340 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4341 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4342 assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4343 "Illegal extract subvector for VEXTRACT");
4346 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4348 MVT VecVT = N->getOperand(0).getSimpleValueType();
4349 MVT ElVT = VecVT.getVectorElementType();
4351 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4352 return Index / NumElemsPerChunk;
4355 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4356 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4357 assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4358 "Illegal insert subvector for VINSERT");
4361 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4363 MVT VecVT = N->getSimpleValueType(0);
4364 MVT ElVT = VecVT.getVectorElementType();
4366 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4367 return Index / NumElemsPerChunk;
4370 /// Return the appropriate immediate to extract the specified
4371 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4372 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4373 return getExtractVEXTRACTImmediate(N, 128);
4376 /// Return the appropriate immediate to extract the specified
4377 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4378 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4379 return getExtractVEXTRACTImmediate(N, 256);
4382 /// Return the appropriate immediate to insert at the specified
4383 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4384 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4385 return getInsertVINSERTImmediate(N, 128);
4388 /// Return the appropriate immediate to insert at the specified
4389 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4390 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4391 return getInsertVINSERTImmediate(N, 256);
4394 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4395 bool X86::isZeroNode(SDValue Elt) {
4396 return isNullConstant(Elt) || isNullFPConstant(Elt);
4399 // Build a vector of constants
4400 // Use an UNDEF node if MaskElt == -1.
4401 // Spilt 64-bit constants in the 32-bit mode.
4402 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4404 SDLoc dl, bool IsMask = false) {
4406 SmallVector<SDValue, 32> Ops;
4409 MVT ConstVecVT = VT;
4410 unsigned NumElts = VT.getVectorNumElements();
4411 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4412 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4413 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4417 MVT EltVT = ConstVecVT.getVectorElementType();
4418 for (unsigned i = 0; i < NumElts; ++i) {
4419 bool IsUndef = Values[i] < 0 && IsMask;
4420 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4421 DAG.getConstant(Values[i], dl, EltVT);
4422 Ops.push_back(OpNode);
4424 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4425 DAG.getConstant(0, dl, EltVT));
4427 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4429 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4433 /// Returns a vector of specified type with all zero elements.
4434 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4435 SelectionDAG &DAG, SDLoc dl) {
4436 assert(VT.isVector() && "Expected a vector type");
4438 // Always build SSE zero vectors as <4 x i32> bitcasted
4439 // to their dest type. This ensures they get CSE'd.
4441 if (VT.is128BitVector()) { // SSE
4442 if (Subtarget->hasSSE2()) { // SSE2
4443 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4444 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4446 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4447 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4449 } else if (VT.is256BitVector()) { // AVX
4450 if (Subtarget->hasInt256()) { // AVX2
4451 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4452 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4453 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4455 // 256-bit logic and arithmetic instructions in AVX are all
4456 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4457 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4458 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4459 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4461 } else if (VT.is512BitVector()) { // AVX-512
4462 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4463 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4464 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4465 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4466 } else if (VT.getVectorElementType() == MVT::i1) {
4468 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4469 && "Unexpected vector type");
4470 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4471 && "Unexpected vector type");
4472 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4473 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4474 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4476 llvm_unreachable("Unexpected vector type");
4478 return DAG.getBitcast(VT, Vec);
4481 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4482 SelectionDAG &DAG, SDLoc dl,
4483 unsigned vectorWidth) {
4484 assert((vectorWidth == 128 || vectorWidth == 256) &&
4485 "Unsupported vector width");
4486 EVT VT = Vec.getValueType();
4487 EVT ElVT = VT.getVectorElementType();
4488 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4489 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4490 VT.getVectorNumElements()/Factor);
4492 // Extract from UNDEF is UNDEF.
4493 if (Vec.getOpcode() == ISD::UNDEF)
4494 return DAG.getUNDEF(ResultVT);
4496 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4497 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4498 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4500 // This is the index of the first element of the vectorWidth-bit chunk
4501 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4502 IdxVal &= ~(ElemsPerChunk - 1);
4504 // If the input is a buildvector just emit a smaller one.
4505 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4506 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4507 makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4509 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4510 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4513 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4514 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4515 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4516 /// instructions or a simple subregister reference. Idx is an index in the
4517 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4518 /// lowering EXTRACT_VECTOR_ELT operations easier.
4519 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4520 SelectionDAG &DAG, SDLoc dl) {
4521 assert((Vec.getValueType().is256BitVector() ||
4522 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4523 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4526 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4527 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4528 SelectionDAG &DAG, SDLoc dl) {
4529 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4530 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4533 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4534 unsigned IdxVal, SelectionDAG &DAG,
4535 SDLoc dl, unsigned vectorWidth) {
4536 assert((vectorWidth == 128 || vectorWidth == 256) &&
4537 "Unsupported vector width");
4538 // Inserting UNDEF is Result
4539 if (Vec.getOpcode() == ISD::UNDEF)
4541 EVT VT = Vec.getValueType();
4542 EVT ElVT = VT.getVectorElementType();
4543 EVT ResultVT = Result.getValueType();
4545 // Insert the relevant vectorWidth bits.
4546 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4547 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4549 // This is the index of the first element of the vectorWidth-bit chunk
4550 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4551 IdxVal &= ~(ElemsPerChunk - 1);
4553 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4554 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4557 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4558 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4559 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4560 /// simple superregister reference. Idx is an index in the 128 bits
4561 /// we want. It need not be aligned to a 128-bit boundary. That makes
4562 /// lowering INSERT_VECTOR_ELT operations easier.
4563 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4564 SelectionDAG &DAG, SDLoc dl) {
4565 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4567 // For insertion into the zero index (low half) of a 256-bit vector, it is
4568 // more efficient to generate a blend with immediate instead of an insert*128.
4569 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4570 // extend the subvector to the size of the result vector. Make sure that
4571 // we are not recursing on that node by checking for undef here.
4572 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4573 Result.getOpcode() != ISD::UNDEF) {
4574 EVT ResultVT = Result.getValueType();
4575 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4576 SDValue Undef = DAG.getUNDEF(ResultVT);
4577 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4580 // The blend instruction, and therefore its mask, depend on the data type.
4581 MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4582 if (ScalarType.isFloatingPoint()) {
4583 // Choose either vblendps (float) or vblendpd (double).
4584 unsigned ScalarSize = ScalarType.getSizeInBits();
4585 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4586 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4587 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4588 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4591 const X86Subtarget &Subtarget =
4592 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4594 // AVX2 is needed for 256-bit integer blend support.
4595 // Integers must be cast to 32-bit because there is only vpblendd;
4596 // vpblendw can't be used for this because it has a handicapped mask.
4598 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4599 // is still more efficient than using the wrong domain vinsertf128 that
4600 // will be created by InsertSubVector().
4601 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4603 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4604 Result = DAG.getBitcast(CastVT, Result);
4605 Vec256 = DAG.getBitcast(CastVT, Vec256);
4606 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4607 return DAG.getBitcast(ResultVT, Vec256);
4610 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4613 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4614 SelectionDAG &DAG, SDLoc dl) {
4615 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4616 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4619 /// Insert i1-subvector to i1-vector.
4620 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4623 SDValue Vec = Op.getOperand(0);
4624 SDValue SubVec = Op.getOperand(1);
4625 SDValue Idx = Op.getOperand(2);
4627 if (!isa<ConstantSDNode>(Idx))
4630 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4631 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4634 MVT OpVT = Op.getSimpleValueType();
4635 MVT SubVecVT = SubVec.getSimpleValueType();
4636 unsigned NumElems = OpVT.getVectorNumElements();
4637 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4639 assert(IdxVal + SubVecNumElems <= NumElems &&
4640 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4641 "Unexpected index value in INSERT_SUBVECTOR");
4643 // There are 3 possible cases:
4644 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4645 // 2. Subvector should be inserted in the upper part
4646 // (IdxVal + SubVecNumElems == NumElems)
4647 // 3. Subvector should be inserted in the middle (for example v2i1
4648 // to v16i1, index 2)
4650 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4651 SDValue Undef = DAG.getUNDEF(OpVT);
4652 SDValue WideSubVec =
4653 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4655 return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4656 DAG.getConstant(IdxVal, dl, MVT::i8));
4658 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4659 unsigned ShiftLeft = NumElems - SubVecNumElems;
4660 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4661 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4662 DAG.getConstant(ShiftLeft, dl, MVT::i8));
4663 return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4664 DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4668 // Zero lower bits of the Vec
4669 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4670 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4671 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4672 // Merge them together
4673 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4676 // Simple case when we put subvector in the upper part
4677 if (IdxVal + SubVecNumElems == NumElems) {
4678 // Zero upper bits of the Vec
4679 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4680 DAG.getConstant(IdxVal, dl, MVT::i8));
4681 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4682 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4683 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4684 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4686 // Subvector should be inserted in the middle - use shuffle
4687 SmallVector<int, 64> Mask;
4688 for (unsigned i = 0; i < NumElems; ++i)
4689 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4691 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4694 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4695 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4696 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4697 /// large BUILD_VECTORS.
4698 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4699 unsigned NumElems, SelectionDAG &DAG,
4701 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4702 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4705 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4706 unsigned NumElems, SelectionDAG &DAG,
4708 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4709 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4712 /// Returns a vector of specified type with all bits set.
4713 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4714 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4715 /// Then bitcast to their original type, ensuring they get CSE'd.
4716 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4717 SelectionDAG &DAG, SDLoc dl) {
4718 assert(VT.isVector() && "Expected a vector type");
4720 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4722 if (VT.is512BitVector()) {
4723 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4724 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4725 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4726 } else if (VT.is256BitVector()) {
4727 if (Subtarget->hasInt256()) { // AVX2
4728 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4729 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4731 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4732 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4734 } else if (VT.is128BitVector()) {
4735 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4737 llvm_unreachable("Unexpected vector type");
4739 return DAG.getBitcast(VT, Vec);
4742 /// Returns a vector_shuffle node for an unpackl operation.
4743 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4745 unsigned NumElems = VT.getVectorNumElements();
4746 SmallVector<int, 8> Mask;
4747 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4749 Mask.push_back(i + NumElems);
4751 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4754 /// Returns a vector_shuffle node for an unpackh operation.
4755 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4757 unsigned NumElems = VT.getVectorNumElements();
4758 SmallVector<int, 8> Mask;
4759 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4760 Mask.push_back(i + Half);
4761 Mask.push_back(i + NumElems + Half);
4763 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4766 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4767 /// This produces a shuffle where the low element of V2 is swizzled into the
4768 /// zero/undef vector, landing at element Idx.
4769 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4770 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4772 const X86Subtarget *Subtarget,
4773 SelectionDAG &DAG) {
4774 MVT VT = V2.getSimpleValueType();
4776 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4777 unsigned NumElems = VT.getVectorNumElements();
4778 SmallVector<int, 16> MaskVec;
4779 for (unsigned i = 0; i != NumElems; ++i)
4780 // If this is the insertion idx, put the low elt of V2 here.
4781 MaskVec.push_back(i == Idx ? NumElems : i);
4782 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4785 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4786 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4787 /// uses one source. Note that this will set IsUnary for shuffles which use a
4788 /// single input multiple times, and in those cases it will
4789 /// adjust the mask to only have indices within that single input.
4790 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4791 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4792 unsigned NumElems = VT.getVectorNumElements();
4796 bool IsFakeUnary = false;
4797 switch(N->getOpcode()) {
4798 case X86ISD::BLENDI:
4799 ImmN = N->getOperand(N->getNumOperands()-1);
4800 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4803 ImmN = N->getOperand(N->getNumOperands()-1);
4804 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4805 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4807 case X86ISD::INSERTPS:
4808 ImmN = N->getOperand(N->getNumOperands()-1);
4809 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4810 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4812 case X86ISD::UNPCKH:
4813 DecodeUNPCKHMask(VT, Mask);
4814 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4816 case X86ISD::UNPCKL:
4817 DecodeUNPCKLMask(VT, Mask);
4818 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4820 case X86ISD::MOVHLPS:
4821 DecodeMOVHLPSMask(NumElems, Mask);
4822 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4824 case X86ISD::MOVLHPS:
4825 DecodeMOVLHPSMask(NumElems, Mask);
4826 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4828 case X86ISD::PALIGNR:
4829 ImmN = N->getOperand(N->getNumOperands()-1);
4830 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4832 case X86ISD::PSHUFD:
4833 case X86ISD::VPERMILPI:
4834 ImmN = N->getOperand(N->getNumOperands()-1);
4835 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4838 case X86ISD::PSHUFHW:
4839 ImmN = N->getOperand(N->getNumOperands()-1);
4840 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4843 case X86ISD::PSHUFLW:
4844 ImmN = N->getOperand(N->getNumOperands()-1);
4845 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4848 case X86ISD::PSHUFB: {
4850 SDValue MaskNode = N->getOperand(1);
4851 while (MaskNode->getOpcode() == ISD::BITCAST)
4852 MaskNode = MaskNode->getOperand(0);
4854 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4855 // If we have a build-vector, then things are easy.
4856 MVT VT = MaskNode.getSimpleValueType();
4857 assert(VT.isVector() &&
4858 "Can't produce a non-vector with a build_vector!");
4859 if (!VT.isInteger())
4862 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4864 SmallVector<uint64_t, 32> RawMask;
4865 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4866 SDValue Op = MaskNode->getOperand(i);
4867 if (Op->getOpcode() == ISD::UNDEF) {
4868 RawMask.push_back((uint64_t)SM_SentinelUndef);
4871 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4874 APInt MaskElement = CN->getAPIntValue();
4876 // We now have to decode the element which could be any integer size and
4877 // extract each byte of it.
4878 for (int j = 0; j < NumBytesPerElement; ++j) {
4879 // Note that this is x86 and so always little endian: the low byte is
4880 // the first byte of the mask.
4881 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4882 MaskElement = MaskElement.lshr(8);
4885 DecodePSHUFBMask(RawMask, Mask);
4889 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4893 SDValue Ptr = MaskLoad->getBasePtr();
4894 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4895 Ptr->getOpcode() == X86ISD::WrapperRIP)
4896 Ptr = Ptr->getOperand(0);
4898 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4899 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4902 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4903 DecodePSHUFBMask(C, Mask);
4909 case X86ISD::VPERMI:
4910 ImmN = N->getOperand(N->getNumOperands()-1);
4911 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4916 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4918 case X86ISD::VPERM2X128:
4919 ImmN = N->getOperand(N->getNumOperands()-1);
4920 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4921 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4923 case X86ISD::MOVSLDUP:
4924 DecodeMOVSLDUPMask(VT, Mask);
4927 case X86ISD::MOVSHDUP:
4928 DecodeMOVSHDUPMask(VT, Mask);
4931 case X86ISD::MOVDDUP:
4932 DecodeMOVDDUPMask(VT, Mask);
4935 case X86ISD::MOVLHPD:
4936 case X86ISD::MOVLPD:
4937 case X86ISD::MOVLPS:
4938 // Not yet implemented
4940 case X86ISD::VPERMV: {
4942 SDValue MaskNode = N->getOperand(0);
4943 while (MaskNode->getOpcode() == ISD::BITCAST)
4944 MaskNode = MaskNode->getOperand(0);
4946 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4947 SmallVector<uint64_t, 32> RawMask;
4948 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4949 // If we have a build-vector, then things are easy.
4950 assert(MaskNode.getSimpleValueType().isInteger() &&
4951 MaskNode.getSimpleValueType().getVectorNumElements() ==
4952 VT.getVectorNumElements());
4954 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4955 SDValue Op = MaskNode->getOperand(i);
4956 if (Op->getOpcode() == ISD::UNDEF)
4957 RawMask.push_back((uint64_t)SM_SentinelUndef);
4958 else if (isa<ConstantSDNode>(Op)) {
4959 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4960 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4964 DecodeVPERMVMask(RawMask, Mask);
4967 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4968 unsigned NumEltsInMask = MaskNode->getNumOperands();
4969 MaskNode = MaskNode->getOperand(0);
4970 if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4971 APInt MaskEltValue = CN->getAPIntValue();
4972 for (unsigned i = 0; i < NumEltsInMask; ++i)
4973 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4974 DecodeVPERMVMask(RawMask, Mask);
4977 // It may be a scalar load
4980 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4984 SDValue Ptr = MaskLoad->getBasePtr();
4985 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4986 Ptr->getOpcode() == X86ISD::WrapperRIP)
4987 Ptr = Ptr->getOperand(0);
4989 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4990 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4993 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4994 DecodeVPERMVMask(C, VT, Mask);
4999 case X86ISD::VPERMV3: {
5001 SDValue MaskNode = N->getOperand(1);
5002 while (MaskNode->getOpcode() == ISD::BITCAST)
5003 MaskNode = MaskNode->getOperand(1);
5005 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5006 // If we have a build-vector, then things are easy.
5007 assert(MaskNode.getSimpleValueType().isInteger() &&
5008 MaskNode.getSimpleValueType().getVectorNumElements() ==
5009 VT.getVectorNumElements());
5011 SmallVector<uint64_t, 32> RawMask;
5012 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
5014 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
5015 SDValue Op = MaskNode->getOperand(i);
5016 if (Op->getOpcode() == ISD::UNDEF)
5017 RawMask.push_back((uint64_t)SM_SentinelUndef);
5019 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5022 APInt MaskElement = CN->getAPIntValue();
5023 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
5026 DecodeVPERMV3Mask(RawMask, Mask);
5030 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5034 SDValue Ptr = MaskLoad->getBasePtr();
5035 if (Ptr->getOpcode() == X86ISD::Wrapper ||
5036 Ptr->getOpcode() == X86ISD::WrapperRIP)
5037 Ptr = Ptr->getOperand(0);
5039 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5040 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5043 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5044 DecodeVPERMV3Mask(C, VT, Mask);
5049 default: llvm_unreachable("unknown target shuffle node");
5052 // Empty mask indicates the decode failed.
5056 // Check if we're getting a shuffle mask with zero'd elements.
5057 if (!AllowSentinelZero)
5058 if (std::any_of(Mask.begin(), Mask.end(),
5059 [](int M){ return M == SM_SentinelZero; }))
5062 // If we have a fake unary shuffle, the shuffle mask is spread across two
5063 // inputs that are actually the same node. Re-map the mask to always point
5064 // into the first input.
5067 if (M >= (int)Mask.size())
5073 /// Returns the scalar element that will make up the ith
5074 /// element of the result of the vector shuffle.
5075 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5078 return SDValue(); // Limit search depth.
5080 SDValue V = SDValue(N, 0);
5081 EVT VT = V.getValueType();
5082 unsigned Opcode = V.getOpcode();
5084 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5085 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5086 int Elt = SV->getMaskElt(Index);
5089 return DAG.getUNDEF(VT.getVectorElementType());
5091 unsigned NumElems = VT.getVectorNumElements();
5092 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5093 : SV->getOperand(1);
5094 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5097 // Recurse into target specific vector shuffles to find scalars.
5098 if (isTargetShuffle(Opcode)) {
5099 MVT ShufVT = V.getSimpleValueType();
5100 int NumElems = (int)ShufVT.getVectorNumElements();
5101 SmallVector<int, 16> ShuffleMask;
5104 if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5107 int Elt = ShuffleMask[Index];
5108 if (Elt == SM_SentinelUndef)
5109 return DAG.getUNDEF(ShufVT.getVectorElementType());
5111 assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5112 SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5113 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5117 // Actual nodes that may contain scalar elements
5118 if (Opcode == ISD::BITCAST) {
5119 V = V.getOperand(0);
5120 EVT SrcVT = V.getValueType();
5121 unsigned NumElems = VT.getVectorNumElements();
5123 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5127 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5128 return (Index == 0) ? V.getOperand(0)
5129 : DAG.getUNDEF(VT.getVectorElementType());
5131 if (V.getOpcode() == ISD::BUILD_VECTOR)
5132 return V.getOperand(Index);
5137 /// Custom lower build_vector of v16i8.
5138 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5139 unsigned NumNonZero, unsigned NumZero,
5141 const X86Subtarget* Subtarget,
5142 const TargetLowering &TLI) {
5150 // SSE4.1 - use PINSRB to insert each byte directly.
5151 if (Subtarget->hasSSE41()) {
5152 for (unsigned i = 0; i < 16; ++i) {
5153 bool isNonZero = (NonZeros & (1 << i)) != 0;
5157 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5159 V = DAG.getUNDEF(MVT::v16i8);
5162 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5163 MVT::v16i8, V, Op.getOperand(i),
5164 DAG.getIntPtrConstant(i, dl));
5171 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5172 for (unsigned i = 0; i < 16; ++i) {
5173 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5174 if (ThisIsNonZero && First) {
5176 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5178 V = DAG.getUNDEF(MVT::v8i16);
5183 SDValue ThisElt, LastElt;
5184 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5185 if (LastIsNonZero) {
5186 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5187 MVT::i16, Op.getOperand(i-1));
5189 if (ThisIsNonZero) {
5190 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5191 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5192 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5194 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5198 if (ThisElt.getNode())
5199 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5200 DAG.getIntPtrConstant(i/2, dl));
5204 return DAG.getBitcast(MVT::v16i8, V);
5207 /// Custom lower build_vector of v8i16.
5208 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5209 unsigned NumNonZero, unsigned NumZero,
5211 const X86Subtarget* Subtarget,
5212 const TargetLowering &TLI) {
5219 for (unsigned i = 0; i < 8; ++i) {
5220 bool isNonZero = (NonZeros & (1 << i)) != 0;
5224 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5226 V = DAG.getUNDEF(MVT::v8i16);
5229 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5230 MVT::v8i16, V, Op.getOperand(i),
5231 DAG.getIntPtrConstant(i, dl));
5238 /// Custom lower build_vector of v4i32 or v4f32.
5239 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5240 const X86Subtarget *Subtarget,
5241 const TargetLowering &TLI) {
5242 // Find all zeroable elements.
5243 std::bitset<4> Zeroable;
5244 for (int i=0; i < 4; ++i) {
5245 SDValue Elt = Op->getOperand(i);
5246 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5248 assert(Zeroable.size() - Zeroable.count() > 1 &&
5249 "We expect at least two non-zero elements!");
5251 // We only know how to deal with build_vector nodes where elements are either
5252 // zeroable or extract_vector_elt with constant index.
5253 SDValue FirstNonZero;
5254 unsigned FirstNonZeroIdx;
5255 for (unsigned i=0; i < 4; ++i) {
5258 SDValue Elt = Op->getOperand(i);
5259 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5260 !isa<ConstantSDNode>(Elt.getOperand(1)))
5262 // Make sure that this node is extracting from a 128-bit vector.
5263 MVT VT = Elt.getOperand(0).getSimpleValueType();
5264 if (!VT.is128BitVector())
5266 if (!FirstNonZero.getNode()) {
5268 FirstNonZeroIdx = i;
5272 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5273 SDValue V1 = FirstNonZero.getOperand(0);
5274 MVT VT = V1.getSimpleValueType();
5276 // See if this build_vector can be lowered as a blend with zero.
5278 unsigned EltMaskIdx, EltIdx;
5280 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5281 if (Zeroable[EltIdx]) {
5282 // The zero vector will be on the right hand side.
5283 Mask[EltIdx] = EltIdx+4;
5287 Elt = Op->getOperand(EltIdx);
5288 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5289 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5290 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5292 Mask[EltIdx] = EltIdx;
5296 // Let the shuffle legalizer deal with blend operations.
5297 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5298 if (V1.getSimpleValueType() != VT)
5299 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5300 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5303 // See if we can lower this build_vector to a INSERTPS.
5304 if (!Subtarget->hasSSE41())
5307 SDValue V2 = Elt.getOperand(0);
5308 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5311 bool CanFold = true;
5312 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5316 SDValue Current = Op->getOperand(i);
5317 SDValue SrcVector = Current->getOperand(0);
5320 CanFold = SrcVector == V1 &&
5321 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5327 assert(V1.getNode() && "Expected at least two non-zero elements!");
5328 if (V1.getSimpleValueType() != MVT::v4f32)
5329 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5330 if (V2.getSimpleValueType() != MVT::v4f32)
5331 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5333 // Ok, we can emit an INSERTPS instruction.
5334 unsigned ZMask = Zeroable.to_ulong();
5336 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5337 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5339 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5340 DAG.getIntPtrConstant(InsertPSMask, DL));
5341 return DAG.getBitcast(VT, Result);
5344 /// Return a vector logical shift node.
5345 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5346 unsigned NumBits, SelectionDAG &DAG,
5347 const TargetLowering &TLI, SDLoc dl) {
5348 assert(VT.is128BitVector() && "Unknown type for VShift");
5349 MVT ShVT = MVT::v2i64;
5350 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5351 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5352 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5353 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5354 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5355 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5359 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5361 // Check if the scalar load can be widened into a vector load. And if
5362 // the address is "base + cst" see if the cst can be "absorbed" into
5363 // the shuffle mask.
5364 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5365 SDValue Ptr = LD->getBasePtr();
5366 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5368 EVT PVT = LD->getValueType(0);
5369 if (PVT != MVT::i32 && PVT != MVT::f32)
5374 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5375 FI = FINode->getIndex();
5377 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5378 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5379 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5380 Offset = Ptr.getConstantOperandVal(1);
5381 Ptr = Ptr.getOperand(0);
5386 // FIXME: 256-bit vector instructions don't require a strict alignment,
5387 // improve this code to support it better.
5388 unsigned RequiredAlign = VT.getSizeInBits()/8;
5389 SDValue Chain = LD->getChain();
5390 // Make sure the stack object alignment is at least 16 or 32.
5391 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5392 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5393 if (MFI->isFixedObjectIndex(FI)) {
5394 // Can't change the alignment. FIXME: It's possible to compute
5395 // the exact stack offset and reference FI + adjust offset instead.
5396 // If someone *really* cares about this. That's the way to implement it.
5399 MFI->setObjectAlignment(FI, RequiredAlign);
5403 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5404 // Ptr + (Offset & ~15).
5407 if ((Offset % RequiredAlign) & 3)
5409 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5412 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5413 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5416 int EltNo = (Offset - StartOffset) >> 2;
5417 unsigned NumElems = VT.getVectorNumElements();
5419 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5420 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5421 LD->getPointerInfo().getWithOffset(StartOffset),
5422 false, false, false, 0);
5424 SmallVector<int, 8> Mask(NumElems, EltNo);
5426 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5432 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5433 /// elements can be replaced by a single large load which has the same value as
5434 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5436 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5438 /// FIXME: we'd also like to handle the case where the last elements are zero
5439 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5440 /// There's even a handy isZeroNode for that purpose.
5441 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5442 SDLoc &DL, SelectionDAG &DAG,
5443 bool isAfterLegalize) {
5444 unsigned NumElems = Elts.size();
5446 LoadSDNode *LDBase = nullptr;
5447 unsigned LastLoadedElt = -1U;
5449 // For each element in the initializer, see if we've found a load or an undef.
5450 // If we don't find an initial load element, or later load elements are
5451 // non-consecutive, bail out.
5452 for (unsigned i = 0; i < NumElems; ++i) {
5453 SDValue Elt = Elts[i];
5454 // Look through a bitcast.
5455 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5456 Elt = Elt.getOperand(0);
5457 if (!Elt.getNode() ||
5458 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5461 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5463 LDBase = cast<LoadSDNode>(Elt.getNode());
5467 if (Elt.getOpcode() == ISD::UNDEF)
5470 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5471 EVT LdVT = Elt.getValueType();
5472 // Each loaded element must be the correct fractional portion of the
5473 // requested vector load.
5474 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5476 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5481 // If we have found an entire vector of loads and undefs, then return a large
5482 // load of the entire vector width starting at the base pointer. If we found
5483 // consecutive loads for the low half, generate a vzext_load node.
5484 if (LastLoadedElt == NumElems - 1) {
5485 assert(LDBase && "Did not find base load for merging consecutive loads");
5486 EVT EltVT = LDBase->getValueType(0);
5487 // Ensure that the input vector size for the merged loads matches the
5488 // cumulative size of the input elements.
5489 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5492 if (isAfterLegalize &&
5493 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5496 SDValue NewLd = SDValue();
5498 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5499 LDBase->getPointerInfo(), LDBase->isVolatile(),
5500 LDBase->isNonTemporal(), LDBase->isInvariant(),
5501 LDBase->getAlignment());
5503 if (LDBase->hasAnyUseOfValue(1)) {
5504 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5506 SDValue(NewLd.getNode(), 1));
5507 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5508 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5509 SDValue(NewLd.getNode(), 1));
5515 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5516 //of a v4i32 / v4f32. It's probably worth generalizing.
5517 EVT EltVT = VT.getVectorElementType();
5518 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5519 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5520 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5521 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5523 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5524 LDBase->getPointerInfo(),
5525 LDBase->getAlignment(),
5526 false/*isVolatile*/, true/*ReadMem*/,
5529 // Make sure the newly-created LOAD is in the same position as LDBase in
5530 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5531 // update uses of LDBase's output chain to use the TokenFactor.
5532 if (LDBase->hasAnyUseOfValue(1)) {
5533 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5534 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5535 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5536 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5537 SDValue(ResNode.getNode(), 1));
5540 return DAG.getBitcast(VT, ResNode);
5545 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5546 /// to generate a splat value for the following cases:
5547 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5548 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5549 /// a scalar load, or a constant.
5550 /// The VBROADCAST node is returned when a pattern is found,
5551 /// or SDValue() otherwise.
5552 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5553 SelectionDAG &DAG) {
5554 // VBROADCAST requires AVX.
5555 // TODO: Splats could be generated for non-AVX CPUs using SSE
5556 // instructions, but there's less potential gain for only 128-bit vectors.
5557 if (!Subtarget->hasAVX())
5560 MVT VT = Op.getSimpleValueType();
5563 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5564 "Unsupported vector type for broadcast.");
5569 switch (Op.getOpcode()) {
5571 // Unknown pattern found.
5574 case ISD::BUILD_VECTOR: {
5575 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5576 BitVector UndefElements;
5577 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5579 // We need a splat of a single value to use broadcast, and it doesn't
5580 // make any sense if the value is only in one element of the vector.
5581 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5585 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5586 Ld.getOpcode() == ISD::ConstantFP);
5588 // Make sure that all of the users of a non-constant load are from the
5589 // BUILD_VECTOR node.
5590 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5595 case ISD::VECTOR_SHUFFLE: {
5596 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5598 // Shuffles must have a splat mask where the first element is
5600 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5603 SDValue Sc = Op.getOperand(0);
5604 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5605 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5607 if (!Subtarget->hasInt256())
5610 // Use the register form of the broadcast instruction available on AVX2.
5611 if (VT.getSizeInBits() >= 256)
5612 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5613 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5616 Ld = Sc.getOperand(0);
5617 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5618 Ld.getOpcode() == ISD::ConstantFP);
5620 // The scalar_to_vector node and the suspected
5621 // load node must have exactly one user.
5622 // Constants may have multiple users.
5624 // AVX-512 has register version of the broadcast
5625 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5626 Ld.getValueType().getSizeInBits() >= 32;
5627 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5634 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5635 bool IsGE256 = (VT.getSizeInBits() >= 256);
5637 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5638 // instruction to save 8 or more bytes of constant pool data.
5639 // TODO: If multiple splats are generated to load the same constant,
5640 // it may be detrimental to overall size. There needs to be a way to detect
5641 // that condition to know if this is truly a size win.
5642 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5644 // Handle broadcasting a single constant scalar from the constant pool
5646 // On Sandybridge (no AVX2), it is still better to load a constant vector
5647 // from the constant pool and not to broadcast it from a scalar.
5648 // But override that restriction when optimizing for size.
5649 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5650 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5651 EVT CVT = Ld.getValueType();
5652 assert(!CVT.isVector() && "Must not broadcast a vector type");
5654 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5655 // For size optimization, also splat v2f64 and v2i64, and for size opt
5656 // with AVX2, also splat i8 and i16.
5657 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5658 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5659 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5660 const Constant *C = nullptr;
5661 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5662 C = CI->getConstantIntValue();
5663 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5664 C = CF->getConstantFPValue();
5666 assert(C && "Invalid constant type");
5668 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5670 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5671 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5673 CVT, dl, DAG.getEntryNode(), CP,
5674 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5675 false, false, Alignment);
5677 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5681 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5683 // Handle AVX2 in-register broadcasts.
5684 if (!IsLoad && Subtarget->hasInt256() &&
5685 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5686 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5688 // The scalar source must be a normal load.
5692 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5693 (Subtarget->hasVLX() && ScalarSize == 64))
5694 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5696 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5697 // double since there is no vbroadcastsd xmm
5698 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5699 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5700 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5703 // Unsupported broadcast.
5707 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5708 /// underlying vector and index.
5710 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5712 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5714 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5715 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5718 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5720 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5722 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5723 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5726 // In this case the vector is the extract_subvector expression and the index
5727 // is 2, as specified by the shuffle.
5728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5729 SDValue ShuffleVec = SVOp->getOperand(0);
5730 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5731 assert(ShuffleVecVT.getVectorElementType() ==
5732 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5734 int ShuffleIdx = SVOp->getMaskElt(Idx);
5735 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5736 ExtractedFromVec = ShuffleVec;
5742 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5743 MVT VT = Op.getSimpleValueType();
5745 // Skip if insert_vec_elt is not supported.
5746 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5747 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5751 unsigned NumElems = Op.getNumOperands();
5755 SmallVector<unsigned, 4> InsertIndices;
5756 SmallVector<int, 8> Mask(NumElems, -1);
5758 for (unsigned i = 0; i != NumElems; ++i) {
5759 unsigned Opc = Op.getOperand(i).getOpcode();
5761 if (Opc == ISD::UNDEF)
5764 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5765 // Quit if more than 1 elements need inserting.
5766 if (InsertIndices.size() > 1)
5769 InsertIndices.push_back(i);
5773 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5774 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5775 // Quit if non-constant index.
5776 if (!isa<ConstantSDNode>(ExtIdx))
5778 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5780 // Quit if extracted from vector of different type.
5781 if (ExtractedFromVec.getValueType() != VT)
5784 if (!VecIn1.getNode())
5785 VecIn1 = ExtractedFromVec;
5786 else if (VecIn1 != ExtractedFromVec) {
5787 if (!VecIn2.getNode())
5788 VecIn2 = ExtractedFromVec;
5789 else if (VecIn2 != ExtractedFromVec)
5790 // Quit if more than 2 vectors to shuffle
5794 if (ExtractedFromVec == VecIn1)
5796 else if (ExtractedFromVec == VecIn2)
5797 Mask[i] = Idx + NumElems;
5800 if (!VecIn1.getNode())
5803 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5804 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5805 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5806 unsigned Idx = InsertIndices[i];
5807 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5808 DAG.getIntPtrConstant(Idx, DL));
5814 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5815 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5816 Op.getScalarValueSizeInBits() == 1 &&
5817 "Can not convert non-constant vector");
5818 uint64_t Immediate = 0;
5819 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5820 SDValue In = Op.getOperand(idx);
5821 if (In.getOpcode() != ISD::UNDEF)
5822 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5826 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5827 return DAG.getConstant(Immediate, dl, VT);
5829 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5831 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5833 MVT VT = Op.getSimpleValueType();
5834 assert((VT.getVectorElementType() == MVT::i1) &&
5835 "Unexpected type in LowerBUILD_VECTORvXi1!");
5838 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5839 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5840 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5841 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5844 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5845 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5846 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5847 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5850 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5851 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5852 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5853 return DAG.getBitcast(VT, Imm);
5854 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5855 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5856 DAG.getIntPtrConstant(0, dl));
5859 // Vector has one or more non-const elements
5860 uint64_t Immediate = 0;
5861 SmallVector<unsigned, 16> NonConstIdx;
5862 bool IsSplat = true;
5863 bool HasConstElts = false;
5865 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5866 SDValue In = Op.getOperand(idx);
5867 if (In.getOpcode() == ISD::UNDEF)
5869 if (!isa<ConstantSDNode>(In))
5870 NonConstIdx.push_back(idx);
5872 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5873 HasConstElts = true;
5877 else if (In != Op.getOperand(SplatIdx))
5881 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5883 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5884 DAG.getConstant(1, dl, VT),
5885 DAG.getConstant(0, dl, VT));
5887 // insert elements one by one
5891 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5892 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5894 else if (HasConstElts)
5895 Imm = DAG.getConstant(0, dl, VT);
5897 Imm = DAG.getUNDEF(VT);
5898 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5899 DstVec = DAG.getBitcast(VT, Imm);
5901 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5902 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5903 DAG.getIntPtrConstant(0, dl));
5906 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5907 unsigned InsertIdx = NonConstIdx[i];
5908 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5909 Op.getOperand(InsertIdx),
5910 DAG.getIntPtrConstant(InsertIdx, dl));
5915 /// \brief Return true if \p N implements a horizontal binop and return the
5916 /// operands for the horizontal binop into V0 and V1.
5918 /// This is a helper function of LowerToHorizontalOp().
5919 /// This function checks that the build_vector \p N in input implements a
5920 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5921 /// operation to match.
5922 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5923 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5924 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5927 /// This function only analyzes elements of \p N whose indices are
5928 /// in range [BaseIdx, LastIdx).
5929 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5931 unsigned BaseIdx, unsigned LastIdx,
5932 SDValue &V0, SDValue &V1) {
5933 EVT VT = N->getValueType(0);
5935 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5936 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5937 "Invalid Vector in input!");
5939 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5940 bool CanFold = true;
5941 unsigned ExpectedVExtractIdx = BaseIdx;
5942 unsigned NumElts = LastIdx - BaseIdx;
5943 V0 = DAG.getUNDEF(VT);
5944 V1 = DAG.getUNDEF(VT);
5946 // Check if N implements a horizontal binop.
5947 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5948 SDValue Op = N->getOperand(i + BaseIdx);
5951 if (Op->getOpcode() == ISD::UNDEF) {
5952 // Update the expected vector extract index.
5953 if (i * 2 == NumElts)
5954 ExpectedVExtractIdx = BaseIdx;
5955 ExpectedVExtractIdx += 2;
5959 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5964 SDValue Op0 = Op.getOperand(0);
5965 SDValue Op1 = Op.getOperand(1);
5967 // Try to match the following pattern:
5968 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5969 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5970 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5971 Op0.getOperand(0) == Op1.getOperand(0) &&
5972 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5973 isa<ConstantSDNode>(Op1.getOperand(1)));
5977 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5978 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5980 if (i * 2 < NumElts) {
5981 if (V0.getOpcode() == ISD::UNDEF) {
5982 V0 = Op0.getOperand(0);
5983 if (V0.getValueType() != VT)
5987 if (V1.getOpcode() == ISD::UNDEF) {
5988 V1 = Op0.getOperand(0);
5989 if (V1.getValueType() != VT)
5992 if (i * 2 == NumElts)
5993 ExpectedVExtractIdx = BaseIdx;
5996 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5997 if (I0 == ExpectedVExtractIdx)
5998 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5999 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6000 // Try to match the following dag sequence:
6001 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6002 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6006 ExpectedVExtractIdx += 2;
6012 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6013 /// a concat_vector.
6015 /// This is a helper function of LowerToHorizontalOp().
6016 /// This function expects two 256-bit vectors called V0 and V1.
6017 /// At first, each vector is split into two separate 128-bit vectors.
6018 /// Then, the resulting 128-bit vectors are used to implement two
6019 /// horizontal binary operations.
6021 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6023 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6024 /// the two new horizontal binop.
6025 /// When Mode is set, the first horizontal binop dag node would take as input
6026 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6027 /// horizontal binop dag node would take as input the lower 128-bit of V1
6028 /// and the upper 128-bit of V1.
6030 /// HADD V0_LO, V0_HI
6031 /// HADD V1_LO, V1_HI
6033 /// Otherwise, the first horizontal binop dag node takes as input the lower
6034 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6035 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
6037 /// HADD V0_LO, V1_LO
6038 /// HADD V0_HI, V1_HI
6040 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6041 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6042 /// the upper 128-bits of the result.
6043 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6044 SDLoc DL, SelectionDAG &DAG,
6045 unsigned X86Opcode, bool Mode,
6046 bool isUndefLO, bool isUndefHI) {
6047 EVT VT = V0.getValueType();
6048 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6049 "Invalid nodes in input!");
6051 unsigned NumElts = VT.getVectorNumElements();
6052 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6053 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6054 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6055 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6056 EVT NewVT = V0_LO.getValueType();
6058 SDValue LO = DAG.getUNDEF(NewVT);
6059 SDValue HI = DAG.getUNDEF(NewVT);
6062 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6063 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6064 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6065 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6066 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6068 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6069 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6070 V1_LO->getOpcode() != ISD::UNDEF))
6071 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6073 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6074 V1_HI->getOpcode() != ISD::UNDEF))
6075 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6078 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6081 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6083 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6084 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6085 MVT VT = BV->getSimpleValueType(0);
6086 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6087 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6091 unsigned NumElts = VT.getVectorNumElements();
6092 SDValue InVec0 = DAG.getUNDEF(VT);
6093 SDValue InVec1 = DAG.getUNDEF(VT);
6095 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6096 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6098 // Odd-numbered elements in the input build vector are obtained from
6099 // adding two integer/float elements.
6100 // Even-numbered elements in the input build vector are obtained from
6101 // subtracting two integer/float elements.
6102 unsigned ExpectedOpcode = ISD::FSUB;
6103 unsigned NextExpectedOpcode = ISD::FADD;
6104 bool AddFound = false;
6105 bool SubFound = false;
6107 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6108 SDValue Op = BV->getOperand(i);
6110 // Skip 'undef' values.
6111 unsigned Opcode = Op.getOpcode();
6112 if (Opcode == ISD::UNDEF) {
6113 std::swap(ExpectedOpcode, NextExpectedOpcode);
6117 // Early exit if we found an unexpected opcode.
6118 if (Opcode != ExpectedOpcode)
6121 SDValue Op0 = Op.getOperand(0);
6122 SDValue Op1 = Op.getOperand(1);
6124 // Try to match the following pattern:
6125 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6126 // Early exit if we cannot match that sequence.
6127 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6128 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6129 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6130 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6131 Op0.getOperand(1) != Op1.getOperand(1))
6134 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6138 // We found a valid add/sub node. Update the information accordingly.
6144 // Update InVec0 and InVec1.
6145 if (InVec0.getOpcode() == ISD::UNDEF) {
6146 InVec0 = Op0.getOperand(0);
6147 if (InVec0.getSimpleValueType() != VT)
6150 if (InVec1.getOpcode() == ISD::UNDEF) {
6151 InVec1 = Op1.getOperand(0);
6152 if (InVec1.getSimpleValueType() != VT)
6156 // Make sure that operands in input to each add/sub node always
6157 // come from a same pair of vectors.
6158 if (InVec0 != Op0.getOperand(0)) {
6159 if (ExpectedOpcode == ISD::FSUB)
6162 // FADD is commutable. Try to commute the operands
6163 // and then test again.
6164 std::swap(Op0, Op1);
6165 if (InVec0 != Op0.getOperand(0))
6169 if (InVec1 != Op1.getOperand(0))
6172 // Update the pair of expected opcodes.
6173 std::swap(ExpectedOpcode, NextExpectedOpcode);
6176 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6177 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6178 InVec1.getOpcode() != ISD::UNDEF)
6179 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6184 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6185 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6186 const X86Subtarget *Subtarget,
6187 SelectionDAG &DAG) {
6188 MVT VT = BV->getSimpleValueType(0);
6189 unsigned NumElts = VT.getVectorNumElements();
6190 unsigned NumUndefsLO = 0;
6191 unsigned NumUndefsHI = 0;
6192 unsigned Half = NumElts/2;
6194 // Count the number of UNDEF operands in the build_vector in input.
6195 for (unsigned i = 0, e = Half; i != e; ++i)
6196 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6199 for (unsigned i = Half, e = NumElts; i != e; ++i)
6200 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6203 // Early exit if this is either a build_vector of all UNDEFs or all the
6204 // operands but one are UNDEF.
6205 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6209 SDValue InVec0, InVec1;
6210 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6211 // Try to match an SSE3 float HADD/HSUB.
6212 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6213 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6215 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6216 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6217 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6218 // Try to match an SSSE3 integer HADD/HSUB.
6219 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6220 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6222 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6223 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6226 if (!Subtarget->hasAVX())
6229 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6230 // Try to match an AVX horizontal add/sub of packed single/double
6231 // precision floating point values from 256-bit vectors.
6232 SDValue InVec2, InVec3;
6233 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6234 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6235 ((InVec0.getOpcode() == ISD::UNDEF ||
6236 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6237 ((InVec1.getOpcode() == ISD::UNDEF ||
6238 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6239 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6241 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6242 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6243 ((InVec0.getOpcode() == ISD::UNDEF ||
6244 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6245 ((InVec1.getOpcode() == ISD::UNDEF ||
6246 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6247 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6248 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6249 // Try to match an AVX2 horizontal add/sub of signed integers.
6250 SDValue InVec2, InVec3;
6252 bool CanFold = true;
6254 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6255 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6256 ((InVec0.getOpcode() == ISD::UNDEF ||
6257 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6258 ((InVec1.getOpcode() == ISD::UNDEF ||
6259 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6260 X86Opcode = X86ISD::HADD;
6261 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6262 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6263 ((InVec0.getOpcode() == ISD::UNDEF ||
6264 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6265 ((InVec1.getOpcode() == ISD::UNDEF ||
6266 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6267 X86Opcode = X86ISD::HSUB;
6272 // Fold this build_vector into a single horizontal add/sub.
6273 // Do this only if the target has AVX2.
6274 if (Subtarget->hasAVX2())
6275 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6277 // Do not try to expand this build_vector into a pair of horizontal
6278 // add/sub if we can emit a pair of scalar add/sub.
6279 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6282 // Convert this build_vector into a pair of horizontal binop followed by
6284 bool isUndefLO = NumUndefsLO == Half;
6285 bool isUndefHI = NumUndefsHI == Half;
6286 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6287 isUndefLO, isUndefHI);
6291 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6292 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6294 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6295 X86Opcode = X86ISD::HADD;
6296 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6297 X86Opcode = X86ISD::HSUB;
6298 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6299 X86Opcode = X86ISD::FHADD;
6300 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6301 X86Opcode = X86ISD::FHSUB;
6305 // Don't try to expand this build_vector into a pair of horizontal add/sub
6306 // if we can simply emit a pair of scalar add/sub.
6307 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6310 // Convert this build_vector into two horizontal add/sub followed by
6312 bool isUndefLO = NumUndefsLO == Half;
6313 bool isUndefHI = NumUndefsHI == Half;
6314 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6315 isUndefLO, isUndefHI);
6322 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6325 MVT VT = Op.getSimpleValueType();
6326 MVT ExtVT = VT.getVectorElementType();
6327 unsigned NumElems = Op.getNumOperands();
6329 // Generate vectors for predicate vectors.
6330 if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6331 return LowerBUILD_VECTORvXi1(Op, DAG);
6333 // Vectors containing all zeros can be matched by pxor and xorps later
6334 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6335 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6336 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6337 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6340 return getZeroVector(VT, Subtarget, DAG, dl);
6343 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6344 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6345 // vpcmpeqd on 256-bit vectors.
6346 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6347 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6350 if (!VT.is512BitVector())
6351 return getOnesVector(VT, Subtarget, DAG, dl);
6354 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6355 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6357 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6358 return HorizontalOp;
6359 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6362 unsigned EVTBits = ExtVT.getSizeInBits();
6364 unsigned NumZero = 0;
6365 unsigned NumNonZero = 0;
6366 uint64_t NonZeros = 0;
6367 bool IsAllConstants = true;
6368 SmallSet<SDValue, 8> Values;
6369 for (unsigned i = 0; i < NumElems; ++i) {
6370 SDValue Elt = Op.getOperand(i);
6371 if (Elt.getOpcode() == ISD::UNDEF)
6374 if (Elt.getOpcode() != ISD::Constant &&
6375 Elt.getOpcode() != ISD::ConstantFP)
6376 IsAllConstants = false;
6377 if (X86::isZeroNode(Elt))
6380 assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6381 NonZeros |= ((uint64_t)1 << i);
6386 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6387 if (NumNonZero == 0)
6388 return DAG.getUNDEF(VT);
6390 // Special case for single non-zero, non-undef, element.
6391 if (NumNonZero == 1) {
6392 unsigned Idx = countTrailingZeros(NonZeros);
6393 SDValue Item = Op.getOperand(Idx);
6395 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6396 // the value are obviously zero, truncate the value to i32 and do the
6397 // insertion that way. Only do this if the value is non-constant or if the
6398 // value is a constant being inserted into element 0. It is cheaper to do
6399 // a constant pool load than it is to do a movd + shuffle.
6400 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6401 (!IsAllConstants || Idx == 0)) {
6402 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6404 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6405 MVT VecVT = MVT::v4i32;
6407 // Truncate the value (which may itself be a constant) to i32, and
6408 // convert it to a vector with movd (S2V+shuffle to zero extend).
6409 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6410 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6411 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6412 Item, Idx * 2, true, Subtarget, DAG));
6416 // If we have a constant or non-constant insertion into the low element of
6417 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6418 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6419 // depending on what the source datatype is.
6422 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6424 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6425 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6426 if (VT.is512BitVector()) {
6427 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6428 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6429 Item, DAG.getIntPtrConstant(0, dl));
6431 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6432 "Expected an SSE value type!");
6433 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6434 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6435 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6438 // We can't directly insert an i8 or i16 into a vector, so zero extend
6440 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6441 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6442 if (VT.is256BitVector()) {
6443 if (Subtarget->hasAVX()) {
6444 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6445 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6447 // Without AVX, we need to extend to a 128-bit vector and then
6448 // insert into the 256-bit vector.
6449 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6450 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6451 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6454 assert(VT.is128BitVector() && "Expected an SSE value type!");
6455 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6456 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6458 return DAG.getBitcast(VT, Item);
6462 // Is it a vector logical left shift?
6463 if (NumElems == 2 && Idx == 1 &&
6464 X86::isZeroNode(Op.getOperand(0)) &&
6465 !X86::isZeroNode(Op.getOperand(1))) {
6466 unsigned NumBits = VT.getSizeInBits();
6467 return getVShift(true, VT,
6468 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6469 VT, Op.getOperand(1)),
6470 NumBits/2, DAG, *this, dl);
6473 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6476 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6477 // is a non-constant being inserted into an element other than the low one,
6478 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6479 // movd/movss) to move this into the low element, then shuffle it into
6481 if (EVTBits == 32) {
6482 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6483 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6487 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6488 if (Values.size() == 1) {
6489 if (EVTBits == 32) {
6490 // Instead of a shuffle like this:
6491 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6492 // Check if it's possible to issue this instead.
6493 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6494 unsigned Idx = countTrailingZeros(NonZeros);
6495 SDValue Item = Op.getOperand(Idx);
6496 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6497 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6502 // A vector full of immediates; various special cases are already
6503 // handled, so this is best done with a single constant-pool load.
6507 // For AVX-length vectors, see if we can use a vector load to get all of the
6508 // elements, otherwise build the individual 128-bit pieces and use
6509 // shuffles to put them in place.
6510 if (VT.is256BitVector() || VT.is512BitVector()) {
6511 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6513 // Check for a build vector of consecutive loads.
6514 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6517 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6519 // Build both the lower and upper subvector.
6520 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6521 makeArrayRef(&V[0], NumElems/2));
6522 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6523 makeArrayRef(&V[NumElems / 2], NumElems/2));
6525 // Recreate the wider vector with the lower and upper part.
6526 if (VT.is256BitVector())
6527 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6528 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6531 // Let legalizer expand 2-wide build_vectors.
6532 if (EVTBits == 64) {
6533 if (NumNonZero == 1) {
6534 // One half is zero or undef.
6535 unsigned Idx = countTrailingZeros(NonZeros);
6536 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6537 Op.getOperand(Idx));
6538 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6543 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6544 if (EVTBits == 8 && NumElems == 16)
6545 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6546 DAG, Subtarget, *this))
6549 if (EVTBits == 16 && NumElems == 8)
6550 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6551 DAG, Subtarget, *this))
6554 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6555 if (EVTBits == 32 && NumElems == 4)
6556 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6559 // If element VT is == 32 bits, turn it into a number of shuffles.
6560 SmallVector<SDValue, 8> V(NumElems);
6561 if (NumElems == 4 && NumZero > 0) {
6562 for (unsigned i = 0; i < 4; ++i) {
6563 bool isZero = !(NonZeros & (1ULL << i));
6565 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6567 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6570 for (unsigned i = 0; i < 2; ++i) {
6571 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6574 V[i] = V[i*2]; // Must be a zero vector.
6577 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6580 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6583 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6588 bool Reverse1 = (NonZeros & 0x3) == 2;
6589 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6593 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6594 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6596 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6599 if (Values.size() > 1 && VT.is128BitVector()) {
6600 // Check for a build vector of consecutive loads.
6601 for (unsigned i = 0; i < NumElems; ++i)
6602 V[i] = Op.getOperand(i);
6604 // Check for elements which are consecutive loads.
6605 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6608 // Check for a build vector from mostly shuffle plus few inserting.
6609 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6612 // For SSE 4.1, use insertps to put the high elements into the low element.
6613 if (Subtarget->hasSSE41()) {
6615 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6616 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6618 Result = DAG.getUNDEF(VT);
6620 for (unsigned i = 1; i < NumElems; ++i) {
6621 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6622 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6623 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6628 // Otherwise, expand into a number of unpckl*, start by extending each of
6629 // our (non-undef) elements to the full vector width with the element in the
6630 // bottom slot of the vector (which generates no code for SSE).
6631 for (unsigned i = 0; i < NumElems; ++i) {
6632 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6633 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6635 V[i] = DAG.getUNDEF(VT);
6638 // Next, we iteratively mix elements, e.g. for v4f32:
6639 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6640 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6641 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6642 unsigned EltStride = NumElems >> 1;
6643 while (EltStride != 0) {
6644 for (unsigned i = 0; i < EltStride; ++i) {
6645 // If V[i+EltStride] is undef and this is the first round of mixing,
6646 // then it is safe to just drop this shuffle: V[i] is already in the
6647 // right place, the one element (since it's the first round) being
6648 // inserted as undef can be dropped. This isn't safe for successive
6649 // rounds because they will permute elements within both vectors.
6650 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6651 EltStride == NumElems/2)
6654 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6663 // 256-bit AVX can use the vinsertf128 instruction
6664 // to create 256-bit vectors from two other 128-bit ones.
6665 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6667 MVT ResVT = Op.getSimpleValueType();
6669 assert((ResVT.is256BitVector() ||
6670 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6672 SDValue V1 = Op.getOperand(0);
6673 SDValue V2 = Op.getOperand(1);
6674 unsigned NumElems = ResVT.getVectorNumElements();
6675 if (ResVT.is256BitVector())
6676 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6678 if (Op.getNumOperands() == 4) {
6679 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6680 ResVT.getVectorNumElements()/2);
6681 SDValue V3 = Op.getOperand(2);
6682 SDValue V4 = Op.getOperand(3);
6683 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6684 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6686 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6689 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6690 const X86Subtarget *Subtarget,
6691 SelectionDAG & DAG) {
6693 MVT ResVT = Op.getSimpleValueType();
6694 unsigned NumOfOperands = Op.getNumOperands();
6696 assert(isPowerOf2_32(NumOfOperands) &&
6697 "Unexpected number of operands in CONCAT_VECTORS");
6699 SDValue Undef = DAG.getUNDEF(ResVT);
6700 if (NumOfOperands > 2) {
6701 // Specialize the cases when all, or all but one, of the operands are undef.
6702 unsigned NumOfDefinedOps = 0;
6704 for (unsigned i = 0; i < NumOfOperands; i++)
6705 if (!Op.getOperand(i).isUndef()) {
6709 if (NumOfDefinedOps == 0)
6711 if (NumOfDefinedOps == 1) {
6712 unsigned SubVecNumElts =
6713 Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6714 SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6715 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6716 Op.getOperand(OpIdx), IdxVal);
6719 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6720 ResVT.getVectorNumElements()/2);
6721 SmallVector<SDValue, 2> Ops;
6722 for (unsigned i = 0; i < NumOfOperands/2; i++)
6723 Ops.push_back(Op.getOperand(i));
6724 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6726 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6727 Ops.push_back(Op.getOperand(i));
6728 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6729 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6733 SDValue V1 = Op.getOperand(0);
6734 SDValue V2 = Op.getOperand(1);
6735 unsigned NumElems = ResVT.getVectorNumElements();
6736 assert(V1.getValueType() == V2.getValueType() &&
6737 V1.getValueType().getVectorNumElements() == NumElems/2 &&
6738 "Unexpected operands in CONCAT_VECTORS");
6740 if (ResVT.getSizeInBits() >= 16)
6741 return Op; // The operation is legal with KUNPCK
6743 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6744 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6745 SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6746 if (IsZeroV1 && IsZeroV2)
6749 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6751 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6753 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6755 SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6757 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6760 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6762 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6763 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6766 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6767 const X86Subtarget *Subtarget,
6768 SelectionDAG &DAG) {
6769 MVT VT = Op.getSimpleValueType();
6770 if (VT.getVectorElementType() == MVT::i1)
6771 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6773 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6774 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6775 Op.getNumOperands() == 4)));
6777 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6778 // from two other 128-bit ones.
6780 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6781 return LowerAVXCONCAT_VECTORS(Op, DAG);
6784 //===----------------------------------------------------------------------===//
6785 // Vector shuffle lowering
6787 // This is an experimental code path for lowering vector shuffles on x86. It is
6788 // designed to handle arbitrary vector shuffles and blends, gracefully
6789 // degrading performance as necessary. It works hard to recognize idiomatic
6790 // shuffles and lower them to optimal instruction patterns without leaving
6791 // a framework that allows reasonably efficient handling of all vector shuffle
6793 //===----------------------------------------------------------------------===//
6795 /// \brief Tiny helper function to identify a no-op mask.
6797 /// This is a somewhat boring predicate function. It checks whether the mask
6798 /// array input, which is assumed to be a single-input shuffle mask of the kind
6799 /// used by the X86 shuffle instructions (not a fully general
6800 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6801 /// in-place shuffle are 'no-op's.
6802 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6803 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6804 if (Mask[i] != -1 && Mask[i] != i)
6809 /// \brief Helper function to classify a mask as a single-input mask.
6811 /// This isn't a generic single-input test because in the vector shuffle
6812 /// lowering we canonicalize single inputs to be the first input operand. This
6813 /// means we can more quickly test for a single input by only checking whether
6814 /// an input from the second operand exists. We also assume that the size of
6815 /// mask corresponds to the size of the input vectors which isn't true in the
6816 /// fully general case.
6817 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6819 if (M >= (int)Mask.size())
6824 /// \brief Test whether there are elements crossing 128-bit lanes in this
6827 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6828 /// and we routinely test for these.
6829 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6830 int LaneSize = 128 / VT.getScalarSizeInBits();
6831 int Size = Mask.size();
6832 for (int i = 0; i < Size; ++i)
6833 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6838 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6840 /// This checks a shuffle mask to see if it is performing the same
6841 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6842 /// that it is also not lane-crossing. It may however involve a blend from the
6843 /// same lane of a second vector.
6845 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6846 /// non-trivial to compute in the face of undef lanes. The representation is
6847 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6848 /// entries from both V1 and V2 inputs to the wider mask.
6850 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6851 SmallVectorImpl<int> &RepeatedMask) {
6852 int LaneSize = 128 / VT.getScalarSizeInBits();
6853 RepeatedMask.resize(LaneSize, -1);
6854 int Size = Mask.size();
6855 for (int i = 0; i < Size; ++i) {
6858 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6859 // This entry crosses lanes, so there is no way to model this shuffle.
6862 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6863 if (RepeatedMask[i % LaneSize] == -1)
6864 // This is the first non-undef entry in this slot of a 128-bit lane.
6865 RepeatedMask[i % LaneSize] =
6866 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6867 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6868 // Found a mismatch with the repeated mask.
6874 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6877 /// This is a fast way to test a shuffle mask against a fixed pattern:
6879 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6881 /// It returns true if the mask is exactly as wide as the argument list, and
6882 /// each element of the mask is either -1 (signifying undef) or the value given
6883 /// in the argument.
6884 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6885 ArrayRef<int> ExpectedMask) {
6886 if (Mask.size() != ExpectedMask.size())
6889 int Size = Mask.size();
6891 // If the values are build vectors, we can look through them to find
6892 // equivalent inputs that make the shuffles equivalent.
6893 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6894 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6896 for (int i = 0; i < Size; ++i)
6897 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6898 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6899 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6900 if (!MaskBV || !ExpectedBV ||
6901 MaskBV->getOperand(Mask[i] % Size) !=
6902 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6909 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6911 /// This helper function produces an 8-bit shuffle immediate corresponding to
6912 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6913 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6916 /// NB: We rely heavily on "undef" masks preserving the input lane.
6917 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6918 SelectionDAG &DAG) {
6919 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6920 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6921 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6922 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6923 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6926 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6927 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6928 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6929 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6930 return DAG.getConstant(Imm, DL, MVT::i8);
6933 /// \brief Compute whether each element of a shuffle is zeroable.
6935 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6936 /// Either it is an undef element in the shuffle mask, the element of the input
6937 /// referenced is undef, or the element of the input referenced is known to be
6938 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6939 /// as many lanes with this technique as possible to simplify the remaining
6941 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6942 SDValue V1, SDValue V2) {
6943 SmallBitVector Zeroable(Mask.size(), false);
6945 while (V1.getOpcode() == ISD::BITCAST)
6946 V1 = V1->getOperand(0);
6947 while (V2.getOpcode() == ISD::BITCAST)
6948 V2 = V2->getOperand(0);
6950 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6951 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6953 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6955 // Handle the easy cases.
6956 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6961 // If this is an index into a build_vector node (which has the same number
6962 // of elements), dig out the input value and use it.
6963 SDValue V = M < Size ? V1 : V2;
6964 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6967 SDValue Input = V.getOperand(M % Size);
6968 // The UNDEF opcode check really should be dead code here, but not quite
6969 // worth asserting on (it isn't invalid, just unexpected).
6970 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6977 // X86 has dedicated unpack instructions that can handle specific blend
6978 // operations: UNPCKH and UNPCKL.
6979 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6980 SDValue V1, SDValue V2,
6981 SelectionDAG &DAG) {
6982 int NumElts = VT.getVectorNumElements();
6983 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6984 SmallVector<int, 8> Unpckl;
6985 SmallVector<int, 8> Unpckh;
6987 for (int i = 0; i < NumElts; ++i) {
6988 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6989 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6990 int HiPos = LoPos + NumEltsInLane / 2;
6991 Unpckl.push_back(LoPos);
6992 Unpckh.push_back(HiPos);
6995 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6996 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6997 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6998 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
7000 // Commute and try again.
7001 ShuffleVectorSDNode::commuteMask(Unpckl);
7002 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
7003 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
7005 ShuffleVectorSDNode::commuteMask(Unpckh);
7006 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
7007 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
7012 /// \brief Try to emit a bitmask instruction for a shuffle.
7014 /// This handles cases where we can model a blend exactly as a bitmask due to
7015 /// one of the inputs being zeroable.
7016 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
7017 SDValue V2, ArrayRef<int> Mask,
7018 SelectionDAG &DAG) {
7019 MVT EltVT = VT.getVectorElementType();
7020 int NumEltBits = EltVT.getSizeInBits();
7021 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
7022 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
7023 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7025 if (EltVT.isFloatingPoint()) {
7026 Zero = DAG.getBitcast(EltVT, Zero);
7027 AllOnes = DAG.getBitcast(EltVT, AllOnes);
7029 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7030 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7032 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7035 if (Mask[i] % Size != i)
7036 return SDValue(); // Not a blend.
7038 V = Mask[i] < Size ? V1 : V2;
7039 else if (V != (Mask[i] < Size ? V1 : V2))
7040 return SDValue(); // Can only let one input through the mask.
7042 VMaskOps[i] = AllOnes;
7045 return SDValue(); // No non-zeroable elements!
7047 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7048 V = DAG.getNode(VT.isFloatingPoint()
7049 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7054 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7056 /// This is used as a fallback approach when first class blend instructions are
7057 /// unavailable. Currently it is only suitable for integer vectors, but could
7058 /// be generalized for floating point vectors if desirable.
7059 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7060 SDValue V2, ArrayRef<int> Mask,
7061 SelectionDAG &DAG) {
7062 assert(VT.isInteger() && "Only supports integer vector types!");
7063 MVT EltVT = VT.getVectorElementType();
7064 int NumEltBits = EltVT.getSizeInBits();
7065 SDValue Zero = DAG.getConstant(0, DL, EltVT);
7066 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7068 SmallVector<SDValue, 16> MaskOps;
7069 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7070 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7071 return SDValue(); // Shuffled input!
7072 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7075 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7076 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7077 // We have to cast V2 around.
7078 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7079 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7080 DAG.getBitcast(MaskVT, V1Mask),
7081 DAG.getBitcast(MaskVT, V2)));
7082 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7085 /// \brief Try to emit a blend instruction for a shuffle.
7087 /// This doesn't do any checks for the availability of instructions for blending
7088 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7089 /// be matched in the backend with the type given. What it does check for is
7090 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7091 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7092 SDValue V2, ArrayRef<int> Original,
7093 const X86Subtarget *Subtarget,
7094 SelectionDAG &DAG) {
7095 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7096 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7097 SmallVector<int, 8> Mask(Original.begin(), Original.end());
7098 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7099 bool ForceV1Zero = false, ForceV2Zero = false;
7101 // Attempt to generate the binary blend mask. If an input is zero then
7102 // we can use any lane.
7103 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7104 unsigned BlendMask = 0;
7105 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7111 if (M == i + Size) {
7112 BlendMask |= 1u << i;
7123 BlendMask |= 1u << i;
7128 return SDValue(); // Shuffled input!
7131 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7133 V1 = getZeroVector(VT, Subtarget, DAG, DL);
7135 V2 = getZeroVector(VT, Subtarget, DAG, DL);
7137 auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7138 unsigned ScaledMask = 0;
7139 for (int i = 0; i != Size; ++i)
7140 if (BlendMask & (1u << i))
7141 for (int j = 0; j != Scale; ++j)
7142 ScaledMask |= 1u << (i * Scale + j);
7146 switch (VT.SimpleTy) {
7151 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7152 DAG.getConstant(BlendMask, DL, MVT::i8));
7156 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7160 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7161 // that instruction.
7162 if (Subtarget->hasAVX2()) {
7163 // Scale the blend by the number of 32-bit dwords per element.
7164 int Scale = VT.getScalarSizeInBits() / 32;
7165 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7166 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7167 V1 = DAG.getBitcast(BlendVT, V1);
7168 V2 = DAG.getBitcast(BlendVT, V2);
7169 return DAG.getBitcast(
7170 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7171 DAG.getConstant(BlendMask, DL, MVT::i8)));
7175 // For integer shuffles we need to expand the mask and cast the inputs to
7176 // v8i16s prior to blending.
7177 int Scale = 8 / VT.getVectorNumElements();
7178 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7179 V1 = DAG.getBitcast(MVT::v8i16, V1);
7180 V2 = DAG.getBitcast(MVT::v8i16, V2);
7181 return DAG.getBitcast(VT,
7182 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7183 DAG.getConstant(BlendMask, DL, MVT::i8)));
7187 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7188 SmallVector<int, 8> RepeatedMask;
7189 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7190 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7191 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7193 for (int i = 0; i < 8; ++i)
7194 if (RepeatedMask[i] >= 16)
7195 BlendMask |= 1u << i;
7196 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7197 DAG.getConstant(BlendMask, DL, MVT::i8));
7203 assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7204 "256-bit byte-blends require AVX2 support!");
7206 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7207 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7210 // Scale the blend by the number of bytes per element.
7211 int Scale = VT.getScalarSizeInBits() / 8;
7213 // This form of blend is always done on bytes. Compute the byte vector
7215 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7217 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7218 // mix of LLVM's code generator and the x86 backend. We tell the code
7219 // generator that boolean values in the elements of an x86 vector register
7220 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7221 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7222 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7223 // of the element (the remaining are ignored) and 0 in that high bit would
7224 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7225 // the LLVM model for boolean values in vector elements gets the relevant
7226 // bit set, it is set backwards and over constrained relative to x86's
7228 SmallVector<SDValue, 32> VSELECTMask;
7229 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7230 for (int j = 0; j < Scale; ++j)
7231 VSELECTMask.push_back(
7232 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7233 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7236 V1 = DAG.getBitcast(BlendVT, V1);
7237 V2 = DAG.getBitcast(BlendVT, V2);
7238 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7239 DAG.getNode(ISD::BUILD_VECTOR, DL,
7240 BlendVT, VSELECTMask),
7245 llvm_unreachable("Not a supported integer vector type!");
7249 /// \brief Try to lower as a blend of elements from two inputs followed by
7250 /// a single-input permutation.
7252 /// This matches the pattern where we can blend elements from two inputs and
7253 /// then reduce the shuffle to a single-input permutation.
7254 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7257 SelectionDAG &DAG) {
7258 // We build up the blend mask while checking whether a blend is a viable way
7259 // to reduce the shuffle.
7260 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7261 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7263 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7267 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7269 if (BlendMask[Mask[i] % Size] == -1)
7270 BlendMask[Mask[i] % Size] = Mask[i];
7271 else if (BlendMask[Mask[i] % Size] != Mask[i])
7272 return SDValue(); // Can't blend in the needed input!
7274 PermuteMask[i] = Mask[i] % Size;
7277 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7278 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7281 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7282 /// blends and permutes.
7284 /// This matches the extremely common pattern for handling combined
7285 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7286 /// operations. It will try to pick the best arrangement of shuffles and
7288 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7292 SelectionDAG &DAG) {
7293 // Shuffle the input elements into the desired positions in V1 and V2 and
7294 // blend them together.
7295 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7296 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7297 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7298 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7299 if (Mask[i] >= 0 && Mask[i] < Size) {
7300 V1Mask[i] = Mask[i];
7302 } else if (Mask[i] >= Size) {
7303 V2Mask[i] = Mask[i] - Size;
7304 BlendMask[i] = i + Size;
7307 // Try to lower with the simpler initial blend strategy unless one of the
7308 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7309 // shuffle may be able to fold with a load or other benefit. However, when
7310 // we'll have to do 2x as many shuffles in order to achieve this, blending
7311 // first is a better strategy.
7312 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7313 if (SDValue BlendPerm =
7314 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7317 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7318 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7319 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7322 /// \brief Try to lower a vector shuffle as a byte rotation.
7324 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7325 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7326 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7327 /// try to generically lower a vector shuffle through such an pattern. It
7328 /// does not check for the profitability of lowering either as PALIGNR or
7329 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7330 /// This matches shuffle vectors that look like:
7332 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7334 /// Essentially it concatenates V1 and V2, shifts right by some number of
7335 /// elements, and takes the low elements as the result. Note that while this is
7336 /// specified as a *right shift* because x86 is little-endian, it is a *left
7337 /// rotate* of the vector lanes.
7338 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7341 const X86Subtarget *Subtarget,
7342 SelectionDAG &DAG) {
7343 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7345 int NumElts = Mask.size();
7346 int NumLanes = VT.getSizeInBits() / 128;
7347 int NumLaneElts = NumElts / NumLanes;
7349 // We need to detect various ways of spelling a rotation:
7350 // [11, 12, 13, 14, 15, 0, 1, 2]
7351 // [-1, 12, 13, 14, -1, -1, 1, -1]
7352 // [-1, -1, -1, -1, -1, -1, 1, 2]
7353 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7354 // [-1, 4, 5, 6, -1, -1, 9, -1]
7355 // [-1, 4, 5, 6, -1, -1, -1, -1]
7358 for (int l = 0; l < NumElts; l += NumLaneElts) {
7359 for (int i = 0; i < NumLaneElts; ++i) {
7360 if (Mask[l + i] == -1)
7362 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7364 // Get the mod-Size index and lane correct it.
7365 int LaneIdx = (Mask[l + i] % NumElts) - l;
7366 // Make sure it was in this lane.
7367 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7370 // Determine where a rotated vector would have started.
7371 int StartIdx = i - LaneIdx;
7373 // The identity rotation isn't interesting, stop.
7376 // If we found the tail of a vector the rotation must be the missing
7377 // front. If we found the head of a vector, it must be how much of the
7379 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7382 Rotation = CandidateRotation;
7383 else if (Rotation != CandidateRotation)
7384 // The rotations don't match, so we can't match this mask.
7387 // Compute which value this mask is pointing at.
7388 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7390 // Compute which of the two target values this index should be assigned
7391 // to. This reflects whether the high elements are remaining or the low
7392 // elements are remaining.
7393 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7395 // Either set up this value if we've not encountered it before, or check
7396 // that it remains consistent.
7399 else if (TargetV != MaskV)
7400 // This may be a rotation, but it pulls from the inputs in some
7401 // unsupported interleaving.
7406 // Check that we successfully analyzed the mask, and normalize the results.
7407 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7408 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7414 // The actual rotate instruction rotates bytes, so we need to scale the
7415 // rotation based on how many bytes are in the vector lane.
7416 int Scale = 16 / NumLaneElts;
7418 // SSSE3 targets can use the palignr instruction.
7419 if (Subtarget->hasSSSE3()) {
7420 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7421 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7422 Lo = DAG.getBitcast(AlignVT, Lo);
7423 Hi = DAG.getBitcast(AlignVT, Hi);
7425 return DAG.getBitcast(
7426 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7427 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7430 assert(VT.is128BitVector() &&
7431 "Rotate-based lowering only supports 128-bit lowering!");
7432 assert(Mask.size() <= 16 &&
7433 "Can shuffle at most 16 bytes in a 128-bit vector!");
7435 // Default SSE2 implementation
7436 int LoByteShift = 16 - Rotation * Scale;
7437 int HiByteShift = Rotation * Scale;
7439 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7440 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7441 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7443 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7444 DAG.getConstant(LoByteShift, DL, MVT::i8));
7445 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7446 DAG.getConstant(HiByteShift, DL, MVT::i8));
7447 return DAG.getBitcast(VT,
7448 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7451 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7453 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7454 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7455 /// matches elements from one of the input vectors shuffled to the left or
7456 /// right with zeroable elements 'shifted in'. It handles both the strictly
7457 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7460 /// PSHL : (little-endian) left bit shift.
7461 /// [ zz, 0, zz, 2 ]
7462 /// [ -1, 4, zz, -1 ]
7463 /// PSRL : (little-endian) right bit shift.
7465 /// [ -1, -1, 7, zz]
7466 /// PSLLDQ : (little-endian) left byte shift
7467 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7468 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7469 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7470 /// PSRLDQ : (little-endian) right byte shift
7471 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7472 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7473 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7474 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7475 SDValue V2, ArrayRef<int> Mask,
7476 SelectionDAG &DAG) {
7477 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7479 int Size = Mask.size();
7480 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7482 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7483 for (int i = 0; i < Size; i += Scale)
7484 for (int j = 0; j < Shift; ++j)
7485 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7491 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7492 for (int i = 0; i != Size; i += Scale) {
7493 unsigned Pos = Left ? i + Shift : i;
7494 unsigned Low = Left ? i : i + Shift;
7495 unsigned Len = Scale - Shift;
7496 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7497 Low + (V == V1 ? 0 : Size)))
7501 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7502 bool ByteShift = ShiftEltBits > 64;
7503 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7504 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7505 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7507 // Normalize the scale for byte shifts to still produce an i64 element
7509 Scale = ByteShift ? Scale / 2 : Scale;
7511 // We need to round trip through the appropriate type for the shift.
7512 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7513 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7514 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7515 "Illegal integer vector type");
7516 V = DAG.getBitcast(ShiftVT, V);
7518 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7519 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7520 return DAG.getBitcast(VT, V);
7523 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7524 // keep doubling the size of the integer elements up to that. We can
7525 // then shift the elements of the integer vector by whole multiples of
7526 // their width within the elements of the larger integer vector. Test each
7527 // multiple to see if we can find a match with the moved element indices
7528 // and that the shifted in elements are all zeroable.
7529 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7530 for (int Shift = 1; Shift != Scale; ++Shift)
7531 for (bool Left : {true, false})
7532 if (CheckZeros(Shift, Scale, Left))
7533 for (SDValue V : {V1, V2})
7534 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7541 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7542 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7543 SDValue V2, ArrayRef<int> Mask,
7544 SelectionDAG &DAG) {
7545 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7546 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7548 int Size = Mask.size();
7549 int HalfSize = Size / 2;
7550 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7552 // Upper half must be undefined.
7553 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7556 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7557 // Remainder of lower half result is zero and upper half is all undef.
7558 auto LowerAsEXTRQ = [&]() {
7559 // Determine the extraction length from the part of the
7560 // lower half that isn't zeroable.
7562 for (; Len > 0; --Len)
7563 if (!Zeroable[Len - 1])
7565 assert(Len > 0 && "Zeroable shuffle mask");
7567 // Attempt to match first Len sequential elements from the lower half.
7570 for (int i = 0; i != Len; ++i) {
7574 SDValue &V = (M < Size ? V1 : V2);
7577 // The extracted elements must start at a valid index and all mask
7578 // elements must be in the lower half.
7579 if (i > M || M >= HalfSize)
7582 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7593 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7594 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7595 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7596 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7597 DAG.getConstant(BitLen, DL, MVT::i8),
7598 DAG.getConstant(BitIdx, DL, MVT::i8));
7601 if (SDValue ExtrQ = LowerAsEXTRQ())
7604 // INSERTQ: Extract lowest Len elements from lower half of second source and
7605 // insert over first source, starting at Idx.
7606 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7607 auto LowerAsInsertQ = [&]() {
7608 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7611 // Attempt to match first source from mask before insertion point.
7612 if (isUndefInRange(Mask, 0, Idx)) {
7614 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7616 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7622 // Extend the extraction length looking to match both the insertion of
7623 // the second source and the remaining elements of the first.
7624 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7629 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7631 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7637 // Match the remaining elements of the lower half.
7638 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7640 } else if ((!Base || (Base == V1)) &&
7641 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7643 } else if ((!Base || (Base == V2)) &&
7644 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7651 // We may not have a base (first source) - this can safely be undefined.
7653 Base = DAG.getUNDEF(VT);
7655 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7656 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7657 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7658 DAG.getConstant(BitLen, DL, MVT::i8),
7659 DAG.getConstant(BitIdx, DL, MVT::i8));
7666 if (SDValue InsertQ = LowerAsInsertQ())
7672 /// \brief Lower a vector shuffle as a zero or any extension.
7674 /// Given a specific number of elements, element bit width, and extension
7675 /// stride, produce either a zero or any extension based on the available
7676 /// features of the subtarget. The extended elements are consecutive and
7677 /// begin and can start from an offseted element index in the input; to
7678 /// avoid excess shuffling the offset must either being in the bottom lane
7679 /// or at the start of a higher lane. All extended elements must be from
7681 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7682 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7683 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7684 assert(Scale > 1 && "Need a scale to extend.");
7685 int EltBits = VT.getScalarSizeInBits();
7686 int NumElements = VT.getVectorNumElements();
7687 int NumEltsPerLane = 128 / EltBits;
7688 int OffsetLane = Offset / NumEltsPerLane;
7689 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7690 "Only 8, 16, and 32 bit elements can be extended.");
7691 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7692 assert(0 <= Offset && "Extension offset must be positive.");
7693 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7694 "Extension offset must be in the first lane or start an upper lane.");
7696 // Check that an index is in same lane as the base offset.
7697 auto SafeOffset = [&](int Idx) {
7698 return OffsetLane == (Idx / NumEltsPerLane);
7701 // Shift along an input so that the offset base moves to the first element.
7702 auto ShuffleOffset = [&](SDValue V) {
7706 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7707 for (int i = 0; i * Scale < NumElements; ++i) {
7708 int SrcIdx = i + Offset;
7709 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7711 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7714 // Found a valid zext mask! Try various lowering strategies based on the
7715 // input type and available ISA extensions.
7716 if (Subtarget->hasSSE41()) {
7717 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7718 // PUNPCK will catch this in a later shuffle match.
7719 if (Offset && Scale == 2 && VT.is128BitVector())
7721 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7722 NumElements / Scale);
7723 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7724 return DAG.getBitcast(VT, InputV);
7727 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7729 // For any extends we can cheat for larger element sizes and use shuffle
7730 // instructions that can fold with a load and/or copy.
7731 if (AnyExt && EltBits == 32) {
7732 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7734 return DAG.getBitcast(
7735 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7736 DAG.getBitcast(MVT::v4i32, InputV),
7737 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7739 if (AnyExt && EltBits == 16 && Scale > 2) {
7740 int PSHUFDMask[4] = {Offset / 2, -1,
7741 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7742 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7743 DAG.getBitcast(MVT::v4i32, InputV),
7744 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7745 int PSHUFWMask[4] = {1, -1, -1, -1};
7746 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7747 return DAG.getBitcast(
7748 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7749 DAG.getBitcast(MVT::v8i16, InputV),
7750 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7753 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7755 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7756 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7757 assert(VT.is128BitVector() && "Unexpected vector width!");
7759 int LoIdx = Offset * EltBits;
7760 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7761 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7762 DAG.getConstant(EltBits, DL, MVT::i8),
7763 DAG.getConstant(LoIdx, DL, MVT::i8)));
7765 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7766 !SafeOffset(Offset + 1))
7767 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7769 int HiIdx = (Offset + 1) * EltBits;
7770 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7771 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7772 DAG.getConstant(EltBits, DL, MVT::i8),
7773 DAG.getConstant(HiIdx, DL, MVT::i8)));
7774 return DAG.getNode(ISD::BITCAST, DL, VT,
7775 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7778 // If this would require more than 2 unpack instructions to expand, use
7779 // pshufb when available. We can only use more than 2 unpack instructions
7780 // when zero extending i8 elements which also makes it easier to use pshufb.
7781 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7782 assert(NumElements == 16 && "Unexpected byte vector width!");
7783 SDValue PSHUFBMask[16];
7784 for (int i = 0; i < 16; ++i) {
7785 int Idx = Offset + (i / Scale);
7786 PSHUFBMask[i] = DAG.getConstant(
7787 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7789 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7790 return DAG.getBitcast(VT,
7791 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7792 DAG.getNode(ISD::BUILD_VECTOR, DL,
7793 MVT::v16i8, PSHUFBMask)));
7796 // If we are extending from an offset, ensure we start on a boundary that
7797 // we can unpack from.
7798 int AlignToUnpack = Offset % (NumElements / Scale);
7799 if (AlignToUnpack) {
7800 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7801 for (int i = AlignToUnpack; i < NumElements; ++i)
7802 ShMask[i - AlignToUnpack] = i;
7803 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7804 Offset -= AlignToUnpack;
7807 // Otherwise emit a sequence of unpacks.
7809 unsigned UnpackLoHi = X86ISD::UNPCKL;
7810 if (Offset >= (NumElements / 2)) {
7811 UnpackLoHi = X86ISD::UNPCKH;
7812 Offset -= (NumElements / 2);
7815 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7816 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7817 : getZeroVector(InputVT, Subtarget, DAG, DL);
7818 InputV = DAG.getBitcast(InputVT, InputV);
7819 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7823 } while (Scale > 1);
7824 return DAG.getBitcast(VT, InputV);
7827 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7829 /// This routine will try to do everything in its power to cleverly lower
7830 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7831 /// check for the profitability of this lowering, it tries to aggressively
7832 /// match this pattern. It will use all of the micro-architectural details it
7833 /// can to emit an efficient lowering. It handles both blends with all-zero
7834 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7835 /// masking out later).
7837 /// The reason we have dedicated lowering for zext-style shuffles is that they
7838 /// are both incredibly common and often quite performance sensitive.
7839 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7840 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7841 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7842 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7844 int Bits = VT.getSizeInBits();
7845 int NumLanes = Bits / 128;
7846 int NumElements = VT.getVectorNumElements();
7847 int NumEltsPerLane = NumElements / NumLanes;
7848 assert(VT.getScalarSizeInBits() <= 32 &&
7849 "Exceeds 32-bit integer zero extension limit");
7850 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7852 // Define a helper function to check a particular ext-scale and lower to it if
7854 auto Lower = [&](int Scale) -> SDValue {
7859 for (int i = 0; i < NumElements; ++i) {
7862 continue; // Valid anywhere but doesn't tell us anything.
7863 if (i % Scale != 0) {
7864 // Each of the extended elements need to be zeroable.
7868 // We no longer are in the anyext case.
7873 // Each of the base elements needs to be consecutive indices into the
7874 // same input vector.
7875 SDValue V = M < NumElements ? V1 : V2;
7876 M = M % NumElements;
7879 Offset = M - (i / Scale);
7880 } else if (InputV != V)
7881 return SDValue(); // Flip-flopping inputs.
7883 // Offset must start in the lowest 128-bit lane or at the start of an
7885 // FIXME: Is it ever worth allowing a negative base offset?
7886 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7887 (Offset % NumEltsPerLane) == 0))
7890 // If we are offsetting, all referenced entries must come from the same
7892 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7895 if ((M % NumElements) != (Offset + (i / Scale)))
7896 return SDValue(); // Non-consecutive strided elements.
7900 // If we fail to find an input, we have a zero-shuffle which should always
7901 // have already been handled.
7902 // FIXME: Maybe handle this here in case during blending we end up with one?
7906 // If we are offsetting, don't extend if we only match a single input, we
7907 // can always do better by using a basic PSHUF or PUNPCK.
7908 if (Offset != 0 && Matches < 2)
7911 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7912 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7915 // The widest scale possible for extending is to a 64-bit integer.
7916 assert(Bits % 64 == 0 &&
7917 "The number of bits in a vector must be divisible by 64 on x86!");
7918 int NumExtElements = Bits / 64;
7920 // Each iteration, try extending the elements half as much, but into twice as
7922 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7923 assert(NumElements % NumExtElements == 0 &&
7924 "The input vector size must be divisible by the extended size.");
7925 if (SDValue V = Lower(NumElements / NumExtElements))
7929 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7933 // Returns one of the source operands if the shuffle can be reduced to a
7934 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7935 auto CanZExtLowHalf = [&]() {
7936 for (int i = NumElements / 2; i != NumElements; ++i)
7939 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7941 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7946 if (SDValue V = CanZExtLowHalf()) {
7947 V = DAG.getBitcast(MVT::v2i64, V);
7948 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7949 return DAG.getBitcast(VT, V);
7952 // No viable ext lowering found.
7956 /// \brief Try to get a scalar value for a specific element of a vector.
7958 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7959 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7960 SelectionDAG &DAG) {
7961 MVT VT = V.getSimpleValueType();
7962 MVT EltVT = VT.getVectorElementType();
7963 while (V.getOpcode() == ISD::BITCAST)
7964 V = V.getOperand(0);
7965 // If the bitcasts shift the element size, we can't extract an equivalent
7967 MVT NewVT = V.getSimpleValueType();
7968 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7971 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7972 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7973 // Ensure the scalar operand is the same size as the destination.
7974 // FIXME: Add support for scalar truncation where possible.
7975 SDValue S = V.getOperand(Idx);
7976 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7977 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7983 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7985 /// This is particularly important because the set of instructions varies
7986 /// significantly based on whether the operand is a load or not.
7987 static bool isShuffleFoldableLoad(SDValue V) {
7988 while (V.getOpcode() == ISD::BITCAST)
7989 V = V.getOperand(0);
7991 return ISD::isNON_EXTLoad(V.getNode());
7994 /// \brief Try to lower insertion of a single element into a zero vector.
7996 /// This is a common pattern that we have especially efficient patterns to lower
7997 /// across all subtarget feature sets.
7998 static SDValue lowerVectorShuffleAsElementInsertion(
7999 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
8000 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8001 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8003 MVT EltVT = VT.getVectorElementType();
8005 int V2Index = std::find_if(Mask.begin(), Mask.end(),
8006 [&Mask](int M) { return M >= (int)Mask.size(); }) -
8008 bool IsV1Zeroable = true;
8009 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8010 if (i != V2Index && !Zeroable[i]) {
8011 IsV1Zeroable = false;
8015 // Check for a single input from a SCALAR_TO_VECTOR node.
8016 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
8017 // all the smarts here sunk into that routine. However, the current
8018 // lowering of BUILD_VECTOR makes that nearly impossible until the old
8019 // vector shuffle lowering is dead.
8020 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
8022 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
8023 // We need to zext the scalar if it is smaller than an i32.
8024 V2S = DAG.getBitcast(EltVT, V2S);
8025 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8026 // Using zext to expand a narrow element won't work for non-zero
8031 // Zero-extend directly to i32.
8033 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8035 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8036 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8037 EltVT == MVT::i16) {
8038 // Either not inserting from the low element of the input or the input
8039 // element size is too small to use VZEXT_MOVL to clear the high bits.
8043 if (!IsV1Zeroable) {
8044 // If V1 can't be treated as a zero vector we have fewer options to lower
8045 // this. We can't support integer vectors or non-zero targets cheaply, and
8046 // the V1 elements can't be permuted in any way.
8047 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8048 if (!VT.isFloatingPoint() || V2Index != 0)
8050 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8051 V1Mask[V2Index] = -1;
8052 if (!isNoopShuffleMask(V1Mask))
8054 // This is essentially a special case blend operation, but if we have
8055 // general purpose blend operations, they are always faster. Bail and let
8056 // the rest of the lowering handle these as blends.
8057 if (Subtarget->hasSSE41())
8060 // Otherwise, use MOVSD or MOVSS.
8061 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8062 "Only two types of floating point element types to handle!");
8063 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8067 // This lowering only works for the low element with floating point vectors.
8068 if (VT.isFloatingPoint() && V2Index != 0)
8071 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8073 V2 = DAG.getBitcast(VT, V2);
8076 // If we have 4 or fewer lanes we can cheaply shuffle the element into
8077 // the desired position. Otherwise it is more efficient to do a vector
8078 // shift left. We know that we can do a vector shift left because all
8079 // the inputs are zero.
8080 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8081 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8082 V2Shuffle[V2Index] = 0;
8083 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8085 V2 = DAG.getBitcast(MVT::v2i64, V2);
8087 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8088 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8089 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8090 DAG.getDataLayout(), VT)));
8091 V2 = DAG.getBitcast(VT, V2);
8097 /// \brief Try to lower broadcast of a single - truncated - integer element,
8098 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8100 /// This assumes we have AVX2.
8101 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8103 const X86Subtarget *Subtarget,
8104 SelectionDAG &DAG) {
8105 assert(Subtarget->hasAVX2() &&
8106 "We can only lower integer broadcasts with AVX2!");
8108 EVT EltVT = VT.getVectorElementType();
8109 EVT V0VT = V0.getValueType();
8111 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8112 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8114 EVT V0EltVT = V0VT.getVectorElementType();
8115 if (!V0EltVT.isInteger())
8118 const unsigned EltSize = EltVT.getSizeInBits();
8119 const unsigned V0EltSize = V0EltVT.getSizeInBits();
8121 // This is only a truncation if the original element type is larger.
8122 if (V0EltSize <= EltSize)
8125 assert(((V0EltSize % EltSize) == 0) &&
8126 "Scalar type sizes must all be powers of 2 on x86!");
8128 const unsigned V0Opc = V0.getOpcode();
8129 const unsigned Scale = V0EltSize / EltSize;
8130 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8132 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8133 V0Opc != ISD::BUILD_VECTOR)
8136 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8138 // If we're extracting non-least-significant bits, shift so we can truncate.
8139 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8140 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8141 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8142 if (const int OffsetIdx = BroadcastIdx % Scale)
8143 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8144 DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8146 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8147 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8150 /// \brief Try to lower broadcast of a single element.
8152 /// For convenience, this code also bundles all of the subtarget feature set
8153 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8154 /// a convenient way to factor it out.
8155 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8156 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8158 const X86Subtarget *Subtarget,
8159 SelectionDAG &DAG) {
8160 if (!Subtarget->hasAVX())
8162 if (VT.isInteger() && !Subtarget->hasAVX2())
8165 // Check that the mask is a broadcast.
8166 int BroadcastIdx = -1;
8168 if (M >= 0 && BroadcastIdx == -1)
8170 else if (M >= 0 && M != BroadcastIdx)
8173 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8174 "a sorted mask where the broadcast "
8177 // Go up the chain of (vector) values to find a scalar load that we can
8178 // combine with the broadcast.
8180 switch (V.getOpcode()) {
8181 case ISD::CONCAT_VECTORS: {
8182 int OperandSize = Mask.size() / V.getNumOperands();
8183 V = V.getOperand(BroadcastIdx / OperandSize);
8184 BroadcastIdx %= OperandSize;
8188 case ISD::INSERT_SUBVECTOR: {
8189 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8190 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8194 int BeginIdx = (int)ConstantIdx->getZExtValue();
8196 BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8197 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8198 BroadcastIdx -= BeginIdx;
8209 // Check if this is a broadcast of a scalar. We special case lowering
8210 // for scalars so that we can more effectively fold with loads.
8211 // First, look through bitcast: if the original value has a larger element
8212 // type than the shuffle, the broadcast element is in essence truncated.
8213 // Make that explicit to ease folding.
8214 if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8215 if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8216 DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8217 return TruncBroadcast;
8219 MVT BroadcastVT = VT;
8221 // Peek through any bitcast (only useful for loads).
8223 while (BC.getOpcode() == ISD::BITCAST)
8224 BC = BC.getOperand(0);
8226 // Also check the simpler case, where we can directly reuse the scalar.
8227 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8228 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8229 V = V.getOperand(BroadcastIdx);
8231 // If the scalar isn't a load, we can't broadcast from it in AVX1.
8232 // Only AVX2 has register broadcasts.
8233 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8235 } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8236 // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8237 if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8238 BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8240 // If we are broadcasting a load that is only used by the shuffle
8241 // then we can reduce the vector load to the broadcasted scalar load.
8242 LoadSDNode *Ld = cast<LoadSDNode>(BC);
8243 SDValue BaseAddr = Ld->getOperand(1);
8244 EVT AddrVT = BaseAddr.getValueType();
8245 EVT SVT = BroadcastVT.getScalarType();
8246 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8247 SDValue NewAddr = DAG.getNode(
8248 ISD::ADD, DL, AddrVT, BaseAddr,
8249 DAG.getConstant(Offset, DL, AddrVT));
8250 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8251 DAG.getMachineFunction().getMachineMemOperand(
8252 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8253 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8254 // We can't broadcast from a vector register without AVX2, and we can only
8255 // broadcast from the zero-element of a vector register.
8259 V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8260 return DAG.getBitcast(VT, V);
8263 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8264 // INSERTPS when the V1 elements are already in the correct locations
8265 // because otherwise we can just always use two SHUFPS instructions which
8266 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8267 // perform INSERTPS if a single V1 element is out of place and all V2
8268 // elements are zeroable.
8269 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8271 SelectionDAG &DAG) {
8272 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8273 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8274 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8275 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8277 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8280 int V1DstIndex = -1;
8281 int V2DstIndex = -1;
8282 bool V1UsedInPlace = false;
8284 for (int i = 0; i < 4; ++i) {
8285 // Synthesize a zero mask from the zeroable elements (includes undefs).
8291 // Flag if we use any V1 inputs in place.
8293 V1UsedInPlace = true;
8297 // We can only insert a single non-zeroable element.
8298 if (V1DstIndex != -1 || V2DstIndex != -1)
8302 // V1 input out of place for insertion.
8305 // V2 input for insertion.
8310 // Don't bother if we have no (non-zeroable) element for insertion.
8311 if (V1DstIndex == -1 && V2DstIndex == -1)
8314 // Determine element insertion src/dst indices. The src index is from the
8315 // start of the inserted vector, not the start of the concatenated vector.
8316 unsigned V2SrcIndex = 0;
8317 if (V1DstIndex != -1) {
8318 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8319 // and don't use the original V2 at all.
8320 V2SrcIndex = Mask[V1DstIndex];
8321 V2DstIndex = V1DstIndex;
8324 V2SrcIndex = Mask[V2DstIndex] - 4;
8327 // If no V1 inputs are used in place, then the result is created only from
8328 // the zero mask and the V2 insertion - so remove V1 dependency.
8330 V1 = DAG.getUNDEF(MVT::v4f32);
8332 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8333 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8335 // Insert the V2 element into the desired position.
8337 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8338 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8341 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8342 /// UNPCK instruction.
8344 /// This specifically targets cases where we end up with alternating between
8345 /// the two inputs, and so can permute them into something that feeds a single
8346 /// UNPCK instruction. Note that this routine only targets integer vectors
8347 /// because for floating point vectors we have a generalized SHUFPS lowering
8348 /// strategy that handles everything that doesn't *exactly* match an unpack,
8349 /// making this clever lowering unnecessary.
8350 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8351 SDValue V1, SDValue V2,
8353 SelectionDAG &DAG) {
8354 assert(!VT.isFloatingPoint() &&
8355 "This routine only supports integer vectors.");
8356 assert(!isSingleInputShuffleMask(Mask) &&
8357 "This routine should only be used when blending two inputs.");
8358 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8360 int Size = Mask.size();
8362 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8363 return M >= 0 && M % Size < Size / 2;
8365 int NumHiInputs = std::count_if(
8366 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8368 bool UnpackLo = NumLoInputs >= NumHiInputs;
8370 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8371 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8372 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8374 for (int i = 0; i < Size; ++i) {
8378 // Each element of the unpack contains Scale elements from this mask.
8379 int UnpackIdx = i / Scale;
8381 // We only handle the case where V1 feeds the first slots of the unpack.
8382 // We rely on canonicalization to ensure this is the case.
8383 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8386 // Setup the mask for this input. The indexing is tricky as we have to
8387 // handle the unpack stride.
8388 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8389 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8393 // If we will have to shuffle both inputs to use the unpack, check whether
8394 // we can just unpack first and shuffle the result. If so, skip this unpack.
8395 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8396 !isNoopShuffleMask(V2Mask))
8399 // Shuffle the inputs into place.
8400 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8401 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8403 // Cast the inputs to the type we will use to unpack them.
8404 V1 = DAG.getBitcast(UnpackVT, V1);
8405 V2 = DAG.getBitcast(UnpackVT, V2);
8407 // Unpack the inputs and cast the result back to the desired type.
8408 return DAG.getBitcast(
8409 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8413 // We try each unpack from the largest to the smallest to try and find one
8414 // that fits this mask.
8415 int OrigNumElements = VT.getVectorNumElements();
8416 int OrigScalarSize = VT.getScalarSizeInBits();
8417 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8418 int Scale = ScalarSize / OrigScalarSize;
8419 int NumElements = OrigNumElements / Scale;
8420 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8421 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8425 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8427 if (NumLoInputs == 0 || NumHiInputs == 0) {
8428 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8429 "We have to have *some* inputs!");
8430 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8432 // FIXME: We could consider the total complexity of the permute of each
8433 // possible unpacking. Or at the least we should consider how many
8434 // half-crossings are created.
8435 // FIXME: We could consider commuting the unpacks.
8437 SmallVector<int, 32> PermMask;
8438 PermMask.assign(Size, -1);
8439 for (int i = 0; i < Size; ++i) {
8443 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8446 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8448 return DAG.getVectorShuffle(
8449 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8451 DAG.getUNDEF(VT), PermMask);
8457 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8459 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8460 /// support for floating point shuffles but not integer shuffles. These
8461 /// instructions will incur a domain crossing penalty on some chips though so
8462 /// it is better to avoid lowering through this for integer vectors where
8464 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8465 const X86Subtarget *Subtarget,
8466 SelectionDAG &DAG) {
8468 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8469 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8470 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8471 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8472 ArrayRef<int> Mask = SVOp->getMask();
8473 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8475 if (isSingleInputShuffleMask(Mask)) {
8476 // Use low duplicate instructions for masks that match their pattern.
8477 if (Subtarget->hasSSE3())
8478 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8479 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8481 // Straight shuffle of a single input vector. Simulate this by using the
8482 // single input as both of the "inputs" to this instruction..
8483 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8485 if (Subtarget->hasAVX()) {
8486 // If we have AVX, we can use VPERMILPS which will allow folding a load
8487 // into the shuffle.
8488 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8489 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8492 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8493 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8495 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8496 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8498 // If we have a single input, insert that into V1 if we can do so cheaply.
8499 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8500 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8501 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8503 // Try inverting the insertion since for v2 masks it is easy to do and we
8504 // can't reliably sort the mask one way or the other.
8505 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8506 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8507 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8508 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8512 // Try to use one of the special instruction patterns to handle two common
8513 // blend patterns if a zero-blend above didn't work.
8514 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8515 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8516 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8517 // We can either use a special instruction to load over the low double or
8518 // to move just the low double.
8520 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8522 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8524 if (Subtarget->hasSSE41())
8525 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8529 // Use dedicated unpack instructions for masks that match their pattern.
8531 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8534 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8535 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8536 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8539 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8541 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8542 /// the integer unit to minimize domain crossing penalties. However, for blends
8543 /// it falls back to the floating point shuffle operation with appropriate bit
8545 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8546 const X86Subtarget *Subtarget,
8547 SelectionDAG &DAG) {
8549 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8550 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8551 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8552 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8553 ArrayRef<int> Mask = SVOp->getMask();
8554 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8556 if (isSingleInputShuffleMask(Mask)) {
8557 // Check for being able to broadcast a single element.
8558 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8559 Mask, Subtarget, DAG))
8562 // Straight shuffle of a single input vector. For everything from SSE2
8563 // onward this has a single fast instruction with no scary immediates.
8564 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8565 V1 = DAG.getBitcast(MVT::v4i32, V1);
8566 int WidenedMask[4] = {
8567 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8568 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8569 return DAG.getBitcast(
8571 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8572 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8574 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8575 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8576 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8577 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8579 // If we have a blend of two PACKUS operations an the blend aligns with the
8580 // low and half halves, we can just merge the PACKUS operations. This is
8581 // particularly important as it lets us merge shuffles that this routine itself
8583 auto GetPackNode = [](SDValue V) {
8584 while (V.getOpcode() == ISD::BITCAST)
8585 V = V.getOperand(0);
8587 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8589 if (SDValue V1Pack = GetPackNode(V1))
8590 if (SDValue V2Pack = GetPackNode(V2))
8591 return DAG.getBitcast(MVT::v2i64,
8592 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8593 Mask[0] == 0 ? V1Pack.getOperand(0)
8594 : V1Pack.getOperand(1),
8595 Mask[1] == 2 ? V2Pack.getOperand(0)
8596 : V2Pack.getOperand(1)));
8598 // Try to use shift instructions.
8600 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8603 // When loading a scalar and then shuffling it into a vector we can often do
8604 // the insertion cheaply.
8605 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8606 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8608 // Try inverting the insertion since for v2 masks it is easy to do and we
8609 // can't reliably sort the mask one way or the other.
8610 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8611 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8612 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8615 // We have different paths for blend lowering, but they all must use the
8616 // *exact* same predicate.
8617 bool IsBlendSupported = Subtarget->hasSSE41();
8618 if (IsBlendSupported)
8619 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8623 // Use dedicated unpack instructions for masks that match their pattern.
8625 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8628 // Try to use byte rotation instructions.
8629 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8630 if (Subtarget->hasSSSE3())
8631 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8632 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8635 // If we have direct support for blends, we should lower by decomposing into
8636 // a permute. That will be faster than the domain cross.
8637 if (IsBlendSupported)
8638 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8641 // We implement this with SHUFPD which is pretty lame because it will likely
8642 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8643 // However, all the alternatives are still more cycles and newer chips don't
8644 // have this problem. It would be really nice if x86 had better shuffles here.
8645 V1 = DAG.getBitcast(MVT::v2f64, V1);
8646 V2 = DAG.getBitcast(MVT::v2f64, V2);
8647 return DAG.getBitcast(MVT::v2i64,
8648 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8651 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8653 /// This is used to disable more specialized lowerings when the shufps lowering
8654 /// will happen to be efficient.
8655 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8656 // This routine only handles 128-bit shufps.
8657 assert(Mask.size() == 4 && "Unsupported mask size!");
8659 // To lower with a single SHUFPS we need to have the low half and high half
8660 // each requiring a single input.
8661 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8663 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8669 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8671 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8672 /// It makes no assumptions about whether this is the *best* lowering, it simply
8674 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8675 ArrayRef<int> Mask, SDValue V1,
8676 SDValue V2, SelectionDAG &DAG) {
8677 SDValue LowV = V1, HighV = V2;
8678 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8681 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8683 if (NumV2Elements == 1) {
8685 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8688 // Compute the index adjacent to V2Index and in the same half by toggling
8690 int V2AdjIndex = V2Index ^ 1;
8692 if (Mask[V2AdjIndex] == -1) {
8693 // Handles all the cases where we have a single V2 element and an undef.
8694 // This will only ever happen in the high lanes because we commute the
8695 // vector otherwise.
8697 std::swap(LowV, HighV);
8698 NewMask[V2Index] -= 4;
8700 // Handle the case where the V2 element ends up adjacent to a V1 element.
8701 // To make this work, blend them together as the first step.
8702 int V1Index = V2AdjIndex;
8703 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8704 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8705 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8707 // Now proceed to reconstruct the final blend as we have the necessary
8708 // high or low half formed.
8715 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8716 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8718 } else if (NumV2Elements == 2) {
8719 if (Mask[0] < 4 && Mask[1] < 4) {
8720 // Handle the easy case where we have V1 in the low lanes and V2 in the
8724 } else if (Mask[2] < 4 && Mask[3] < 4) {
8725 // We also handle the reversed case because this utility may get called
8726 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8727 // arrange things in the right direction.
8733 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8734 // trying to place elements directly, just blend them and set up the final
8735 // shuffle to place them.
8737 // The first two blend mask elements are for V1, the second two are for
8739 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8740 Mask[2] < 4 ? Mask[2] : Mask[3],
8741 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8742 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8743 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8744 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8746 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8749 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8750 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8751 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8752 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8755 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8756 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8759 /// \brief Lower 4-lane 32-bit floating point shuffles.
8761 /// Uses instructions exclusively from the floating point unit to minimize
8762 /// domain crossing penalties, as these are sufficient to implement all v4f32
8764 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8765 const X86Subtarget *Subtarget,
8766 SelectionDAG &DAG) {
8768 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8769 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8770 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8771 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8772 ArrayRef<int> Mask = SVOp->getMask();
8773 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8776 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8778 if (NumV2Elements == 0) {
8779 // Check for being able to broadcast a single element.
8780 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8781 Mask, Subtarget, DAG))
8784 // Use even/odd duplicate instructions for masks that match their pattern.
8785 if (Subtarget->hasSSE3()) {
8786 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8787 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8788 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8789 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8792 if (Subtarget->hasAVX()) {
8793 // If we have AVX, we can use VPERMILPS which will allow folding a load
8794 // into the shuffle.
8795 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8796 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8799 // Otherwise, use a straight shuffle of a single input vector. We pass the
8800 // input vector to both operands to simulate this with a SHUFPS.
8801 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8802 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8805 // There are special ways we can lower some single-element blends. However, we
8806 // have custom ways we can lower more complex single-element blends below that
8807 // we defer to if both this and BLENDPS fail to match, so restrict this to
8808 // when the V2 input is targeting element 0 of the mask -- that is the fast
8810 if (NumV2Elements == 1 && Mask[0] >= 4)
8811 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8812 Mask, Subtarget, DAG))
8815 if (Subtarget->hasSSE41()) {
8816 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8820 // Use INSERTPS if we can complete the shuffle efficiently.
8821 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8824 if (!isSingleSHUFPSMask(Mask))
8825 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8826 DL, MVT::v4f32, V1, V2, Mask, DAG))
8830 // Use dedicated unpack instructions for masks that match their pattern.
8832 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8835 // Otherwise fall back to a SHUFPS lowering strategy.
8836 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8839 /// \brief Lower 4-lane i32 vector shuffles.
8841 /// We try to handle these with integer-domain shuffles where we can, but for
8842 /// blends we use the floating point domain blend instructions.
8843 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8844 const X86Subtarget *Subtarget,
8845 SelectionDAG &DAG) {
8847 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8848 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8849 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8850 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8851 ArrayRef<int> Mask = SVOp->getMask();
8852 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8854 // Whenever we can lower this as a zext, that instruction is strictly faster
8855 // than any alternative. It also allows us to fold memory operands into the
8856 // shuffle in many cases.
8857 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8858 Mask, Subtarget, DAG))
8862 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8864 if (NumV2Elements == 0) {
8865 // Check for being able to broadcast a single element.
8866 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8867 Mask, Subtarget, DAG))
8870 // Straight shuffle of a single input vector. For everything from SSE2
8871 // onward this has a single fast instruction with no scary immediates.
8872 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8873 // but we aren't actually going to use the UNPCK instruction because doing
8874 // so prevents folding a load into this instruction or making a copy.
8875 const int UnpackLoMask[] = {0, 0, 1, 1};
8876 const int UnpackHiMask[] = {2, 2, 3, 3};
8877 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8878 Mask = UnpackLoMask;
8879 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8880 Mask = UnpackHiMask;
8882 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8883 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8886 // Try to use shift instructions.
8888 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8891 // There are special ways we can lower some single-element blends.
8892 if (NumV2Elements == 1)
8893 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8894 Mask, Subtarget, DAG))
8897 // We have different paths for blend lowering, but they all must use the
8898 // *exact* same predicate.
8899 bool IsBlendSupported = Subtarget->hasSSE41();
8900 if (IsBlendSupported)
8901 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8905 if (SDValue Masked =
8906 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8909 // Use dedicated unpack instructions for masks that match their pattern.
8911 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8914 // Try to use byte rotation instructions.
8915 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8916 if (Subtarget->hasSSSE3())
8917 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8918 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8921 // If we have direct support for blends, we should lower by decomposing into
8922 // a permute. That will be faster than the domain cross.
8923 if (IsBlendSupported)
8924 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8927 // Try to lower by permuting the inputs into an unpack instruction.
8928 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8932 // We implement this with SHUFPS because it can blend from two vectors.
8933 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8934 // up the inputs, bypassing domain shift penalties that we would encur if we
8935 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8937 return DAG.getBitcast(
8939 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8940 DAG.getBitcast(MVT::v4f32, V2), Mask));
8943 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8944 /// shuffle lowering, and the most complex part.
8946 /// The lowering strategy is to try to form pairs of input lanes which are
8947 /// targeted at the same half of the final vector, and then use a dword shuffle
8948 /// to place them onto the right half, and finally unpack the paired lanes into
8949 /// their final position.
8951 /// The exact breakdown of how to form these dword pairs and align them on the
8952 /// correct sides is really tricky. See the comments within the function for
8953 /// more of the details.
8955 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8956 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8957 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8958 /// vector, form the analogous 128-bit 8-element Mask.
8959 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8960 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8961 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8962 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8963 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8965 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8966 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8967 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8969 SmallVector<int, 4> LoInputs;
8970 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8971 [](int M) { return M >= 0; });
8972 std::sort(LoInputs.begin(), LoInputs.end());
8973 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8974 SmallVector<int, 4> HiInputs;
8975 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8976 [](int M) { return M >= 0; });
8977 std::sort(HiInputs.begin(), HiInputs.end());
8978 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8980 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8981 int NumHToL = LoInputs.size() - NumLToL;
8983 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8984 int NumHToH = HiInputs.size() - NumLToH;
8985 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8986 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8987 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8988 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8990 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8991 // such inputs we can swap two of the dwords across the half mark and end up
8992 // with <=2 inputs to each half in each half. Once there, we can fall through
8993 // to the generic code below. For example:
8995 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8996 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8998 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8999 // and an existing 2-into-2 on the other half. In this case we may have to
9000 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
9001 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
9002 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
9003 // because any other situation (including a 3-into-1 or 1-into-3 in the other
9004 // half than the one we target for fixing) will be fixed when we re-enter this
9005 // path. We will also combine away any sequence of PSHUFD instructions that
9006 // result into a single instruction. Here is an example of the tricky case:
9008 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
9009 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
9011 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
9013 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
9014 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
9016 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
9017 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
9019 // The result is fine to be handled by the generic logic.
9020 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
9021 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
9022 int AOffset, int BOffset) {
9023 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
9024 "Must call this with A having 3 or 1 inputs from the A half.");
9025 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
9026 "Must call this with B having 1 or 3 inputs from the B half.");
9027 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
9028 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
9030 bool ThreeAInputs = AToAInputs.size() == 3;
9032 // Compute the index of dword with only one word among the three inputs in
9033 // a half by taking the sum of the half with three inputs and subtracting
9034 // the sum of the actual three inputs. The difference is the remaining
9037 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
9038 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
9039 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
9040 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
9041 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9042 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9043 int TripleNonInputIdx =
9044 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9045 TripleDWord = TripleNonInputIdx / 2;
9047 // We use xor with one to compute the adjacent DWord to whichever one the
9049 OneInputDWord = (OneInput / 2) ^ 1;
9051 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9052 // and BToA inputs. If there is also such a problem with the BToB and AToB
9053 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9054 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9055 // is essential that we don't *create* a 3<-1 as then we might oscillate.
9056 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9057 // Compute how many inputs will be flipped by swapping these DWords. We
9059 // to balance this to ensure we don't form a 3-1 shuffle in the other
9061 int NumFlippedAToBInputs =
9062 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9063 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9064 int NumFlippedBToBInputs =
9065 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9066 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9067 if ((NumFlippedAToBInputs == 1 &&
9068 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9069 (NumFlippedBToBInputs == 1 &&
9070 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9071 // We choose whether to fix the A half or B half based on whether that
9072 // half has zero flipped inputs. At zero, we may not be able to fix it
9073 // with that half. We also bias towards fixing the B half because that
9074 // will more commonly be the high half, and we have to bias one way.
9075 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9076 ArrayRef<int> Inputs) {
9077 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9078 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9079 PinnedIdx ^ 1) != Inputs.end();
9080 // Determine whether the free index is in the flipped dword or the
9081 // unflipped dword based on where the pinned index is. We use this bit
9082 // in an xor to conditionally select the adjacent dword.
9083 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9084 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9085 FixFreeIdx) != Inputs.end();
9086 if (IsFixIdxInput == IsFixFreeIdxInput)
9088 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9089 FixFreeIdx) != Inputs.end();
9090 assert(IsFixIdxInput != IsFixFreeIdxInput &&
9091 "We need to be changing the number of flipped inputs!");
9092 int PSHUFHalfMask[] = {0, 1, 2, 3};
9093 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9094 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9096 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9099 if (M != -1 && M == FixIdx)
9101 else if (M != -1 && M == FixFreeIdx)
9104 if (NumFlippedBToBInputs != 0) {
9106 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9107 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9109 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9110 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9111 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9116 int PSHUFDMask[] = {0, 1, 2, 3};
9117 PSHUFDMask[ADWord] = BDWord;
9118 PSHUFDMask[BDWord] = ADWord;
9121 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9122 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9124 // Adjust the mask to match the new locations of A and B.
9126 if (M != -1 && M/2 == ADWord)
9127 M = 2 * BDWord + M % 2;
9128 else if (M != -1 && M/2 == BDWord)
9129 M = 2 * ADWord + M % 2;
9131 // Recurse back into this routine to re-compute state now that this isn't
9132 // a 3 and 1 problem.
9133 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9136 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9137 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9138 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9139 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9141 // At this point there are at most two inputs to the low and high halves from
9142 // each half. That means the inputs can always be grouped into dwords and
9143 // those dwords can then be moved to the correct half with a dword shuffle.
9144 // We use at most one low and one high word shuffle to collect these paired
9145 // inputs into dwords, and finally a dword shuffle to place them.
9146 int PSHUFLMask[4] = {-1, -1, -1, -1};
9147 int PSHUFHMask[4] = {-1, -1, -1, -1};
9148 int PSHUFDMask[4] = {-1, -1, -1, -1};
9150 // First fix the masks for all the inputs that are staying in their
9151 // original halves. This will then dictate the targets of the cross-half
9153 auto fixInPlaceInputs =
9154 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9155 MutableArrayRef<int> SourceHalfMask,
9156 MutableArrayRef<int> HalfMask, int HalfOffset) {
9157 if (InPlaceInputs.empty())
9159 if (InPlaceInputs.size() == 1) {
9160 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9161 InPlaceInputs[0] - HalfOffset;
9162 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9165 if (IncomingInputs.empty()) {
9166 // Just fix all of the in place inputs.
9167 for (int Input : InPlaceInputs) {
9168 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9169 PSHUFDMask[Input / 2] = Input / 2;
9174 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9175 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9176 InPlaceInputs[0] - HalfOffset;
9177 // Put the second input next to the first so that they are packed into
9178 // a dword. We find the adjacent index by toggling the low bit.
9179 int AdjIndex = InPlaceInputs[0] ^ 1;
9180 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9181 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9182 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9184 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9185 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9187 // Now gather the cross-half inputs and place them into a free dword of
9188 // their target half.
9189 // FIXME: This operation could almost certainly be simplified dramatically to
9190 // look more like the 3-1 fixing operation.
9191 auto moveInputsToRightHalf = [&PSHUFDMask](
9192 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9193 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9194 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9196 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9197 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9199 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9201 int LowWord = Word & ~1;
9202 int HighWord = Word | 1;
9203 return isWordClobbered(SourceHalfMask, LowWord) ||
9204 isWordClobbered(SourceHalfMask, HighWord);
9207 if (IncomingInputs.empty())
9210 if (ExistingInputs.empty()) {
9211 // Map any dwords with inputs from them into the right half.
9212 for (int Input : IncomingInputs) {
9213 // If the source half mask maps over the inputs, turn those into
9214 // swaps and use the swapped lane.
9215 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9216 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9217 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9218 Input - SourceOffset;
9219 // We have to swap the uses in our half mask in one sweep.
9220 for (int &M : HalfMask)
9221 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9223 else if (M == Input)
9224 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9226 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9227 Input - SourceOffset &&
9228 "Previous placement doesn't match!");
9230 // Note that this correctly re-maps both when we do a swap and when
9231 // we observe the other side of the swap above. We rely on that to
9232 // avoid swapping the members of the input list directly.
9233 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9236 // Map the input's dword into the correct half.
9237 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9238 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9240 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9242 "Previous placement doesn't match!");
9245 // And just directly shift any other-half mask elements to be same-half
9246 // as we will have mirrored the dword containing the element into the
9247 // same position within that half.
9248 for (int &M : HalfMask)
9249 if (M >= SourceOffset && M < SourceOffset + 4) {
9250 M = M - SourceOffset + DestOffset;
9251 assert(M >= 0 && "This should never wrap below zero!");
9256 // Ensure we have the input in a viable dword of its current half. This
9257 // is particularly tricky because the original position may be clobbered
9258 // by inputs being moved and *staying* in that half.
9259 if (IncomingInputs.size() == 1) {
9260 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9261 int InputFixed = std::find(std::begin(SourceHalfMask),
9262 std::end(SourceHalfMask), -1) -
9263 std::begin(SourceHalfMask) + SourceOffset;
9264 SourceHalfMask[InputFixed - SourceOffset] =
9265 IncomingInputs[0] - SourceOffset;
9266 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9268 IncomingInputs[0] = InputFixed;
9270 } else if (IncomingInputs.size() == 2) {
9271 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9272 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9273 // We have two non-adjacent or clobbered inputs we need to extract from
9274 // the source half. To do this, we need to map them into some adjacent
9275 // dword slot in the source mask.
9276 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9277 IncomingInputs[1] - SourceOffset};
9279 // If there is a free slot in the source half mask adjacent to one of
9280 // the inputs, place the other input in it. We use (Index XOR 1) to
9281 // compute an adjacent index.
9282 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9283 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9284 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9285 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9286 InputsFixed[1] = InputsFixed[0] ^ 1;
9287 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9288 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9289 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9290 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9291 InputsFixed[0] = InputsFixed[1] ^ 1;
9292 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9293 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9294 // The two inputs are in the same DWord but it is clobbered and the
9295 // adjacent DWord isn't used at all. Move both inputs to the free
9297 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9298 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9299 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9300 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9302 // The only way we hit this point is if there is no clobbering
9303 // (because there are no off-half inputs to this half) and there is no
9304 // free slot adjacent to one of the inputs. In this case, we have to
9305 // swap an input with a non-input.
9306 for (int i = 0; i < 4; ++i)
9307 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9308 "We can't handle any clobbers here!");
9309 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9310 "Cannot have adjacent inputs here!");
9312 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9313 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9315 // We also have to update the final source mask in this case because
9316 // it may need to undo the above swap.
9317 for (int &M : FinalSourceHalfMask)
9318 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9319 M = InputsFixed[1] + SourceOffset;
9320 else if (M == InputsFixed[1] + SourceOffset)
9321 M = (InputsFixed[0] ^ 1) + SourceOffset;
9323 InputsFixed[1] = InputsFixed[0] ^ 1;
9326 // Point everything at the fixed inputs.
9327 for (int &M : HalfMask)
9328 if (M == IncomingInputs[0])
9329 M = InputsFixed[0] + SourceOffset;
9330 else if (M == IncomingInputs[1])
9331 M = InputsFixed[1] + SourceOffset;
9333 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9334 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9337 llvm_unreachable("Unhandled input size!");
9340 // Now hoist the DWord down to the right half.
9341 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9342 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9343 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9344 for (int &M : HalfMask)
9345 for (int Input : IncomingInputs)
9347 M = FreeDWord * 2 + Input % 2;
9349 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9350 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9351 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9352 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9354 // Now enact all the shuffles we've computed to move the inputs into their
9356 if (!isNoopShuffleMask(PSHUFLMask))
9357 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9358 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9359 if (!isNoopShuffleMask(PSHUFHMask))
9360 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9361 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9362 if (!isNoopShuffleMask(PSHUFDMask))
9365 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9366 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9368 // At this point, each half should contain all its inputs, and we can then
9369 // just shuffle them into their final position.
9370 assert(std::count_if(LoMask.begin(), LoMask.end(),
9371 [](int M) { return M >= 4; }) == 0 &&
9372 "Failed to lift all the high half inputs to the low mask!");
9373 assert(std::count_if(HiMask.begin(), HiMask.end(),
9374 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9375 "Failed to lift all the low half inputs to the high mask!");
9377 // Do a half shuffle for the low mask.
9378 if (!isNoopShuffleMask(LoMask))
9379 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9380 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9382 // Do a half shuffle with the high mask after shifting its values down.
9383 for (int &M : HiMask)
9386 if (!isNoopShuffleMask(HiMask))
9387 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9388 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9393 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9394 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9395 SDValue V2, ArrayRef<int> Mask,
9396 SelectionDAG &DAG, bool &V1InUse,
9398 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9404 int Size = Mask.size();
9405 int Scale = 16 / Size;
9406 for (int i = 0; i < 16; ++i) {
9407 if (Mask[i / Scale] == -1) {
9408 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9410 const int ZeroMask = 0x80;
9411 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9413 int V2Idx = Mask[i / Scale] < Size
9415 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9416 if (Zeroable[i / Scale])
9417 V1Idx = V2Idx = ZeroMask;
9418 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9419 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9420 V1InUse |= (ZeroMask != V1Idx);
9421 V2InUse |= (ZeroMask != V2Idx);
9426 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9427 DAG.getBitcast(MVT::v16i8, V1),
9428 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9430 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9431 DAG.getBitcast(MVT::v16i8, V2),
9432 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9434 // If we need shuffled inputs from both, blend the two.
9436 if (V1InUse && V2InUse)
9437 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9439 V = V1InUse ? V1 : V2;
9441 // Cast the result back to the correct type.
9442 return DAG.getBitcast(VT, V);
9445 /// \brief Generic lowering of 8-lane i16 shuffles.
9447 /// This handles both single-input shuffles and combined shuffle/blends with
9448 /// two inputs. The single input shuffles are immediately delegated to
9449 /// a dedicated lowering routine.
9451 /// The blends are lowered in one of three fundamental ways. If there are few
9452 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9453 /// of the input is significantly cheaper when lowered as an interleaving of
9454 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9455 /// halves of the inputs separately (making them have relatively few inputs)
9456 /// and then concatenate them.
9457 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9458 const X86Subtarget *Subtarget,
9459 SelectionDAG &DAG) {
9461 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9462 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9463 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9464 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9465 ArrayRef<int> OrigMask = SVOp->getMask();
9466 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9467 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9468 MutableArrayRef<int> Mask(MaskStorage);
9470 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9472 // Whenever we can lower this as a zext, that instruction is strictly faster
9473 // than any alternative.
9474 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9475 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9478 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9480 auto isV2 = [](int M) { return M >= 8; };
9482 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9484 if (NumV2Inputs == 0) {
9485 // Check for being able to broadcast a single element.
9486 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9487 Mask, Subtarget, DAG))
9490 // Try to use shift instructions.
9492 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9495 // Use dedicated unpack instructions for masks that match their pattern.
9497 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9500 // Try to use byte rotation instructions.
9501 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9502 Mask, Subtarget, DAG))
9505 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9509 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9510 "All single-input shuffles should be canonicalized to be V1-input "
9513 // Try to use shift instructions.
9515 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9518 // See if we can use SSE4A Extraction / Insertion.
9519 if (Subtarget->hasSSE4A())
9520 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9523 // There are special ways we can lower some single-element blends.
9524 if (NumV2Inputs == 1)
9525 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9526 Mask, Subtarget, DAG))
9529 // We have different paths for blend lowering, but they all must use the
9530 // *exact* same predicate.
9531 bool IsBlendSupported = Subtarget->hasSSE41();
9532 if (IsBlendSupported)
9533 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9537 if (SDValue Masked =
9538 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9541 // Use dedicated unpack instructions for masks that match their pattern.
9543 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9546 // Try to use byte rotation instructions.
9547 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9548 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9551 if (SDValue BitBlend =
9552 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9555 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9559 // If we can't directly blend but can use PSHUFB, that will be better as it
9560 // can both shuffle and set up the inefficient blend.
9561 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9562 bool V1InUse, V2InUse;
9563 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9567 // We can always bit-blend if we have to so the fallback strategy is to
9568 // decompose into single-input permutes and blends.
9569 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9573 /// \brief Check whether a compaction lowering can be done by dropping even
9574 /// elements and compute how many times even elements must be dropped.
9576 /// This handles shuffles which take every Nth element where N is a power of
9577 /// two. Example shuffle masks:
9579 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9580 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9581 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9582 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9583 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9584 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9586 /// Any of these lanes can of course be undef.
9588 /// This routine only supports N <= 3.
9589 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9592 /// \returns N above, or the number of times even elements must be dropped if
9593 /// there is such a number. Otherwise returns zero.
9594 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9595 // Figure out whether we're looping over two inputs or just one.
9596 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9598 // The modulus for the shuffle vector entries is based on whether this is
9599 // a single input or not.
9600 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9601 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9602 "We should only be called with masks with a power-of-2 size!");
9604 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9606 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9607 // and 2^3 simultaneously. This is because we may have ambiguity with
9608 // partially undef inputs.
9609 bool ViableForN[3] = {true, true, true};
9611 for (int i = 0, e = Mask.size(); i < e; ++i) {
9612 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9617 bool IsAnyViable = false;
9618 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9619 if (ViableForN[j]) {
9622 // The shuffle mask must be equal to (i * 2^N) % M.
9623 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9626 ViableForN[j] = false;
9628 // Early exit if we exhaust the possible powers of two.
9633 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9637 // Return 0 as there is no viable power of two.
9641 /// \brief Generic lowering of v16i8 shuffles.
9643 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9644 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9645 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9646 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9648 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9649 const X86Subtarget *Subtarget,
9650 SelectionDAG &DAG) {
9652 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9653 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9654 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9655 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9656 ArrayRef<int> Mask = SVOp->getMask();
9657 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9659 // Try to use shift instructions.
9661 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9664 // Try to use byte rotation instructions.
9665 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9666 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9669 // Try to use a zext lowering.
9670 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9671 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9674 // See if we can use SSE4A Extraction / Insertion.
9675 if (Subtarget->hasSSE4A())
9676 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9680 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9682 // For single-input shuffles, there are some nicer lowering tricks we can use.
9683 if (NumV2Elements == 0) {
9684 // Check for being able to broadcast a single element.
9685 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9686 Mask, Subtarget, DAG))
9689 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9690 // Notably, this handles splat and partial-splat shuffles more efficiently.
9691 // However, it only makes sense if the pre-duplication shuffle simplifies
9692 // things significantly. Currently, this means we need to be able to
9693 // express the pre-duplication shuffle as an i16 shuffle.
9695 // FIXME: We should check for other patterns which can be widened into an
9696 // i16 shuffle as well.
9697 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9698 for (int i = 0; i < 16; i += 2)
9699 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9704 auto tryToWidenViaDuplication = [&]() -> SDValue {
9705 if (!canWidenViaDuplication(Mask))
9707 SmallVector<int, 4> LoInputs;
9708 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9709 [](int M) { return M >= 0 && M < 8; });
9710 std::sort(LoInputs.begin(), LoInputs.end());
9711 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9713 SmallVector<int, 4> HiInputs;
9714 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9715 [](int M) { return M >= 8; });
9716 std::sort(HiInputs.begin(), HiInputs.end());
9717 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9720 bool TargetLo = LoInputs.size() >= HiInputs.size();
9721 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9722 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9724 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9725 SmallDenseMap<int, int, 8> LaneMap;
9726 for (int I : InPlaceInputs) {
9727 PreDupI16Shuffle[I/2] = I/2;
9730 int j = TargetLo ? 0 : 4, je = j + 4;
9731 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9732 // Check if j is already a shuffle of this input. This happens when
9733 // there are two adjacent bytes after we move the low one.
9734 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9735 // If we haven't yet mapped the input, search for a slot into which
9737 while (j < je && PreDupI16Shuffle[j] != -1)
9741 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9744 // Map this input with the i16 shuffle.
9745 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9748 // Update the lane map based on the mapping we ended up with.
9749 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9751 V1 = DAG.getBitcast(
9753 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9754 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9756 // Unpack the bytes to form the i16s that will be shuffled into place.
9757 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9758 MVT::v16i8, V1, V1);
9760 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9761 for (int i = 0; i < 16; ++i)
9762 if (Mask[i] != -1) {
9763 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9764 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9765 if (PostDupI16Shuffle[i / 2] == -1)
9766 PostDupI16Shuffle[i / 2] = MappedMask;
9768 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9769 "Conflicting entrties in the original shuffle!");
9771 return DAG.getBitcast(
9773 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9774 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9776 if (SDValue V = tryToWidenViaDuplication())
9780 if (SDValue Masked =
9781 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9784 // Use dedicated unpack instructions for masks that match their pattern.
9786 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9789 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9790 // with PSHUFB. It is important to do this before we attempt to generate any
9791 // blends but after all of the single-input lowerings. If the single input
9792 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9793 // want to preserve that and we can DAG combine any longer sequences into
9794 // a PSHUFB in the end. But once we start blending from multiple inputs,
9795 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9796 // and there are *very* few patterns that would actually be faster than the
9797 // PSHUFB approach because of its ability to zero lanes.
9799 // FIXME: The only exceptions to the above are blends which are exact
9800 // interleavings with direct instructions supporting them. We currently don't
9801 // handle those well here.
9802 if (Subtarget->hasSSSE3()) {
9803 bool V1InUse = false;
9804 bool V2InUse = false;
9806 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9807 DAG, V1InUse, V2InUse);
9809 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9810 // do so. This avoids using them to handle blends-with-zero which is
9811 // important as a single pshufb is significantly faster for that.
9812 if (V1InUse && V2InUse) {
9813 if (Subtarget->hasSSE41())
9814 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9815 Mask, Subtarget, DAG))
9818 // We can use an unpack to do the blending rather than an or in some
9819 // cases. Even though the or may be (very minorly) more efficient, we
9820 // preference this lowering because there are common cases where part of
9821 // the complexity of the shuffles goes away when we do the final blend as
9823 // FIXME: It might be worth trying to detect if the unpack-feeding
9824 // shuffles will both be pshufb, in which case we shouldn't bother with
9826 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9827 DL, MVT::v16i8, V1, V2, Mask, DAG))
9834 // There are special ways we can lower some single-element blends.
9835 if (NumV2Elements == 1)
9836 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9837 Mask, Subtarget, DAG))
9840 if (SDValue BitBlend =
9841 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9844 // Check whether a compaction lowering can be done. This handles shuffles
9845 // which take every Nth element for some even N. See the helper function for
9848 // We special case these as they can be particularly efficiently handled with
9849 // the PACKUSB instruction on x86 and they show up in common patterns of
9850 // rearranging bytes to truncate wide elements.
9851 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9852 // NumEvenDrops is the power of two stride of the elements. Another way of
9853 // thinking about it is that we need to drop the even elements this many
9854 // times to get the original input.
9855 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9857 // First we need to zero all the dropped bytes.
9858 assert(NumEvenDrops <= 3 &&
9859 "No support for dropping even elements more than 3 times.");
9860 // We use the mask type to pick which bytes are preserved based on how many
9861 // elements are dropped.
9862 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9863 SDValue ByteClearMask = DAG.getBitcast(
9864 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9865 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9867 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9869 // Now pack things back together.
9870 V1 = DAG.getBitcast(MVT::v8i16, V1);
9871 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9872 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9873 for (int i = 1; i < NumEvenDrops; ++i) {
9874 Result = DAG.getBitcast(MVT::v8i16, Result);
9875 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9881 // Handle multi-input cases by blending single-input shuffles.
9882 if (NumV2Elements > 0)
9883 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9886 // The fallback path for single-input shuffles widens this into two v8i16
9887 // vectors with unpacks, shuffles those, and then pulls them back together
9891 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9892 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9893 for (int i = 0; i < 16; ++i)
9895 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9897 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9899 SDValue VLoHalf, VHiHalf;
9900 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9901 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9903 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9904 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9905 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9906 [](int M) { return M >= 0 && M % 2 == 1; })) {
9907 // Use a mask to drop the high bytes.
9908 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9909 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9910 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9912 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9913 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9915 // Squash the masks to point directly into VLoHalf.
9916 for (int &M : LoBlendMask)
9919 for (int &M : HiBlendMask)
9923 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9924 // VHiHalf so that we can blend them as i16s.
9925 VLoHalf = DAG.getBitcast(
9926 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9927 VHiHalf = DAG.getBitcast(
9928 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9931 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9932 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9934 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9937 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9939 /// This routine breaks down the specific type of 128-bit shuffle and
9940 /// dispatches to the lowering routines accordingly.
9941 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9942 MVT VT, const X86Subtarget *Subtarget,
9943 SelectionDAG &DAG) {
9944 switch (VT.SimpleTy) {
9946 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9948 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9950 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9952 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9954 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9956 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9959 llvm_unreachable("Unimplemented!");
9963 /// \brief Helper function to test whether a shuffle mask could be
9964 /// simplified by widening the elements being shuffled.
9966 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9967 /// leaves it in an unspecified state.
9969 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9970 /// shuffle masks. The latter have the special property of a '-2' representing
9971 /// a zero-ed lane of a vector.
9972 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9973 SmallVectorImpl<int> &WidenedMask) {
9974 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9975 // If both elements are undef, its trivial.
9976 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9977 WidenedMask.push_back(SM_SentinelUndef);
9981 // Check for an undef mask and a mask value properly aligned to fit with
9982 // a pair of values. If we find such a case, use the non-undef mask's value.
9983 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9984 WidenedMask.push_back(Mask[i + 1] / 2);
9987 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9988 WidenedMask.push_back(Mask[i] / 2);
9992 // When zeroing, we need to spread the zeroing across both lanes to widen.
9993 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9994 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9995 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9996 WidenedMask.push_back(SM_SentinelZero);
10002 // Finally check if the two mask values are adjacent and aligned with
10004 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
10005 WidenedMask.push_back(Mask[i] / 2);
10009 // Otherwise we can't safely widen the elements used in this shuffle.
10012 assert(WidenedMask.size() == Mask.size() / 2 &&
10013 "Incorrect size of mask after widening the elements!");
10018 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
10020 /// This routine just extracts two subvectors, shuffles them independently, and
10021 /// then concatenates them back together. This should work effectively with all
10022 /// AVX vector shuffle types.
10023 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10024 SDValue V2, ArrayRef<int> Mask,
10025 SelectionDAG &DAG) {
10026 assert(VT.getSizeInBits() >= 256 &&
10027 "Only for 256-bit or wider vector shuffles!");
10028 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
10029 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10031 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10032 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10034 int NumElements = VT.getVectorNumElements();
10035 int SplitNumElements = NumElements / 2;
10036 MVT ScalarVT = VT.getVectorElementType();
10037 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10039 // Rather than splitting build-vectors, just build two narrower build
10040 // vectors. This helps shuffling with splats and zeros.
10041 auto SplitVector = [&](SDValue V) {
10042 while (V.getOpcode() == ISD::BITCAST)
10043 V = V->getOperand(0);
10045 MVT OrigVT = V.getSimpleValueType();
10046 int OrigNumElements = OrigVT.getVectorNumElements();
10047 int OrigSplitNumElements = OrigNumElements / 2;
10048 MVT OrigScalarVT = OrigVT.getVectorElementType();
10049 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10053 auto *BV = dyn_cast<BuildVectorSDNode>(V);
10055 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10056 DAG.getIntPtrConstant(0, DL));
10057 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10058 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10061 SmallVector<SDValue, 16> LoOps, HiOps;
10062 for (int i = 0; i < OrigSplitNumElements; ++i) {
10063 LoOps.push_back(BV->getOperand(i));
10064 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10066 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10067 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10069 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10070 DAG.getBitcast(SplitVT, HiV));
10073 SDValue LoV1, HiV1, LoV2, HiV2;
10074 std::tie(LoV1, HiV1) = SplitVector(V1);
10075 std::tie(LoV2, HiV2) = SplitVector(V2);
10077 // Now create two 4-way blends of these half-width vectors.
10078 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10079 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10080 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10081 for (int i = 0; i < SplitNumElements; ++i) {
10082 int M = HalfMask[i];
10083 if (M >= NumElements) {
10084 if (M >= NumElements + SplitNumElements)
10088 V2BlendMask.push_back(M - NumElements);
10089 V1BlendMask.push_back(-1);
10090 BlendMask.push_back(SplitNumElements + i);
10091 } else if (M >= 0) {
10092 if (M >= SplitNumElements)
10096 V2BlendMask.push_back(-1);
10097 V1BlendMask.push_back(M);
10098 BlendMask.push_back(i);
10100 V2BlendMask.push_back(-1);
10101 V1BlendMask.push_back(-1);
10102 BlendMask.push_back(-1);
10106 // Because the lowering happens after all combining takes place, we need to
10107 // manually combine these blend masks as much as possible so that we create
10108 // a minimal number of high-level vector shuffle nodes.
10110 // First try just blending the halves of V1 or V2.
10111 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10112 return DAG.getUNDEF(SplitVT);
10113 if (!UseLoV2 && !UseHiV2)
10114 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10115 if (!UseLoV1 && !UseHiV1)
10116 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10118 SDValue V1Blend, V2Blend;
10119 if (UseLoV1 && UseHiV1) {
10121 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10123 // We only use half of V1 so map the usage down into the final blend mask.
10124 V1Blend = UseLoV1 ? LoV1 : HiV1;
10125 for (int i = 0; i < SplitNumElements; ++i)
10126 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10127 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10129 if (UseLoV2 && UseHiV2) {
10131 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10133 // We only use half of V2 so map the usage down into the final blend mask.
10134 V2Blend = UseLoV2 ? LoV2 : HiV2;
10135 for (int i = 0; i < SplitNumElements; ++i)
10136 if (BlendMask[i] >= SplitNumElements)
10137 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10139 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10141 SDValue Lo = HalfBlend(LoMask);
10142 SDValue Hi = HalfBlend(HiMask);
10143 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10146 /// \brief Either split a vector in halves or decompose the shuffles and the
10149 /// This is provided as a good fallback for many lowerings of non-single-input
10150 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10151 /// between splitting the shuffle into 128-bit components and stitching those
10152 /// back together vs. extracting the single-input shuffles and blending those
10154 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10155 SDValue V2, ArrayRef<int> Mask,
10156 SelectionDAG &DAG) {
10157 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10158 "lower single-input shuffles as it "
10159 "could then recurse on itself.");
10160 int Size = Mask.size();
10162 // If this can be modeled as a broadcast of two elements followed by a blend,
10163 // prefer that lowering. This is especially important because broadcasts can
10164 // often fold with memory operands.
10165 auto DoBothBroadcast = [&] {
10166 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10169 if (V2BroadcastIdx == -1)
10170 V2BroadcastIdx = M - Size;
10171 else if (M - Size != V2BroadcastIdx)
10173 } else if (M >= 0) {
10174 if (V1BroadcastIdx == -1)
10175 V1BroadcastIdx = M;
10176 else if (M != V1BroadcastIdx)
10181 if (DoBothBroadcast())
10182 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10185 // If the inputs all stem from a single 128-bit lane of each input, then we
10186 // split them rather than blending because the split will decompose to
10187 // unusually few instructions.
10188 int LaneCount = VT.getSizeInBits() / 128;
10189 int LaneSize = Size / LaneCount;
10190 SmallBitVector LaneInputs[2];
10191 LaneInputs[0].resize(LaneCount, false);
10192 LaneInputs[1].resize(LaneCount, false);
10193 for (int i = 0; i < Size; ++i)
10195 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10196 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10197 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10199 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10200 // that the decomposed single-input shuffles don't end up here.
10201 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10204 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10205 /// a permutation and blend of those lanes.
10207 /// This essentially blends the out-of-lane inputs to each lane into the lane
10208 /// from a permuted copy of the vector. This lowering strategy results in four
10209 /// instructions in the worst case for a single-input cross lane shuffle which
10210 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10211 /// of. Special cases for each particular shuffle pattern should be handled
10212 /// prior to trying this lowering.
10213 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10214 SDValue V1, SDValue V2,
10215 ArrayRef<int> Mask,
10216 SelectionDAG &DAG) {
10217 // FIXME: This should probably be generalized for 512-bit vectors as well.
10218 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10219 int LaneSize = Mask.size() / 2;
10221 // If there are only inputs from one 128-bit lane, splitting will in fact be
10222 // less expensive. The flags track whether the given lane contains an element
10223 // that crosses to another lane.
10224 bool LaneCrossing[2] = {false, false};
10225 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10226 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10227 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10228 if (!LaneCrossing[0] || !LaneCrossing[1])
10229 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10231 if (isSingleInputShuffleMask(Mask)) {
10232 SmallVector<int, 32> FlippedBlendMask;
10233 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10234 FlippedBlendMask.push_back(
10235 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10237 : Mask[i] % LaneSize +
10238 (i / LaneSize) * LaneSize + Size));
10240 // Flip the vector, and blend the results which should now be in-lane. The
10241 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10242 // 5 for the high source. The value 3 selects the high half of source 2 and
10243 // the value 2 selects the low half of source 2. We only use source 2 to
10244 // allow folding it into a memory operand.
10245 unsigned PERMMask = 3 | 2 << 4;
10246 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10247 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10248 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10251 // This now reduces to two single-input shuffles of V1 and V2 which at worst
10252 // will be handled by the above logic and a blend of the results, much like
10253 // other patterns in AVX.
10254 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10257 /// \brief Handle lowering 2-lane 128-bit shuffles.
10258 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10259 SDValue V2, ArrayRef<int> Mask,
10260 const X86Subtarget *Subtarget,
10261 SelectionDAG &DAG) {
10262 // TODO: If minimizing size and one of the inputs is a zero vector and the
10263 // the zero vector has only one use, we could use a VPERM2X128 to save the
10264 // instruction bytes needed to explicitly generate the zero vector.
10266 // Blends are faster and handle all the non-lane-crossing cases.
10267 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10271 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10272 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10274 // If either input operand is a zero vector, use VPERM2X128 because its mask
10275 // allows us to replace the zero input with an implicit zero.
10276 if (!IsV1Zero && !IsV2Zero) {
10277 // Check for patterns which can be matched with a single insert of a 128-bit
10279 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10280 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10281 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10282 VT.getVectorNumElements() / 2);
10283 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10284 DAG.getIntPtrConstant(0, DL));
10285 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10286 OnlyUsesV1 ? V1 : V2,
10287 DAG.getIntPtrConstant(0, DL));
10288 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10292 // Otherwise form a 128-bit permutation. After accounting for undefs,
10293 // convert the 64-bit shuffle mask selection values into 128-bit
10294 // selection bits by dividing the indexes by 2 and shifting into positions
10295 // defined by a vperm2*128 instruction's immediate control byte.
10297 // The immediate permute control byte looks like this:
10298 // [1:0] - select 128 bits from sources for low half of destination
10300 // [3] - zero low half of destination
10301 // [5:4] - select 128 bits from sources for high half of destination
10303 // [7] - zero high half of destination
10305 int MaskLO = Mask[0];
10306 if (MaskLO == SM_SentinelUndef)
10307 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10309 int MaskHI = Mask[2];
10310 if (MaskHI == SM_SentinelUndef)
10311 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10313 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10315 // If either input is a zero vector, replace it with an undef input.
10316 // Shuffle mask values < 4 are selecting elements of V1.
10317 // Shuffle mask values >= 4 are selecting elements of V2.
10318 // Adjust each half of the permute mask by clearing the half that was
10319 // selecting the zero vector and setting the zero mask bit.
10321 V1 = DAG.getUNDEF(VT);
10323 PermMask = (PermMask & 0xf0) | 0x08;
10325 PermMask = (PermMask & 0x0f) | 0x80;
10328 V2 = DAG.getUNDEF(VT);
10330 PermMask = (PermMask & 0xf0) | 0x08;
10332 PermMask = (PermMask & 0x0f) | 0x80;
10335 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10336 DAG.getConstant(PermMask, DL, MVT::i8));
10339 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10340 /// shuffling each lane.
10342 /// This will only succeed when the result of fixing the 128-bit lanes results
10343 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10344 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10345 /// the lane crosses early and then use simpler shuffles within each lane.
10347 /// FIXME: It might be worthwhile at some point to support this without
10348 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10349 /// in x86 only floating point has interesting non-repeating shuffles, and even
10350 /// those are still *marginally* more expensive.
10351 static SDValue lowerVectorShuffleByMerging128BitLanes(
10352 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10353 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10354 assert(!isSingleInputShuffleMask(Mask) &&
10355 "This is only useful with multiple inputs.");
10357 int Size = Mask.size();
10358 int LaneSize = 128 / VT.getScalarSizeInBits();
10359 int NumLanes = Size / LaneSize;
10360 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10362 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10363 // check whether the in-128-bit lane shuffles share a repeating pattern.
10364 SmallVector<int, 4> Lanes;
10365 Lanes.resize(NumLanes, -1);
10366 SmallVector<int, 4> InLaneMask;
10367 InLaneMask.resize(LaneSize, -1);
10368 for (int i = 0; i < Size; ++i) {
10372 int j = i / LaneSize;
10374 if (Lanes[j] < 0) {
10375 // First entry we've seen for this lane.
10376 Lanes[j] = Mask[i] / LaneSize;
10377 } else if (Lanes[j] != Mask[i] / LaneSize) {
10378 // This doesn't match the lane selected previously!
10382 // Check that within each lane we have a consistent shuffle mask.
10383 int k = i % LaneSize;
10384 if (InLaneMask[k] < 0) {
10385 InLaneMask[k] = Mask[i] % LaneSize;
10386 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10387 // This doesn't fit a repeating in-lane mask.
10392 // First shuffle the lanes into place.
10393 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10394 VT.getSizeInBits() / 64);
10395 SmallVector<int, 8> LaneMask;
10396 LaneMask.resize(NumLanes * 2, -1);
10397 for (int i = 0; i < NumLanes; ++i)
10398 if (Lanes[i] >= 0) {
10399 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10400 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10403 V1 = DAG.getBitcast(LaneVT, V1);
10404 V2 = DAG.getBitcast(LaneVT, V2);
10405 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10407 // Cast it back to the type we actually want.
10408 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10410 // Now do a simple shuffle that isn't lane crossing.
10411 SmallVector<int, 8> NewMask;
10412 NewMask.resize(Size, -1);
10413 for (int i = 0; i < Size; ++i)
10415 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10416 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10417 "Must not introduce lane crosses at this point!");
10419 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10422 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10423 /// This allows for fast cases such as subvector extraction/insertion
10424 /// or shuffling smaller vector types which can lower more efficiently.
10425 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10426 SDValue V2, ArrayRef<int> Mask,
10427 const X86Subtarget *Subtarget,
10428 SelectionDAG &DAG) {
10429 assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10431 unsigned NumElts = VT.getVectorNumElements();
10432 unsigned HalfNumElts = NumElts / 2;
10433 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10435 bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10436 bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10437 if (!UndefLower && !UndefUpper)
10440 // Upper half is undef and lower half is whole upper subvector.
10441 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10443 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10444 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10445 DAG.getIntPtrConstant(HalfNumElts, DL));
10446 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10447 DAG.getIntPtrConstant(0, DL));
10450 // Lower half is undef and upper half is whole lower subvector.
10451 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10453 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10454 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10455 DAG.getIntPtrConstant(0, DL));
10456 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10457 DAG.getIntPtrConstant(HalfNumElts, DL));
10460 // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10461 if (UndefLower && Subtarget->hasAVX2() &&
10462 (VT == MVT::v4f64 || VT == MVT::v4i64))
10465 // If the shuffle only uses the lower halves of the input operands,
10466 // then extract them and perform the 'half' shuffle at half width.
10467 // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10468 int HalfIdx1 = -1, HalfIdx2 = -1;
10469 SmallVector<int, 8> HalfMask;
10470 unsigned Offset = UndefLower ? HalfNumElts : 0;
10471 for (unsigned i = 0; i != HalfNumElts; ++i) {
10472 int M = Mask[i + Offset];
10474 HalfMask.push_back(M);
10478 // Determine which of the 4 half vectors this element is from.
10479 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10480 int HalfIdx = M / HalfNumElts;
10482 // Only shuffle using the lower halves of the inputs.
10483 // TODO: Investigate usefulness of shuffling with upper halves.
10484 if (HalfIdx != 0 && HalfIdx != 2)
10487 // Determine the element index into its half vector source.
10488 int HalfElt = M % HalfNumElts;
10490 // We can shuffle with up to 2 half vectors, set the new 'half'
10491 // shuffle mask accordingly.
10492 if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10493 HalfMask.push_back(HalfElt);
10494 HalfIdx1 = HalfIdx;
10497 if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10498 HalfMask.push_back(HalfElt + HalfNumElts);
10499 HalfIdx2 = HalfIdx;
10503 // Too many half vectors referenced.
10506 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10508 auto GetHalfVector = [&](int HalfIdx) {
10510 return DAG.getUNDEF(HalfVT);
10511 SDValue V = (HalfIdx < 2 ? V1 : V2);
10512 HalfIdx = (HalfIdx % 2) * HalfNumElts;
10513 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10514 DAG.getIntPtrConstant(HalfIdx, DL));
10517 SDValue Half1 = GetHalfVector(HalfIdx1);
10518 SDValue Half2 = GetHalfVector(HalfIdx2);
10519 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10520 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10521 DAG.getIntPtrConstant(Offset, DL));
10524 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10527 /// This returns true if the elements from a particular input are already in the
10528 /// slot required by the given mask and require no permutation.
10529 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10530 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10531 int Size = Mask.size();
10532 for (int i = 0; i < Size; ++i)
10533 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10539 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10540 ArrayRef<int> Mask, SDValue V1,
10541 SDValue V2, SelectionDAG &DAG) {
10543 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10544 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10545 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10546 int NumElts = VT.getVectorNumElements();
10547 bool ShufpdMask = true;
10548 bool CommutableMask = true;
10549 unsigned Immediate = 0;
10550 for (int i = 0; i < NumElts; ++i) {
10553 int Val = (i & 6) + NumElts * (i & 1);
10554 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10555 if (Mask[i] < Val || Mask[i] > Val + 1)
10556 ShufpdMask = false;
10557 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10558 CommutableMask = false;
10559 Immediate |= (Mask[i] % 2) << i;
10562 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10563 DAG.getConstant(Immediate, DL, MVT::i8));
10564 if (CommutableMask)
10565 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10566 DAG.getConstant(Immediate, DL, MVT::i8));
10570 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10572 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10573 /// isn't available.
10574 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10575 const X86Subtarget *Subtarget,
10576 SelectionDAG &DAG) {
10578 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10579 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10580 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10581 ArrayRef<int> Mask = SVOp->getMask();
10582 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10584 SmallVector<int, 4> WidenedMask;
10585 if (canWidenShuffleElements(Mask, WidenedMask))
10586 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10589 if (isSingleInputShuffleMask(Mask)) {
10590 // Check for being able to broadcast a single element.
10591 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10592 Mask, Subtarget, DAG))
10595 // Use low duplicate instructions for masks that match their pattern.
10596 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10597 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10599 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10600 // Non-half-crossing single input shuffles can be lowerid with an
10601 // interleaved permutation.
10602 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10603 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10604 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10605 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10608 // With AVX2 we have direct support for this permutation.
10609 if (Subtarget->hasAVX2())
10610 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10611 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10613 // Otherwise, fall back.
10614 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10618 // Use dedicated unpack instructions for masks that match their pattern.
10620 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10623 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10627 // Check if the blend happens to exactly fit that of SHUFPD.
10629 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10632 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10633 // shuffle. However, if we have AVX2 and either inputs are already in place,
10634 // we will be able to shuffle even across lanes the other input in a single
10635 // instruction so skip this pattern.
10636 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10637 isShuffleMaskInputInPlace(1, Mask))))
10638 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10639 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10642 // If we have AVX2 then we always want to lower with a blend because an v4 we
10643 // can fully permute the elements.
10644 if (Subtarget->hasAVX2())
10645 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10648 // Otherwise fall back on generic lowering.
10649 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10652 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10654 /// This routine is only called when we have AVX2 and thus a reasonable
10655 /// instruction set for v4i64 shuffling..
10656 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10657 const X86Subtarget *Subtarget,
10658 SelectionDAG &DAG) {
10660 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10661 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10662 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10663 ArrayRef<int> Mask = SVOp->getMask();
10664 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10665 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10667 SmallVector<int, 4> WidenedMask;
10668 if (canWidenShuffleElements(Mask, WidenedMask))
10669 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10672 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10676 // Check for being able to broadcast a single element.
10677 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10678 Mask, Subtarget, DAG))
10681 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10682 // use lower latency instructions that will operate on both 128-bit lanes.
10683 SmallVector<int, 2> RepeatedMask;
10684 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10685 if (isSingleInputShuffleMask(Mask)) {
10686 int PSHUFDMask[] = {-1, -1, -1, -1};
10687 for (int i = 0; i < 2; ++i)
10688 if (RepeatedMask[i] >= 0) {
10689 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10690 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10692 return DAG.getBitcast(
10694 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10695 DAG.getBitcast(MVT::v8i32, V1),
10696 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10700 // AVX2 provides a direct instruction for permuting a single input across
10702 if (isSingleInputShuffleMask(Mask))
10703 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10704 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10706 // Try to use shift instructions.
10707 if (SDValue Shift =
10708 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10711 // Use dedicated unpack instructions for masks that match their pattern.
10713 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10716 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10717 // shuffle. However, if we have AVX2 and either inputs are already in place,
10718 // we will be able to shuffle even across lanes the other input in a single
10719 // instruction so skip this pattern.
10720 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10721 isShuffleMaskInputInPlace(1, Mask))))
10722 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10723 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10726 // Otherwise fall back on generic blend lowering.
10727 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10731 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10733 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10734 /// isn't available.
10735 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10736 const X86Subtarget *Subtarget,
10737 SelectionDAG &DAG) {
10739 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10740 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10741 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10742 ArrayRef<int> Mask = SVOp->getMask();
10743 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10745 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10749 // Check for being able to broadcast a single element.
10750 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10751 Mask, Subtarget, DAG))
10754 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10755 // options to efficiently lower the shuffle.
10756 SmallVector<int, 4> RepeatedMask;
10757 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10758 assert(RepeatedMask.size() == 4 &&
10759 "Repeated masks must be half the mask width!");
10761 // Use even/odd duplicate instructions for masks that match their pattern.
10762 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10763 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10764 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10765 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10767 if (isSingleInputShuffleMask(Mask))
10768 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10769 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10771 // Use dedicated unpack instructions for masks that match their pattern.
10773 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10776 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10777 // have already handled any direct blends. We also need to squash the
10778 // repeated mask into a simulated v4f32 mask.
10779 for (int i = 0; i < 4; ++i)
10780 if (RepeatedMask[i] >= 8)
10781 RepeatedMask[i] -= 4;
10782 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10785 // If we have a single input shuffle with different shuffle patterns in the
10786 // two 128-bit lanes use the variable mask to VPERMILPS.
10787 if (isSingleInputShuffleMask(Mask)) {
10788 SDValue VPermMask[8];
10789 for (int i = 0; i < 8; ++i)
10790 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10791 : DAG.getConstant(Mask[i], DL, MVT::i32);
10792 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10793 return DAG.getNode(
10794 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10795 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10797 if (Subtarget->hasAVX2())
10798 return DAG.getNode(
10799 X86ISD::VPERMV, DL, MVT::v8f32,
10800 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10802 // Otherwise, fall back.
10803 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10807 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10809 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10810 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10813 // If we have AVX2 then we always want to lower with a blend because at v8 we
10814 // can fully permute the elements.
10815 if (Subtarget->hasAVX2())
10816 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10819 // Otherwise fall back on generic lowering.
10820 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10823 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10825 /// This routine is only called when we have AVX2 and thus a reasonable
10826 /// instruction set for v8i32 shuffling..
10827 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10828 const X86Subtarget *Subtarget,
10829 SelectionDAG &DAG) {
10831 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10832 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10833 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10834 ArrayRef<int> Mask = SVOp->getMask();
10835 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10836 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10838 // Whenever we can lower this as a zext, that instruction is strictly faster
10839 // than any alternative. It also allows us to fold memory operands into the
10840 // shuffle in many cases.
10841 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10842 Mask, Subtarget, DAG))
10845 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10849 // Check for being able to broadcast a single element.
10850 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10851 Mask, Subtarget, DAG))
10854 // If the shuffle mask is repeated in each 128-bit lane we can use more
10855 // efficient instructions that mirror the shuffles across the two 128-bit
10857 SmallVector<int, 4> RepeatedMask;
10858 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10859 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10860 if (isSingleInputShuffleMask(Mask))
10861 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10862 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10864 // Use dedicated unpack instructions for masks that match their pattern.
10866 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10870 // Try to use shift instructions.
10871 if (SDValue Shift =
10872 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10875 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10876 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10879 // If the shuffle patterns aren't repeated but it is a single input, directly
10880 // generate a cross-lane VPERMD instruction.
10881 if (isSingleInputShuffleMask(Mask)) {
10882 SDValue VPermMask[8];
10883 for (int i = 0; i < 8; ++i)
10884 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10885 : DAG.getConstant(Mask[i], DL, MVT::i32);
10886 return DAG.getNode(
10887 X86ISD::VPERMV, DL, MVT::v8i32,
10888 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10891 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10893 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10894 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10897 // Otherwise fall back on generic blend lowering.
10898 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10902 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10904 /// This routine is only called when we have AVX2 and thus a reasonable
10905 /// instruction set for v16i16 shuffling..
10906 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10907 const X86Subtarget *Subtarget,
10908 SelectionDAG &DAG) {
10910 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10911 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10912 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10913 ArrayRef<int> Mask = SVOp->getMask();
10914 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10915 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10917 // Whenever we can lower this as a zext, that instruction is strictly faster
10918 // than any alternative. It also allows us to fold memory operands into the
10919 // shuffle in many cases.
10920 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10921 Mask, Subtarget, DAG))
10924 // Check for being able to broadcast a single element.
10925 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10926 Mask, Subtarget, DAG))
10929 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10933 // Use dedicated unpack instructions for masks that match their pattern.
10935 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10938 // Try to use shift instructions.
10939 if (SDValue Shift =
10940 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10943 // Try to use byte rotation instructions.
10944 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10945 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10948 if (isSingleInputShuffleMask(Mask)) {
10949 // There are no generalized cross-lane shuffle operations available on i16
10951 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10952 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10955 SmallVector<int, 8> RepeatedMask;
10956 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10957 // As this is a single-input shuffle, the repeated mask should be
10958 // a strictly valid v8i16 mask that we can pass through to the v8i16
10959 // lowering to handle even the v16 case.
10960 return lowerV8I16GeneralSingleInputVectorShuffle(
10961 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10964 SDValue PSHUFBMask[32];
10965 for (int i = 0; i < 16; ++i) {
10966 if (Mask[i] == -1) {
10967 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10971 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10972 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10973 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10974 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10976 return DAG.getBitcast(MVT::v16i16,
10977 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10978 DAG.getBitcast(MVT::v32i8, V1),
10979 DAG.getNode(ISD::BUILD_VECTOR, DL,
10980 MVT::v32i8, PSHUFBMask)));
10983 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10985 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10986 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10989 // Otherwise fall back on generic lowering.
10990 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10993 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10995 /// This routine is only called when we have AVX2 and thus a reasonable
10996 /// instruction set for v32i8 shuffling..
10997 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10998 const X86Subtarget *Subtarget,
10999 SelectionDAG &DAG) {
11001 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11002 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11003 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11004 ArrayRef<int> Mask = SVOp->getMask();
11005 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11006 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
11008 // Whenever we can lower this as a zext, that instruction is strictly faster
11009 // than any alternative. It also allows us to fold memory operands into the
11010 // shuffle in many cases.
11011 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
11012 Mask, Subtarget, DAG))
11015 // Check for being able to broadcast a single element.
11016 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
11017 Mask, Subtarget, DAG))
11020 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
11024 // Use dedicated unpack instructions for masks that match their pattern.
11026 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
11029 // Try to use shift instructions.
11030 if (SDValue Shift =
11031 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
11034 // Try to use byte rotation instructions.
11035 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11036 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11039 if (isSingleInputShuffleMask(Mask)) {
11040 // There are no generalized cross-lane shuffle operations available on i8
11042 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11043 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11046 SDValue PSHUFBMask[32];
11047 for (int i = 0; i < 32; ++i)
11050 ? DAG.getUNDEF(MVT::i8)
11051 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11054 return DAG.getNode(
11055 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11056 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11059 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11061 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11062 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11065 // Otherwise fall back on generic lowering.
11066 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11069 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11071 /// This routine either breaks down the specific type of a 256-bit x86 vector
11072 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11073 /// together based on the available instructions.
11074 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11075 MVT VT, const X86Subtarget *Subtarget,
11076 SelectionDAG &DAG) {
11078 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11079 ArrayRef<int> Mask = SVOp->getMask();
11081 // If we have a single input to the zero element, insert that into V1 if we
11082 // can do so cheaply.
11083 int NumElts = VT.getVectorNumElements();
11084 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11085 return M >= NumElts;
11088 if (NumV2Elements == 1 && Mask[0] >= NumElts)
11089 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11090 DL, VT, V1, V2, Mask, Subtarget, DAG))
11093 // Handle special cases where the lower or upper half is UNDEF.
11095 lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11098 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11099 // can check for those subtargets here and avoid much of the subtarget
11100 // querying in the per-vector-type lowering routines. With AVX1 we have
11101 // essentially *zero* ability to manipulate a 256-bit vector with integer
11102 // types. Since we'll use floating point types there eventually, just
11103 // immediately cast everything to a float and operate entirely in that domain.
11104 if (VT.isInteger() && !Subtarget->hasAVX2()) {
11105 int ElementBits = VT.getScalarSizeInBits();
11106 if (ElementBits < 32)
11107 // No floating point type available, decompose into 128-bit vectors.
11108 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11110 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11111 VT.getVectorNumElements());
11112 V1 = DAG.getBitcast(FpVT, V1);
11113 V2 = DAG.getBitcast(FpVT, V2);
11114 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11117 switch (VT.SimpleTy) {
11119 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11121 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11123 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11125 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11127 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11129 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11132 llvm_unreachable("Not a valid 256-bit x86 vector type!");
11136 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11137 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11138 ArrayRef<int> Mask,
11139 SDValue V1, SDValue V2,
11140 SelectionDAG &DAG) {
11141 assert(VT.getScalarSizeInBits() == 64 &&
11142 "Unexpected element type size for 128bit shuffle.");
11144 // To handle 256 bit vector requires VLX and most probably
11145 // function lowerV2X128VectorShuffle() is better solution.
11146 assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11148 SmallVector<int, 4> WidenedMask;
11149 if (!canWidenShuffleElements(Mask, WidenedMask))
11152 // Form a 128-bit permutation.
11153 // Convert the 64-bit shuffle mask selection values into 128-bit selection
11154 // bits defined by a vshuf64x2 instruction's immediate control byte.
11155 unsigned PermMask = 0, Imm = 0;
11156 unsigned ControlBitsNum = WidenedMask.size() / 2;
11158 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11159 if (WidenedMask[i] == SM_SentinelZero)
11162 // Use first element in place of undef mask.
11163 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11164 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11167 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11168 DAG.getConstant(PermMask, DL, MVT::i8));
11171 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11172 ArrayRef<int> Mask, SDValue V1,
11173 SDValue V2, SelectionDAG &DAG) {
11175 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11177 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11178 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11180 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11181 if (isSingleInputShuffleMask(Mask))
11182 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11184 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11187 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11188 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11189 const X86Subtarget *Subtarget,
11190 SelectionDAG &DAG) {
11192 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11193 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11194 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11195 ArrayRef<int> Mask = SVOp->getMask();
11196 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11198 if (SDValue Shuf128 =
11199 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11202 if (SDValue Unpck =
11203 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11206 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11209 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11210 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11211 const X86Subtarget *Subtarget,
11212 SelectionDAG &DAG) {
11214 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11215 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11216 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11217 ArrayRef<int> Mask = SVOp->getMask();
11218 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11220 if (SDValue Unpck =
11221 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11224 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11227 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11228 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11229 const X86Subtarget *Subtarget,
11230 SelectionDAG &DAG) {
11232 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11233 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11234 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11235 ArrayRef<int> Mask = SVOp->getMask();
11236 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11238 if (SDValue Shuf128 =
11239 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11242 if (SDValue Unpck =
11243 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11246 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11249 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11250 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11251 const X86Subtarget *Subtarget,
11252 SelectionDAG &DAG) {
11254 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11255 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11256 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11257 ArrayRef<int> Mask = SVOp->getMask();
11258 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11260 if (SDValue Unpck =
11261 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11264 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11267 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11268 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11269 const X86Subtarget *Subtarget,
11270 SelectionDAG &DAG) {
11272 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11273 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11274 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11275 ArrayRef<int> Mask = SVOp->getMask();
11276 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11277 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11279 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11282 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11283 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11284 const X86Subtarget *Subtarget,
11285 SelectionDAG &DAG) {
11287 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11288 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11289 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11290 ArrayRef<int> Mask = SVOp->getMask();
11291 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11292 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11294 // FIXME: Implement direct support for this type!
11295 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11298 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11300 /// This routine either breaks down the specific type of a 512-bit x86 vector
11301 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11302 /// together based on the available instructions.
11303 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11304 MVT VT, const X86Subtarget *Subtarget,
11305 SelectionDAG &DAG) {
11307 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11308 ArrayRef<int> Mask = SVOp->getMask();
11309 assert(Subtarget->hasAVX512() &&
11310 "Cannot lower 512-bit vectors w/ basic ISA!");
11312 // Check for being able to broadcast a single element.
11313 if (SDValue Broadcast =
11314 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11317 // Dispatch to each element type for lowering. If we don't have supprot for
11318 // specific element type shuffles at 512 bits, immediately split them and
11319 // lower them. Each lowering routine of a given type is allowed to assume that
11320 // the requisite ISA extensions for that element type are available.
11321 switch (VT.SimpleTy) {
11323 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11325 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11327 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11329 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11331 if (Subtarget->hasBWI())
11332 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11335 if (Subtarget->hasBWI())
11336 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11340 llvm_unreachable("Not a valid 512-bit x86 vector type!");
11343 // Otherwise fall back on splitting.
11344 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11347 // Lower vXi1 vector shuffles.
11348 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11349 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11350 // vector, shuffle and then truncate it back.
11351 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11352 MVT VT, const X86Subtarget *Subtarget,
11353 SelectionDAG &DAG) {
11355 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11356 ArrayRef<int> Mask = SVOp->getMask();
11357 assert(Subtarget->hasAVX512() &&
11358 "Cannot lower 512-bit vectors w/o basic ISA!");
11360 switch (VT.SimpleTy) {
11362 llvm_unreachable("Expected a vector of i1 elements");
11364 ExtVT = MVT::v2i64;
11367 ExtVT = MVT::v4i32;
11370 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11373 ExtVT = MVT::v16i32;
11376 ExtVT = MVT::v32i16;
11379 ExtVT = MVT::v64i8;
11383 if (ISD::isBuildVectorAllZeros(V1.getNode()))
11384 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11385 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11386 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11388 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11391 V2 = DAG.getUNDEF(ExtVT);
11392 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11393 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11394 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11395 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11397 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11398 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11399 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11401 /// \brief Top-level lowering for x86 vector shuffles.
11403 /// This handles decomposition, canonicalization, and lowering of all x86
11404 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11405 /// above in helper routines. The canonicalization attempts to widen shuffles
11406 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11407 /// s.t. only one of the two inputs needs to be tested, etc.
11408 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11409 SelectionDAG &DAG) {
11410 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11411 ArrayRef<int> Mask = SVOp->getMask();
11412 SDValue V1 = Op.getOperand(0);
11413 SDValue V2 = Op.getOperand(1);
11414 MVT VT = Op.getSimpleValueType();
11415 int NumElements = VT.getVectorNumElements();
11417 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11419 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11420 "Can't lower MMX shuffles");
11422 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11423 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11424 if (V1IsUndef && V2IsUndef)
11425 return DAG.getUNDEF(VT);
11427 // When we create a shuffle node we put the UNDEF node to second operand,
11428 // but in some cases the first operand may be transformed to UNDEF.
11429 // In this case we should just commute the node.
11431 return DAG.getCommutedVectorShuffle(*SVOp);
11433 // Check for non-undef masks pointing at an undef vector and make the masks
11434 // undef as well. This makes it easier to match the shuffle based solely on
11438 if (M >= NumElements) {
11439 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11440 for (int &M : NewMask)
11441 if (M >= NumElements)
11443 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11446 // We actually see shuffles that are entirely re-arrangements of a set of
11447 // zero inputs. This mostly happens while decomposing complex shuffles into
11448 // simple ones. Directly lower these as a buildvector of zeros.
11449 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11450 if (Zeroable.all())
11451 return getZeroVector(VT, Subtarget, DAG, dl);
11453 // Try to collapse shuffles into using a vector type with fewer elements but
11454 // wider element types. We cap this to not form integers or floating point
11455 // elements wider than 64 bits, but it might be interesting to form i128
11456 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11457 SmallVector<int, 16> WidenedMask;
11458 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11459 canWidenShuffleElements(Mask, WidenedMask)) {
11460 MVT NewEltVT = VT.isFloatingPoint()
11461 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11462 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11463 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11464 // Make sure that the new vector type is legal. For example, v2f64 isn't
11466 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11467 V1 = DAG.getBitcast(NewVT, V1);
11468 V2 = DAG.getBitcast(NewVT, V2);
11469 return DAG.getBitcast(
11470 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11474 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11475 for (int M : SVOp->getMask())
11477 ++NumUndefElements;
11478 else if (M < NumElements)
11483 // Commute the shuffle as needed such that more elements come from V1 than
11484 // V2. This allows us to match the shuffle pattern strictly on how many
11485 // elements come from V1 without handling the symmetric cases.
11486 if (NumV2Elements > NumV1Elements)
11487 return DAG.getCommutedVectorShuffle(*SVOp);
11489 // When the number of V1 and V2 elements are the same, try to minimize the
11490 // number of uses of V2 in the low half of the vector. When that is tied,
11491 // ensure that the sum of indices for V1 is equal to or lower than the sum
11492 // indices for V2. When those are equal, try to ensure that the number of odd
11493 // indices for V1 is lower than the number of odd indices for V2.
11494 if (NumV1Elements == NumV2Elements) {
11495 int LowV1Elements = 0, LowV2Elements = 0;
11496 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11497 if (M >= NumElements)
11501 if (LowV2Elements > LowV1Elements) {
11502 return DAG.getCommutedVectorShuffle(*SVOp);
11503 } else if (LowV2Elements == LowV1Elements) {
11504 int SumV1Indices = 0, SumV2Indices = 0;
11505 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11506 if (SVOp->getMask()[i] >= NumElements)
11508 else if (SVOp->getMask()[i] >= 0)
11510 if (SumV2Indices < SumV1Indices) {
11511 return DAG.getCommutedVectorShuffle(*SVOp);
11512 } else if (SumV2Indices == SumV1Indices) {
11513 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11514 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11515 if (SVOp->getMask()[i] >= NumElements)
11516 NumV2OddIndices += i % 2;
11517 else if (SVOp->getMask()[i] >= 0)
11518 NumV1OddIndices += i % 2;
11519 if (NumV2OddIndices < NumV1OddIndices)
11520 return DAG.getCommutedVectorShuffle(*SVOp);
11525 // For each vector width, delegate to a specialized lowering routine.
11526 if (VT.is128BitVector())
11527 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11529 if (VT.is256BitVector())
11530 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11532 if (VT.is512BitVector())
11533 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11536 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11537 llvm_unreachable("Unimplemented!");
11540 // This function assumes its argument is a BUILD_VECTOR of constants or
11541 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11543 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11544 unsigned &MaskValue) {
11546 unsigned NumElems = BuildVector->getNumOperands();
11548 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11549 // We don't handle the >2 lanes case right now.
11550 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11554 unsigned NumElemsInLane = NumElems / NumLanes;
11556 // Blend for v16i16 should be symmetric for the both lanes.
11557 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11558 SDValue EltCond = BuildVector->getOperand(i);
11559 SDValue SndLaneEltCond =
11560 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11562 int Lane1Cond = -1, Lane2Cond = -1;
11563 if (isa<ConstantSDNode>(EltCond))
11564 Lane1Cond = !isNullConstant(EltCond);
11565 if (isa<ConstantSDNode>(SndLaneEltCond))
11566 Lane2Cond = !isNullConstant(SndLaneEltCond);
11568 unsigned LaneMask = 0;
11569 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11570 // Lane1Cond != 0, means we want the first argument.
11571 // Lane1Cond == 0, means we want the second argument.
11572 // The encoding of this argument is 0 for the first argument, 1
11573 // for the second. Therefore, invert the condition.
11574 LaneMask = !Lane1Cond << i;
11575 else if (Lane1Cond < 0)
11576 LaneMask = !Lane2Cond << i;
11580 MaskValue |= LaneMask;
11582 MaskValue |= LaneMask << NumElemsInLane;
11587 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11588 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11589 const X86Subtarget *Subtarget,
11590 SelectionDAG &DAG) {
11591 SDValue Cond = Op.getOperand(0);
11592 SDValue LHS = Op.getOperand(1);
11593 SDValue RHS = Op.getOperand(2);
11595 MVT VT = Op.getSimpleValueType();
11597 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11599 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11601 // Only non-legal VSELECTs reach this lowering, convert those into generic
11602 // shuffles and re-use the shuffle lowering path for blends.
11603 SmallVector<int, 32> Mask;
11604 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11605 SDValue CondElt = CondBV->getOperand(i);
11607 isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11610 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11613 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11614 // A vselect where all conditions and data are constants can be optimized into
11615 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11616 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11617 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11618 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11621 // Try to lower this to a blend-style vector shuffle. This can handle all
11622 // constant condition cases.
11623 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11626 // Variable blends are only legal from SSE4.1 onward.
11627 if (!Subtarget->hasSSE41())
11630 // Only some types will be legal on some subtargets. If we can emit a legal
11631 // VSELECT-matching blend, return Op, and but if we need to expand, return
11633 switch (Op.getSimpleValueType().SimpleTy) {
11635 // Most of the vector types have blends past SSE4.1.
11639 // The byte blends for AVX vectors were introduced only in AVX2.
11640 if (Subtarget->hasAVX2())
11647 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11648 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11651 // FIXME: We should custom lower this by fixing the condition and using i8
11657 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11658 MVT VT = Op.getSimpleValueType();
11661 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11664 if (VT.getSizeInBits() == 8) {
11665 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11666 Op.getOperand(0), Op.getOperand(1));
11667 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11668 DAG.getValueType(VT));
11669 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11672 if (VT.getSizeInBits() == 16) {
11673 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11674 if (isNullConstant(Op.getOperand(1)))
11675 return DAG.getNode(
11676 ISD::TRUNCATE, dl, MVT::i16,
11677 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11678 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11679 Op.getOperand(1)));
11680 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11681 Op.getOperand(0), Op.getOperand(1));
11682 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11683 DAG.getValueType(VT));
11684 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11687 if (VT == MVT::f32) {
11688 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11689 // the result back to FR32 register. It's only worth matching if the
11690 // result has a single use which is a store or a bitcast to i32. And in
11691 // the case of a store, it's not worth it if the index is a constant 0,
11692 // because a MOVSSmr can be used instead, which is smaller and faster.
11693 if (!Op.hasOneUse())
11695 SDNode *User = *Op.getNode()->use_begin();
11696 if ((User->getOpcode() != ISD::STORE ||
11697 isNullConstant(Op.getOperand(1))) &&
11698 (User->getOpcode() != ISD::BITCAST ||
11699 User->getValueType(0) != MVT::i32))
11701 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11702 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11704 return DAG.getBitcast(MVT::f32, Extract);
11707 if (VT == MVT::i32 || VT == MVT::i64) {
11708 // ExtractPS/pextrq works with constant index.
11709 if (isa<ConstantSDNode>(Op.getOperand(1)))
11715 /// Extract one bit from mask vector, like v16i1 or v8i1.
11716 /// AVX-512 feature.
11718 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11719 SDValue Vec = Op.getOperand(0);
11721 MVT VecVT = Vec.getSimpleValueType();
11722 SDValue Idx = Op.getOperand(1);
11723 MVT EltVT = Op.getSimpleValueType();
11725 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11726 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11727 "Unexpected vector type in ExtractBitFromMaskVector");
11729 // variable index can't be handled in mask registers,
11730 // extend vector to VR512
11731 if (!isa<ConstantSDNode>(Idx)) {
11732 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11733 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11734 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11735 ExtVT.getVectorElementType(), Ext, Idx);
11736 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11739 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11740 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11741 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11742 rc = getRegClassFor(MVT::v16i1);
11743 unsigned MaxSift = rc->getSize()*8 - 1;
11744 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11745 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11746 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11747 DAG.getConstant(MaxSift, dl, MVT::i8));
11748 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11749 DAG.getIntPtrConstant(0, dl));
11753 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11754 SelectionDAG &DAG) const {
11756 SDValue Vec = Op.getOperand(0);
11757 MVT VecVT = Vec.getSimpleValueType();
11758 SDValue Idx = Op.getOperand(1);
11760 if (Op.getSimpleValueType() == MVT::i1)
11761 return ExtractBitFromMaskVector(Op, DAG);
11763 if (!isa<ConstantSDNode>(Idx)) {
11764 if (VecVT.is512BitVector() ||
11765 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11766 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11769 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11770 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11771 MaskEltVT.getSizeInBits());
11773 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11774 auto PtrVT = getPointerTy(DAG.getDataLayout());
11775 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11776 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11777 DAG.getConstant(0, dl, PtrVT));
11778 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11779 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11780 DAG.getConstant(0, dl, PtrVT));
11785 // If this is a 256-bit vector result, first extract the 128-bit vector and
11786 // then extract the element from the 128-bit vector.
11787 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11789 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11790 // Get the 128-bit vector.
11791 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11792 MVT EltVT = VecVT.getVectorElementType();
11794 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11795 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11797 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11798 // this can be done with a mask.
11799 IdxVal &= ElemsPerChunk - 1;
11800 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11801 DAG.getConstant(IdxVal, dl, MVT::i32));
11804 assert(VecVT.is128BitVector() && "Unexpected vector length");
11806 if (Subtarget->hasSSE41())
11807 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11810 MVT VT = Op.getSimpleValueType();
11811 // TODO: handle v16i8.
11812 if (VT.getSizeInBits() == 16) {
11813 SDValue Vec = Op.getOperand(0);
11814 if (isNullConstant(Op.getOperand(1)))
11815 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11816 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11817 DAG.getBitcast(MVT::v4i32, Vec),
11818 Op.getOperand(1)));
11819 // Transform it so it match pextrw which produces a 32-bit result.
11820 MVT EltVT = MVT::i32;
11821 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11822 Op.getOperand(0), Op.getOperand(1));
11823 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11824 DAG.getValueType(VT));
11825 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11828 if (VT.getSizeInBits() == 32) {
11829 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11833 // SHUFPS the element to the lowest double word, then movss.
11834 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11835 MVT VVT = Op.getOperand(0).getSimpleValueType();
11836 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11837 DAG.getUNDEF(VVT), Mask);
11838 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11839 DAG.getIntPtrConstant(0, dl));
11842 if (VT.getSizeInBits() == 64) {
11843 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11844 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11845 // to match extract_elt for f64.
11846 if (isNullConstant(Op.getOperand(1)))
11849 // UNPCKHPD the element to the lowest double word, then movsd.
11850 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11851 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11852 int Mask[2] = { 1, -1 };
11853 MVT VVT = Op.getOperand(0).getSimpleValueType();
11854 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11855 DAG.getUNDEF(VVT), Mask);
11856 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11857 DAG.getIntPtrConstant(0, dl));
11863 /// Insert one bit to mask vector, like v16i1 or v8i1.
11864 /// AVX-512 feature.
11866 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11868 SDValue Vec = Op.getOperand(0);
11869 SDValue Elt = Op.getOperand(1);
11870 SDValue Idx = Op.getOperand(2);
11871 MVT VecVT = Vec.getSimpleValueType();
11873 if (!isa<ConstantSDNode>(Idx)) {
11874 // Non constant index. Extend source and destination,
11875 // insert element and then truncate the result.
11876 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11877 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11878 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11879 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11880 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11881 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11884 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11885 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11887 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11888 DAG.getConstant(IdxVal, dl, MVT::i8));
11889 if (Vec.getOpcode() == ISD::UNDEF)
11891 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11894 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11895 SelectionDAG &DAG) const {
11896 MVT VT = Op.getSimpleValueType();
11897 MVT EltVT = VT.getVectorElementType();
11899 if (EltVT == MVT::i1)
11900 return InsertBitToMaskVector(Op, DAG);
11903 SDValue N0 = Op.getOperand(0);
11904 SDValue N1 = Op.getOperand(1);
11905 SDValue N2 = Op.getOperand(2);
11906 if (!isa<ConstantSDNode>(N2))
11908 auto *N2C = cast<ConstantSDNode>(N2);
11909 unsigned IdxVal = N2C->getZExtValue();
11911 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11912 // into that, and then insert the subvector back into the result.
11913 if (VT.is256BitVector() || VT.is512BitVector()) {
11914 // With a 256-bit vector, we can insert into the zero element efficiently
11915 // using a blend if we have AVX or AVX2 and the right data type.
11916 if (VT.is256BitVector() && IdxVal == 0) {
11917 // TODO: It is worthwhile to cast integer to floating point and back
11918 // and incur a domain crossing penalty if that's what we'll end up
11919 // doing anyway after extracting to a 128-bit vector.
11920 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11921 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11922 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11923 N2 = DAG.getIntPtrConstant(1, dl);
11924 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11928 // Get the desired 128-bit vector chunk.
11929 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11931 // Insert the element into the desired chunk.
11932 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11933 assert(isPowerOf2_32(NumEltsIn128));
11934 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11935 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11937 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11938 DAG.getConstant(IdxIn128, dl, MVT::i32));
11940 // Insert the changed part back into the bigger vector
11941 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11943 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11945 if (Subtarget->hasSSE41()) {
11946 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11948 if (VT == MVT::v8i16) {
11949 Opc = X86ISD::PINSRW;
11951 assert(VT == MVT::v16i8);
11952 Opc = X86ISD::PINSRB;
11955 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11957 if (N1.getValueType() != MVT::i32)
11958 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11959 if (N2.getValueType() != MVT::i32)
11960 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11961 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11964 if (EltVT == MVT::f32) {
11965 // Bits [7:6] of the constant are the source select. This will always be
11966 // zero here. The DAG Combiner may combine an extract_elt index into
11967 // these bits. For example (insert (extract, 3), 2) could be matched by
11968 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11969 // Bits [5:4] of the constant are the destination select. This is the
11970 // value of the incoming immediate.
11971 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11972 // combine either bitwise AND or insert of float 0.0 to set these bits.
11974 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11975 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11976 // If this is an insertion of 32-bits into the low 32-bits of
11977 // a vector, we prefer to generate a blend with immediate rather
11978 // than an insertps. Blends are simpler operations in hardware and so
11979 // will always have equal or better performance than insertps.
11980 // But if optimizing for size and there's a load folding opportunity,
11981 // generate insertps because blendps does not have a 32-bit memory
11983 N2 = DAG.getIntPtrConstant(1, dl);
11984 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11985 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11987 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11988 // Create this as a scalar to vector..
11989 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11990 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11993 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11994 // PINSR* works with constant index.
11999 if (EltVT == MVT::i8)
12002 if (EltVT.getSizeInBits() == 16) {
12003 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12004 // as its second argument.
12005 if (N1.getValueType() != MVT::i32)
12006 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12007 if (N2.getValueType() != MVT::i32)
12008 N2 = DAG.getIntPtrConstant(IdxVal, dl);
12009 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12014 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12016 MVT OpVT = Op.getSimpleValueType();
12018 // If this is a 256-bit vector result, first insert into a 128-bit
12019 // vector and then insert into the 256-bit vector.
12020 if (!OpVT.is128BitVector()) {
12021 // Insert into a 128-bit vector.
12022 unsigned SizeFactor = OpVT.getSizeInBits()/128;
12023 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12024 OpVT.getVectorNumElements() / SizeFactor);
12026 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12028 // Insert the 128-bit vector.
12029 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12032 if (OpVT == MVT::v1i64 &&
12033 Op.getOperand(0).getValueType() == MVT::i64)
12034 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12036 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12037 assert(OpVT.is128BitVector() && "Expected an SSE type!");
12038 return DAG.getBitcast(
12039 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
12042 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
12043 // a simple subregister reference or explicit instructions to grab
12044 // upper bits of a vector.
12045 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12046 SelectionDAG &DAG) {
12048 SDValue In = Op.getOperand(0);
12049 SDValue Idx = Op.getOperand(1);
12050 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12051 MVT ResVT = Op.getSimpleValueType();
12052 MVT InVT = In.getSimpleValueType();
12054 if (Subtarget->hasFp256()) {
12055 if (ResVT.is128BitVector() &&
12056 (InVT.is256BitVector() || InVT.is512BitVector()) &&
12057 isa<ConstantSDNode>(Idx)) {
12058 return Extract128BitVector(In, IdxVal, DAG, dl);
12060 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12061 isa<ConstantSDNode>(Idx)) {
12062 return Extract256BitVector(In, IdxVal, DAG, dl);
12068 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
12069 // simple superregister reference or explicit instructions to insert
12070 // the upper bits of a vector.
12071 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12072 SelectionDAG &DAG) {
12073 if (!Subtarget->hasAVX())
12077 SDValue Vec = Op.getOperand(0);
12078 SDValue SubVec = Op.getOperand(1);
12079 SDValue Idx = Op.getOperand(2);
12081 if (!isa<ConstantSDNode>(Idx))
12084 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12085 MVT OpVT = Op.getSimpleValueType();
12086 MVT SubVecVT = SubVec.getSimpleValueType();
12088 // Fold two 16-byte subvector loads into one 32-byte load:
12089 // (insert_subvector (insert_subvector undef, (load addr), 0),
12090 // (load addr + 16), Elts/2)
12092 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12093 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12094 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12095 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12096 if (Idx2 && Idx2->getZExtValue() == 0) {
12097 SDValue SubVec2 = Vec.getOperand(1);
12098 // If needed, look through a bitcast to get to the load.
12099 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12100 SubVec2 = SubVec2.getOperand(0);
12102 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12104 unsigned Alignment = FirstLd->getAlignment();
12105 unsigned AS = FirstLd->getAddressSpace();
12106 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12107 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12108 OpVT, AS, Alignment, &Fast) && Fast) {
12109 SDValue Ops[] = { SubVec2, SubVec };
12110 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12117 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12118 SubVecVT.is128BitVector())
12119 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12121 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12122 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12124 if (OpVT.getVectorElementType() == MVT::i1)
12125 return Insert1BitVector(Op, DAG);
12130 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12131 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12132 // one of the above mentioned nodes. It has to be wrapped because otherwise
12133 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12134 // be used to form addressing mode. These wrapped nodes will be selected
12137 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12138 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12140 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12141 // global base reg.
12142 unsigned char OpFlag = 0;
12143 unsigned WrapperKind = X86ISD::Wrapper;
12144 CodeModel::Model M = DAG.getTarget().getCodeModel();
12146 if (Subtarget->isPICStyleRIPRel() &&
12147 (M == CodeModel::Small || M == CodeModel::Kernel))
12148 WrapperKind = X86ISD::WrapperRIP;
12149 else if (Subtarget->isPICStyleGOT())
12150 OpFlag = X86II::MO_GOTOFF;
12151 else if (Subtarget->isPICStyleStubPIC())
12152 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12154 auto PtrVT = getPointerTy(DAG.getDataLayout());
12155 SDValue Result = DAG.getTargetConstantPool(
12156 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12158 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12159 // With PIC, the address is actually $g + Offset.
12162 DAG.getNode(ISD::ADD, DL, PtrVT,
12163 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12169 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12170 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12172 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12173 // global base reg.
12174 unsigned char OpFlag = 0;
12175 unsigned WrapperKind = X86ISD::Wrapper;
12176 CodeModel::Model M = DAG.getTarget().getCodeModel();
12178 if (Subtarget->isPICStyleRIPRel() &&
12179 (M == CodeModel::Small || M == CodeModel::Kernel))
12180 WrapperKind = X86ISD::WrapperRIP;
12181 else if (Subtarget->isPICStyleGOT())
12182 OpFlag = X86II::MO_GOTOFF;
12183 else if (Subtarget->isPICStyleStubPIC())
12184 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12186 auto PtrVT = getPointerTy(DAG.getDataLayout());
12187 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12189 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12191 // With PIC, the address is actually $g + Offset.
12194 DAG.getNode(ISD::ADD, DL, PtrVT,
12195 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12201 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12202 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12204 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12205 // global base reg.
12206 unsigned char OpFlag = 0;
12207 unsigned WrapperKind = X86ISD::Wrapper;
12208 CodeModel::Model M = DAG.getTarget().getCodeModel();
12210 if (Subtarget->isPICStyleRIPRel() &&
12211 (M == CodeModel::Small || M == CodeModel::Kernel)) {
12212 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12213 OpFlag = X86II::MO_GOTPCREL;
12214 WrapperKind = X86ISD::WrapperRIP;
12215 } else if (Subtarget->isPICStyleGOT()) {
12216 OpFlag = X86II::MO_GOT;
12217 } else if (Subtarget->isPICStyleStubPIC()) {
12218 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12219 } else if (Subtarget->isPICStyleStubNoDynamic()) {
12220 OpFlag = X86II::MO_DARWIN_NONLAZY;
12223 auto PtrVT = getPointerTy(DAG.getDataLayout());
12224 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12227 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12229 // With PIC, the address is actually $g + Offset.
12230 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12231 !Subtarget->is64Bit()) {
12233 DAG.getNode(ISD::ADD, DL, PtrVT,
12234 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12237 // For symbols that require a load from a stub to get the address, emit the
12239 if (isGlobalStubReference(OpFlag))
12240 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12241 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12242 false, false, false, 0);
12248 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12249 // Create the TargetBlockAddressAddress node.
12250 unsigned char OpFlags =
12251 Subtarget->ClassifyBlockAddressReference();
12252 CodeModel::Model M = DAG.getTarget().getCodeModel();
12253 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12254 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12256 auto PtrVT = getPointerTy(DAG.getDataLayout());
12257 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12259 if (Subtarget->isPICStyleRIPRel() &&
12260 (M == CodeModel::Small || M == CodeModel::Kernel))
12261 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12263 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12265 // With PIC, the address is actually $g + Offset.
12266 if (isGlobalRelativeToPICBase(OpFlags)) {
12267 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12268 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12275 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12276 int64_t Offset, SelectionDAG &DAG) const {
12277 // Create the TargetGlobalAddress node, folding in the constant
12278 // offset if it is legal.
12279 unsigned char OpFlags =
12280 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12281 CodeModel::Model M = DAG.getTarget().getCodeModel();
12282 auto PtrVT = getPointerTy(DAG.getDataLayout());
12284 if (OpFlags == X86II::MO_NO_FLAG &&
12285 X86::isOffsetSuitableForCodeModel(Offset, M)) {
12286 // A direct static reference to a global.
12287 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12290 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12293 if (Subtarget->isPICStyleRIPRel() &&
12294 (M == CodeModel::Small || M == CodeModel::Kernel))
12295 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12297 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12299 // With PIC, the address is actually $g + Offset.
12300 if (isGlobalRelativeToPICBase(OpFlags)) {
12301 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12302 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12305 // For globals that require a load from a stub to get the address, emit the
12307 if (isGlobalStubReference(OpFlags))
12308 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12309 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12310 false, false, false, 0);
12312 // If there was a non-zero offset that we didn't fold, create an explicit
12313 // addition for it.
12315 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12316 DAG.getConstant(Offset, dl, PtrVT));
12322 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12323 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12324 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12325 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12329 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12330 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12331 unsigned char OperandFlags, bool LocalDynamic = false) {
12332 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12333 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12335 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12336 GA->getValueType(0),
12340 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12344 SDValue Ops[] = { Chain, TGA, *InFlag };
12345 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12347 SDValue Ops[] = { Chain, TGA };
12348 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12351 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12352 MFI->setAdjustsStack(true);
12353 MFI->setHasCalls(true);
12355 SDValue Flag = Chain.getValue(1);
12356 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12359 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12361 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12364 SDLoc dl(GA); // ? function entry point might be better
12365 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12366 DAG.getNode(X86ISD::GlobalBaseReg,
12367 SDLoc(), PtrVT), InFlag);
12368 InFlag = Chain.getValue(1);
12370 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12373 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12375 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12377 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12378 X86::RAX, X86II::MO_TLSGD);
12381 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12387 // Get the start address of the TLS block for this module.
12388 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12389 .getInfo<X86MachineFunctionInfo>();
12390 MFI->incNumLocalDynamicTLSAccesses();
12394 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12395 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12398 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12399 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12400 InFlag = Chain.getValue(1);
12401 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12402 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12405 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12409 unsigned char OperandFlags = X86II::MO_DTPOFF;
12410 unsigned WrapperKind = X86ISD::Wrapper;
12411 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12412 GA->getValueType(0),
12413 GA->getOffset(), OperandFlags);
12414 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12416 // Add x@dtpoff with the base.
12417 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12420 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12421 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12422 const EVT PtrVT, TLSModel::Model model,
12423 bool is64Bit, bool isPIC) {
12426 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12427 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12428 is64Bit ? 257 : 256));
12430 SDValue ThreadPointer =
12431 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12432 MachinePointerInfo(Ptr), false, false, false, 0);
12434 unsigned char OperandFlags = 0;
12435 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12437 unsigned WrapperKind = X86ISD::Wrapper;
12438 if (model == TLSModel::LocalExec) {
12439 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12440 } else if (model == TLSModel::InitialExec) {
12442 OperandFlags = X86II::MO_GOTTPOFF;
12443 WrapperKind = X86ISD::WrapperRIP;
12445 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12448 llvm_unreachable("Unexpected model");
12451 // emit "addl x@ntpoff,%eax" (local exec)
12452 // or "addl x@indntpoff,%eax" (initial exec)
12453 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12455 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12456 GA->getOffset(), OperandFlags);
12457 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12459 if (model == TLSModel::InitialExec) {
12460 if (isPIC && !is64Bit) {
12461 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12462 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12466 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12467 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12468 false, false, false, 0);
12471 // The address of the thread local variable is the add of the thread
12472 // pointer with the offset of the variable.
12473 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12477 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12479 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12481 // Cygwin uses emutls.
12482 // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12483 if (Subtarget->isTargetWindowsCygwin())
12484 return LowerToTLSEmulatedModel(GA, DAG);
12486 const GlobalValue *GV = GA->getGlobal();
12487 auto PtrVT = getPointerTy(DAG.getDataLayout());
12489 if (Subtarget->isTargetELF()) {
12490 if (DAG.getTarget().Options.EmulatedTLS)
12491 return LowerToTLSEmulatedModel(GA, DAG);
12492 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12494 case TLSModel::GeneralDynamic:
12495 if (Subtarget->is64Bit())
12496 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12497 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12498 case TLSModel::LocalDynamic:
12499 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12500 Subtarget->is64Bit());
12501 case TLSModel::InitialExec:
12502 case TLSModel::LocalExec:
12503 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12504 DAG.getTarget().getRelocationModel() ==
12507 llvm_unreachable("Unknown TLS model.");
12510 if (Subtarget->isTargetDarwin()) {
12511 // Darwin only has one model of TLS. Lower to that.
12512 unsigned char OpFlag = 0;
12513 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12514 X86ISD::WrapperRIP : X86ISD::Wrapper;
12516 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12517 // global base reg.
12518 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12519 !Subtarget->is64Bit();
12521 OpFlag = X86II::MO_TLVP_PIC_BASE;
12523 OpFlag = X86II::MO_TLVP;
12525 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12526 GA->getValueType(0),
12527 GA->getOffset(), OpFlag);
12528 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12530 // With PIC32, the address is actually $g + Offset.
12532 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12533 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12536 // Lowering the machine isd will make sure everything is in the right
12538 SDValue Chain = DAG.getEntryNode();
12539 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12540 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12541 SDValue Args[] = { Chain, Offset };
12542 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12544 DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12545 DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12547 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12548 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12549 MFI->setAdjustsStack(true);
12551 // And our return value (tls address) is in the standard call return value
12553 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12554 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12557 if (Subtarget->isTargetKnownWindowsMSVC() ||
12558 Subtarget->isTargetWindowsGNU()) {
12559 // Just use the implicit TLS architecture
12560 // Need to generate someting similar to:
12561 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12563 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12564 // mov rcx, qword [rdx+rcx*8]
12565 // mov eax, .tls$:tlsvar
12566 // [rax+rcx] contains the address
12567 // Windows 64bit: gs:0x58
12568 // Windows 32bit: fs:__tls_array
12571 SDValue Chain = DAG.getEntryNode();
12573 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12574 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12575 // use its literal value of 0x2C.
12576 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12577 ? Type::getInt8PtrTy(*DAG.getContext(),
12579 : Type::getInt32PtrTy(*DAG.getContext(),
12582 SDValue TlsArray = Subtarget->is64Bit()
12583 ? DAG.getIntPtrConstant(0x58, dl)
12584 : (Subtarget->isTargetWindowsGNU()
12585 ? DAG.getIntPtrConstant(0x2C, dl)
12586 : DAG.getExternalSymbol("_tls_array", PtrVT));
12588 SDValue ThreadPointer =
12589 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12593 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12594 res = ThreadPointer;
12596 // Load the _tls_index variable
12597 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12598 if (Subtarget->is64Bit())
12599 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12600 MachinePointerInfo(), MVT::i32, false, false,
12603 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12606 auto &DL = DAG.getDataLayout();
12608 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12609 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12611 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12614 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12617 // Get the offset of start of .tls section
12618 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12619 GA->getValueType(0),
12620 GA->getOffset(), X86II::MO_SECREL);
12621 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12623 // The address of the thread local variable is the add of the thread
12624 // pointer with the offset of the variable.
12625 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12628 llvm_unreachable("TLS not implemented for this target.");
12631 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12632 /// and take a 2 x i32 value to shift plus a shift amount.
12633 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12634 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12635 MVT VT = Op.getSimpleValueType();
12636 unsigned VTBits = VT.getSizeInBits();
12638 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12639 SDValue ShOpLo = Op.getOperand(0);
12640 SDValue ShOpHi = Op.getOperand(1);
12641 SDValue ShAmt = Op.getOperand(2);
12642 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12643 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12645 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12646 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12647 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12648 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12649 : DAG.getConstant(0, dl, VT);
12651 SDValue Tmp2, Tmp3;
12652 if (Op.getOpcode() == ISD::SHL_PARTS) {
12653 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12654 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12656 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12657 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12660 // If the shift amount is larger or equal than the width of a part we can't
12661 // rely on the results of shld/shrd. Insert a test and select the appropriate
12662 // values for large shift amounts.
12663 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12664 DAG.getConstant(VTBits, dl, MVT::i8));
12665 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12666 AndNode, DAG.getConstant(0, dl, MVT::i8));
12669 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12670 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12671 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12673 if (Op.getOpcode() == ISD::SHL_PARTS) {
12674 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12675 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12677 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12678 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12681 SDValue Ops[2] = { Lo, Hi };
12682 return DAG.getMergeValues(Ops, dl);
12685 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12686 SelectionDAG &DAG) const {
12687 SDValue Src = Op.getOperand(0);
12688 MVT SrcVT = Src.getSimpleValueType();
12689 MVT VT = Op.getSimpleValueType();
12692 if (SrcVT.isVector()) {
12693 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12694 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12695 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12696 DAG.getUNDEF(SrcVT)));
12698 if (SrcVT.getVectorElementType() == MVT::i1) {
12699 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12700 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12701 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12706 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12707 "Unknown SINT_TO_FP to lower!");
12709 // These are really Legal; return the operand so the caller accepts it as
12711 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12713 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12714 Subtarget->is64Bit()) {
12718 SDValue ValueToStore = Op.getOperand(0);
12719 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12720 !Subtarget->is64Bit())
12721 // Bitcasting to f64 here allows us to do a single 64-bit store from
12722 // an SSE register, avoiding the store forwarding penalty that would come
12723 // with two 32-bit stores.
12724 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
12726 unsigned Size = SrcVT.getSizeInBits()/8;
12727 MachineFunction &MF = DAG.getMachineFunction();
12728 auto PtrVT = getPointerTy(MF.getDataLayout());
12729 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12730 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12731 SDValue Chain = DAG.getStore(
12732 DAG.getEntryNode(), dl, ValueToStore, StackSlot,
12733 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12735 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12738 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12740 SelectionDAG &DAG) const {
12744 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12746 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12748 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12750 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12752 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12753 MachineMemOperand *MMO;
12755 int SSFI = FI->getIndex();
12756 MMO = DAG.getMachineFunction().getMachineMemOperand(
12757 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12758 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12760 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12761 StackSlot = StackSlot.getOperand(1);
12763 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12764 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12766 Tys, Ops, SrcVT, MMO);
12769 Chain = Result.getValue(1);
12770 SDValue InFlag = Result.getValue(2);
12772 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12773 // shouldn't be necessary except that RFP cannot be live across
12774 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12775 MachineFunction &MF = DAG.getMachineFunction();
12776 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12777 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12778 auto PtrVT = getPointerTy(MF.getDataLayout());
12779 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12780 Tys = DAG.getVTList(MVT::Other);
12782 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12784 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12785 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12786 MachineMemOperand::MOStore, SSFISize, SSFISize);
12788 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12789 Ops, Op.getValueType(), MMO);
12790 Result = DAG.getLoad(
12791 Op.getValueType(), DL, Chain, StackSlot,
12792 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12793 false, false, false, 0);
12799 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12800 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12801 SelectionDAG &DAG) const {
12802 // This algorithm is not obvious. Here it is what we're trying to output:
12805 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12806 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12808 haddpd %xmm0, %xmm0
12810 pshufd $0x4e, %xmm0, %xmm1
12816 LLVMContext *Context = DAG.getContext();
12818 // Build some magic constants.
12819 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12820 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12821 auto PtrVT = getPointerTy(DAG.getDataLayout());
12822 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12824 SmallVector<Constant*,2> CV1;
12826 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12827 APInt(64, 0x4330000000000000ULL))));
12829 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12830 APInt(64, 0x4530000000000000ULL))));
12831 Constant *C1 = ConstantVector::get(CV1);
12832 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12834 // Load the 64-bit value into an XMM register.
12835 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12838 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12839 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12840 false, false, false, 16);
12842 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12845 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12846 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12847 false, false, false, 16);
12848 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12849 // TODO: Are there any fast-math-flags to propagate here?
12850 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12853 if (Subtarget->hasSSE3()) {
12854 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12855 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12857 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12858 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12860 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12861 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12864 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12865 DAG.getIntPtrConstant(0, dl));
12868 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12869 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12870 SelectionDAG &DAG) const {
12872 // FP constant to bias correct the final result.
12873 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12876 // Load the 32-bit value into an XMM register.
12877 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12880 // Zero out the upper parts of the register.
12881 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12883 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12884 DAG.getBitcast(MVT::v2f64, Load),
12885 DAG.getIntPtrConstant(0, dl));
12887 // Or the load with the bias.
12888 SDValue Or = DAG.getNode(
12889 ISD::OR, dl, MVT::v2i64,
12890 DAG.getBitcast(MVT::v2i64,
12891 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12892 DAG.getBitcast(MVT::v2i64,
12893 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12895 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12896 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12898 // Subtract the bias.
12899 // TODO: Are there any fast-math-flags to propagate here?
12900 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12902 // Handle final rounding.
12903 MVT DestVT = Op.getSimpleValueType();
12905 if (DestVT.bitsLT(MVT::f64))
12906 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12907 DAG.getIntPtrConstant(0, dl));
12908 if (DestVT.bitsGT(MVT::f64))
12909 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12911 // Handle final rounding.
12915 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12916 const X86Subtarget &Subtarget) {
12917 // The algorithm is the following:
12918 // #ifdef __SSE4_1__
12919 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12920 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12921 // (uint4) 0x53000000, 0xaa);
12923 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12924 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12926 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12927 // return (float4) lo + fhi;
12929 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12930 // reassociate the two FADDs, and if we do that, the algorithm fails
12931 // spectacularly (PR24512).
12932 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12933 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12934 // there's also the MachineCombiner reassociations happening on Machine IR.
12935 if (DAG.getTarget().Options.UnsafeFPMath)
12939 SDValue V = Op->getOperand(0);
12940 MVT VecIntVT = V.getSimpleValueType();
12941 bool Is128 = VecIntVT == MVT::v4i32;
12942 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12943 // If we convert to something else than the supported type, e.g., to v4f64,
12945 if (VecFloatVT != Op->getSimpleValueType(0))
12948 unsigned NumElts = VecIntVT.getVectorNumElements();
12949 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12950 "Unsupported custom type");
12951 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12953 // In the #idef/#else code, we have in common:
12954 // - The vector of constants:
12960 // Create the splat vector for 0x4b000000.
12961 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12962 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12963 CstLow, CstLow, CstLow, CstLow};
12964 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12965 makeArrayRef(&CstLowArray[0], NumElts));
12966 // Create the splat vector for 0x53000000.
12967 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12968 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12969 CstHigh, CstHigh, CstHigh, CstHigh};
12970 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12971 makeArrayRef(&CstHighArray[0], NumElts));
12973 // Create the right shift.
12974 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12975 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12976 CstShift, CstShift, CstShift, CstShift};
12977 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12978 makeArrayRef(&CstShiftArray[0], NumElts));
12979 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12982 if (Subtarget.hasSSE41()) {
12983 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12984 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12985 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12986 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12987 // Low will be bitcasted right away, so do not bother bitcasting back to its
12989 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12990 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12991 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12992 // (uint4) 0x53000000, 0xaa);
12993 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12994 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12995 // High will be bitcasted right away, so do not bother bitcasting back to
12996 // its original type.
12997 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12998 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
13000 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
13001 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13002 CstMask, CstMask, CstMask);
13003 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13004 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13005 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13007 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
13008 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13011 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13012 SDValue CstFAdd = DAG.getConstantFP(
13013 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
13014 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13015 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13016 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13017 makeArrayRef(&CstFAddArray[0], NumElts));
13019 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13020 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
13021 // TODO: Are there any fast-math-flags to propagate here?
13023 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13024 // return (float4) lo + fhi;
13025 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
13026 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13029 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13030 SelectionDAG &DAG) const {
13031 SDValue N0 = Op.getOperand(0);
13032 MVT SVT = N0.getSimpleValueType();
13035 switch (SVT.SimpleTy) {
13037 llvm_unreachable("Custom UINT_TO_FP is not supported!");
13042 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13043 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13044 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13048 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13051 assert(Subtarget->hasAVX512());
13052 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13053 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13057 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13058 SelectionDAG &DAG) const {
13059 SDValue N0 = Op.getOperand(0);
13061 auto PtrVT = getPointerTy(DAG.getDataLayout());
13063 if (Op.getSimpleValueType().isVector())
13064 return lowerUINT_TO_FP_vec(Op, DAG);
13066 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13067 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13068 // the optimization here.
13069 if (DAG.SignBitIsZero(N0))
13070 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13072 MVT SrcVT = N0.getSimpleValueType();
13073 MVT DstVT = Op.getSimpleValueType();
13075 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13076 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13077 // Conversions from unsigned i32 to f32/f64 are legal,
13078 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
13082 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13083 return LowerUINT_TO_FP_i64(Op, DAG);
13084 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13085 return LowerUINT_TO_FP_i32(Op, DAG);
13086 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13089 // Make a 64-bit buffer, and use it to build an FILD.
13090 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13091 if (SrcVT == MVT::i32) {
13092 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13093 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13094 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13095 StackSlot, MachinePointerInfo(),
13097 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13098 OffsetSlot, MachinePointerInfo(),
13100 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13104 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13105 SDValue ValueToStore = Op.getOperand(0);
13106 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget->is64Bit())
13107 // Bitcasting to f64 here allows us to do a single 64-bit store from
13108 // an SSE register, avoiding the store forwarding penalty that would come
13109 // with two 32-bit stores.
13110 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13111 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore,
13112 StackSlot, MachinePointerInfo(),
13114 // For i64 source, we need to add the appropriate power of 2 if the input
13115 // was negative. This is the same as the optimization in
13116 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13117 // we must be careful to do the computation in x87 extended precision, not
13118 // in SSE. (The generic code can't know it's OK to do this, or how to.)
13119 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13120 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13121 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13122 MachineMemOperand::MOLoad, 8, 8);
13124 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13125 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13126 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13129 APInt FF(32, 0x5F800000ULL);
13131 // Check whether the sign bit is set.
13132 SDValue SignSet = DAG.getSetCC(
13133 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13134 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13136 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13137 SDValue FudgePtr = DAG.getConstantPool(
13138 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13140 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13141 SDValue Zero = DAG.getIntPtrConstant(0, dl);
13142 SDValue Four = DAG.getIntPtrConstant(4, dl);
13143 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13145 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13147 // Load the value out, extending it from f32 to f80.
13148 // FIXME: Avoid the extend by constructing the right constant pool?
13149 SDValue Fudge = DAG.getExtLoad(
13150 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13151 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13152 false, false, false, 4);
13153 // Extend everything to 80 bits to force it to be done on x87.
13154 // TODO: Are there any fast-math-flags to propagate here?
13155 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13156 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13157 DAG.getIntPtrConstant(0, dl));
13160 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13161 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13162 // just return an <SDValue(), SDValue()> pair.
13163 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13164 // to i16, i32 or i64, and we lower it to a legal sequence.
13165 // If lowered to the final integer result we return a <result, SDValue()> pair.
13166 // Otherwise we lower it to a sequence ending with a FIST, return a
13167 // <FIST, StackSlot> pair, and the caller is responsible for loading
13168 // the final integer result from StackSlot.
13169 std::pair<SDValue,SDValue>
13170 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13171 bool IsSigned, bool IsReplace) const {
13174 EVT DstTy = Op.getValueType();
13175 EVT TheVT = Op.getOperand(0).getValueType();
13176 auto PtrVT = getPointerTy(DAG.getDataLayout());
13178 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13179 // f16 must be promoted before using the lowering in this routine.
13180 // fp128 does not use this lowering.
13181 return std::make_pair(SDValue(), SDValue());
13184 // If using FIST to compute an unsigned i64, we'll need some fixup
13185 // to handle values above the maximum signed i64. A FIST is always
13186 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13187 bool UnsignedFixup = !IsSigned &&
13188 DstTy == MVT::i64 &&
13189 (!Subtarget->is64Bit() ||
13190 !isScalarFPTypeInSSEReg(TheVT));
13192 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13193 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13194 // The low 32 bits of the fist result will have the correct uint32 result.
13195 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13199 assert(DstTy.getSimpleVT() <= MVT::i64 &&
13200 DstTy.getSimpleVT() >= MVT::i16 &&
13201 "Unknown FP_TO_INT to lower!");
13203 // These are really Legal.
13204 if (DstTy == MVT::i32 &&
13205 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13206 return std::make_pair(SDValue(), SDValue());
13207 if (Subtarget->is64Bit() &&
13208 DstTy == MVT::i64 &&
13209 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13210 return std::make_pair(SDValue(), SDValue());
13212 // We lower FP->int64 into FISTP64 followed by a load from a temporary
13214 MachineFunction &MF = DAG.getMachineFunction();
13215 unsigned MemSize = DstTy.getSizeInBits()/8;
13216 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13217 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13220 switch (DstTy.getSimpleVT().SimpleTy) {
13221 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13222 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13223 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13224 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13227 SDValue Chain = DAG.getEntryNode();
13228 SDValue Value = Op.getOperand(0);
13229 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13231 if (UnsignedFixup) {
13233 // Conversion to unsigned i64 is implemented with a select,
13234 // depending on whether the source value fits in the range
13235 // of a signed i64. Let Thresh be the FP equivalent of
13236 // 0x8000000000000000ULL.
13238 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13239 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
13240 // Fist-to-mem64 FistSrc
13241 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13242 // to XOR'ing the high 32 bits with Adjust.
13244 // Being a power of 2, Thresh is exactly representable in all FP formats.
13245 // For X87 we'd like to use the smallest FP type for this constant, but
13246 // for DAG type consistency we have to match the FP operand type.
13248 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13249 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13250 bool LosesInfo = false;
13251 if (TheVT == MVT::f64)
13252 // The rounding mode is irrelevant as the conversion should be exact.
13253 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13255 else if (TheVT == MVT::f80)
13256 Status = Thresh.convert(APFloat::x87DoubleExtended,
13257 APFloat::rmNearestTiesToEven, &LosesInfo);
13259 assert(Status == APFloat::opOK && !LosesInfo &&
13260 "FP conversion should have been exact");
13262 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13264 SDValue Cmp = DAG.getSetCC(DL,
13265 getSetCCResultType(DAG.getDataLayout(),
13266 *DAG.getContext(), TheVT),
13267 Value, ThreshVal, ISD::SETLT);
13268 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13269 DAG.getConstant(0, DL, MVT::i32),
13270 DAG.getConstant(0x80000000, DL, MVT::i32));
13271 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13272 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13273 *DAG.getContext(), TheVT),
13274 Value, ThreshVal, ISD::SETLT);
13275 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13278 // FIXME This causes a redundant load/store if the SSE-class value is already
13279 // in memory, such as if it is on the callstack.
13280 if (isScalarFPTypeInSSEReg(TheVT)) {
13281 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13282 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13283 MachinePointerInfo::getFixedStack(MF, SSFI), false,
13285 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13287 Chain, StackSlot, DAG.getValueType(TheVT)
13290 MachineMemOperand *MMO =
13291 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13292 MachineMemOperand::MOLoad, MemSize, MemSize);
13293 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13294 Chain = Value.getValue(1);
13295 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13296 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13299 MachineMemOperand *MMO =
13300 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13301 MachineMemOperand::MOStore, MemSize, MemSize);
13303 if (UnsignedFixup) {
13305 // Insert the FIST, load its result as two i32's,
13306 // and XOR the high i32 with Adjust.
13308 SDValue FistOps[] = { Chain, Value, StackSlot };
13309 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13310 FistOps, DstTy, MMO);
13312 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13313 MachinePointerInfo(),
13314 false, false, false, 0);
13315 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13316 DAG.getConstant(4, DL, PtrVT));
13318 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13319 MachinePointerInfo(),
13320 false, false, false, 0);
13321 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13323 if (Subtarget->is64Bit()) {
13324 // Join High32 and Low32 into a 64-bit result.
13325 // (High32 << 32) | Low32
13326 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13327 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13328 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13329 DAG.getConstant(32, DL, MVT::i8));
13330 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13331 return std::make_pair(Result, SDValue());
13334 SDValue ResultOps[] = { Low32, High32 };
13336 SDValue pair = IsReplace
13337 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13338 : DAG.getMergeValues(ResultOps, DL);
13339 return std::make_pair(pair, SDValue());
13341 // Build the FP_TO_INT*_IN_MEM
13342 SDValue Ops[] = { Chain, Value, StackSlot };
13343 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13345 return std::make_pair(FIST, StackSlot);
13349 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13350 const X86Subtarget *Subtarget) {
13351 MVT VT = Op->getSimpleValueType(0);
13352 SDValue In = Op->getOperand(0);
13353 MVT InVT = In.getSimpleValueType();
13356 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13357 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13359 // Optimize vectors in AVX mode:
13362 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
13363 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
13364 // Concat upper and lower parts.
13367 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
13368 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
13369 // Concat upper and lower parts.
13372 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13373 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13374 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13377 if (Subtarget->hasInt256())
13378 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13380 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13381 SDValue Undef = DAG.getUNDEF(InVT);
13382 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13383 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13384 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13386 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13387 VT.getVectorNumElements()/2);
13389 OpLo = DAG.getBitcast(HVT, OpLo);
13390 OpHi = DAG.getBitcast(HVT, OpHi);
13392 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13395 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13396 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13397 MVT VT = Op->getSimpleValueType(0);
13398 SDValue In = Op->getOperand(0);
13399 MVT InVT = In.getSimpleValueType();
13401 unsigned int NumElts = VT.getVectorNumElements();
13402 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13405 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13406 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13408 assert(InVT.getVectorElementType() == MVT::i1);
13409 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13411 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13413 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13415 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13416 if (VT.is512BitVector())
13418 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13421 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13422 SelectionDAG &DAG) {
13423 if (Subtarget->hasFp256())
13424 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13430 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13431 SelectionDAG &DAG) {
13433 MVT VT = Op.getSimpleValueType();
13434 SDValue In = Op.getOperand(0);
13435 MVT SVT = In.getSimpleValueType();
13437 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13438 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13440 if (Subtarget->hasFp256())
13441 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13444 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13445 VT.getVectorNumElements() != SVT.getVectorNumElements());
13449 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13450 const X86Subtarget *Subtarget) {
13453 MVT VT = Op.getSimpleValueType();
13454 SDValue In = Op.getOperand(0);
13455 MVT InVT = In.getSimpleValueType();
13457 assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13459 // Shift LSB to MSB and use VPMOVB2M - SKX.
13460 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13461 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13462 Subtarget->hasBWI()) || // legal, will go to VPMOVB2M, VPMOVW2M
13463 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13464 InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13465 Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13466 // Shift packed bytes not supported natively, bitcast to dword
13467 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13468 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13469 DAG.getBitcast(ExtVT, In),
13470 DAG.getConstant(ShiftInx, DL, ExtVT));
13471 ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13472 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13474 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13475 Subtarget->hasDQI()) || // legal, will go to VPMOVD2M, VPMOVQ2M
13476 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13477 InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13478 Subtarget->hasVLX())) { // legal, will go to VPMOVD2M, VPMOVQ2M
13480 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13481 DAG.getConstant(ShiftInx, DL, InVT));
13482 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13485 // Shift LSB to MSB, extend if necessary and use TESTM.
13486 unsigned NumElts = InVT.getVectorNumElements();
13487 if (InVT.getSizeInBits() < 512 &&
13488 (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13489 !Subtarget->hasVLX())) {
13490 assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13492 // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13493 // so vector should be extended to packed dword/qword.
13494 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13495 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13497 ShiftInx = InVT.getScalarSizeInBits() - 1;
13500 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13501 DAG.getConstant(ShiftInx, DL, InVT));
13502 return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13505 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13507 MVT VT = Op.getSimpleValueType();
13508 SDValue In = Op.getOperand(0);
13509 MVT InVT = In.getSimpleValueType();
13511 if (VT == MVT::i1) {
13512 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13513 "Invalid scalar TRUNCATE operation");
13514 if (InVT.getSizeInBits() >= 32)
13516 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13517 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13519 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13520 "Invalid TRUNCATE operation");
13522 if (VT.getVectorElementType() == MVT::i1)
13523 return LowerTruncateVecI1(Op, DAG, Subtarget);
13525 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13526 if (Subtarget->hasAVX512()) {
13527 // word to byte only under BWI
13528 if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13529 return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13530 DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13531 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13533 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13534 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13535 if (Subtarget->hasInt256()) {
13536 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13537 In = DAG.getBitcast(MVT::v8i32, In);
13538 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13540 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13541 DAG.getIntPtrConstant(0, DL));
13544 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13545 DAG.getIntPtrConstant(0, DL));
13546 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13547 DAG.getIntPtrConstant(2, DL));
13548 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13549 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13550 static const int ShufMask[] = {0, 2, 4, 6};
13551 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13554 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13555 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13556 if (Subtarget->hasInt256()) {
13557 In = DAG.getBitcast(MVT::v32i8, In);
13559 SmallVector<SDValue,32> pshufbMask;
13560 for (unsigned i = 0; i < 2; ++i) {
13561 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13562 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13563 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13564 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13565 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13566 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13567 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13568 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13569 for (unsigned j = 0; j < 8; ++j)
13570 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13572 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13573 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13574 In = DAG.getBitcast(MVT::v4i64, In);
13576 static const int ShufMask[] = {0, 2, -1, -1};
13577 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13579 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13580 DAG.getIntPtrConstant(0, DL));
13581 return DAG.getBitcast(VT, In);
13584 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13585 DAG.getIntPtrConstant(0, DL));
13587 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13588 DAG.getIntPtrConstant(4, DL));
13590 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13591 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13593 // The PSHUFB mask:
13594 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13595 -1, -1, -1, -1, -1, -1, -1, -1};
13597 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13598 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13599 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13601 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13602 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13604 // The MOVLHPS Mask:
13605 static const int ShufMask2[] = {0, 1, 4, 5};
13606 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13607 return DAG.getBitcast(MVT::v8i16, res);
13610 // Handle truncation of V256 to V128 using shuffles.
13611 if (!VT.is128BitVector() || !InVT.is256BitVector())
13614 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13616 unsigned NumElems = VT.getVectorNumElements();
13617 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13619 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13620 // Prepare truncation shuffle mask
13621 for (unsigned i = 0; i != NumElems; ++i)
13622 MaskVec[i] = i * 2;
13623 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13624 DAG.getUNDEF(NVT), &MaskVec[0]);
13625 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13626 DAG.getIntPtrConstant(0, DL));
13629 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13630 SelectionDAG &DAG) const {
13631 assert(!Op.getSimpleValueType().isVector());
13633 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13634 /*IsSigned=*/ true, /*IsReplace=*/ false);
13635 SDValue FIST = Vals.first, StackSlot = Vals.second;
13636 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13637 if (!FIST.getNode())
13640 if (StackSlot.getNode())
13641 // Load the result.
13642 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13643 FIST, StackSlot, MachinePointerInfo(),
13644 false, false, false, 0);
13646 // The node is the result.
13650 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13651 SelectionDAG &DAG) const {
13652 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13653 /*IsSigned=*/ false, /*IsReplace=*/ false);
13654 SDValue FIST = Vals.first, StackSlot = Vals.second;
13655 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13656 if (!FIST.getNode())
13659 if (StackSlot.getNode())
13660 // Load the result.
13661 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13662 FIST, StackSlot, MachinePointerInfo(),
13663 false, false, false, 0);
13665 // The node is the result.
13669 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13671 MVT VT = Op.getSimpleValueType();
13672 SDValue In = Op.getOperand(0);
13673 MVT SVT = In.getSimpleValueType();
13675 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13677 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13678 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13679 In, DAG.getUNDEF(SVT)));
13682 /// The only differences between FABS and FNEG are the mask and the logic op.
13683 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13684 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13685 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13686 "Wrong opcode for lowering FABS or FNEG.");
13688 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13690 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13691 // into an FNABS. We'll lower the FABS after that if it is still in use.
13693 for (SDNode *User : Op->uses())
13694 if (User->getOpcode() == ISD::FNEG)
13698 MVT VT = Op.getSimpleValueType();
13700 bool IsF128 = (VT == MVT::f128);
13702 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13703 // decide if we should generate a 16-byte constant mask when we only need 4 or
13704 // 8 bytes for the scalar case.
13710 if (VT.isVector()) {
13712 EltVT = VT.getVectorElementType();
13713 NumElts = VT.getVectorNumElements();
13714 } else if (IsF128) {
13715 // SSE instructions are used for optimized f128 logical operations.
13716 LogicVT = MVT::f128;
13720 // There are no scalar bitwise logical SSE/AVX instructions, so we
13721 // generate a 16-byte vector constant and logic op even for the scalar case.
13722 // Using a 16-byte mask allows folding the load of the mask with
13723 // the logic op, so it can save (~4 bytes) on code size.
13724 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13726 NumElts = (VT == MVT::f64) ? 2 : 4;
13729 unsigned EltBits = EltVT.getSizeInBits();
13730 LLVMContext *Context = DAG.getContext();
13731 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13733 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13734 Constant *C = ConstantInt::get(*Context, MaskElt);
13735 C = ConstantVector::getSplat(NumElts, C);
13736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13737 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13738 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13740 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13741 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13742 false, false, false, Alignment);
13744 SDValue Op0 = Op.getOperand(0);
13745 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13747 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13748 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13750 if (VT.isVector() || IsF128)
13751 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13753 // For the scalar case extend to a 128-bit vector, perform the logic op,
13754 // and extract the scalar result back out.
13755 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13756 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13757 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13758 DAG.getIntPtrConstant(0, dl));
13761 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13763 LLVMContext *Context = DAG.getContext();
13764 SDValue Op0 = Op.getOperand(0);
13765 SDValue Op1 = Op.getOperand(1);
13767 MVT VT = Op.getSimpleValueType();
13768 MVT SrcVT = Op1.getSimpleValueType();
13769 bool IsF128 = (VT == MVT::f128);
13771 // If second operand is smaller, extend it first.
13772 if (SrcVT.bitsLT(VT)) {
13773 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13776 // And if it is bigger, shrink it first.
13777 if (SrcVT.bitsGT(VT)) {
13778 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13782 // At this point the operands and the result should have the same
13783 // type, and that won't be f80 since that is not custom lowered.
13784 assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13785 "Unexpected type in LowerFCOPYSIGN");
13787 const fltSemantics &Sem =
13788 VT == MVT::f64 ? APFloat::IEEEdouble :
13789 (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13790 const unsigned SizeInBits = VT.getSizeInBits();
13792 SmallVector<Constant *, 4> CV(
13793 VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13794 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13796 // First, clear all bits but the sign bit from the second operand (sign).
13797 CV[0] = ConstantFP::get(*Context,
13798 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13799 Constant *C = ConstantVector::get(CV);
13800 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13801 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13803 // Perform all logic operations as 16-byte vectors because there are no
13804 // scalar FP logic instructions in SSE. This allows load folding of the
13805 // constants into the logic instructions.
13806 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13808 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13809 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13810 false, false, false, 16);
13812 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13813 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13815 // Next, clear the sign bit from the first operand (magnitude).
13816 // If it's a constant, we can clear it here.
13817 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13818 APFloat APF = Op0CN->getValueAPF();
13819 // If the magnitude is a positive zero, the sign bit alone is enough.
13820 if (APF.isPosZero())
13821 return IsF128 ? SignBit :
13822 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13823 DAG.getIntPtrConstant(0, dl));
13825 CV[0] = ConstantFP::get(*Context, APF);
13827 CV[0] = ConstantFP::get(
13829 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13831 C = ConstantVector::get(CV);
13832 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13834 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13835 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13836 false, false, false, 16);
13837 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13838 if (!isa<ConstantFPSDNode>(Op0)) {
13840 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13841 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13843 // OR the magnitude value with the sign bit.
13844 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13845 return IsF128 ? Val :
13846 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13847 DAG.getIntPtrConstant(0, dl));
13850 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13851 SDValue N0 = Op.getOperand(0);
13853 MVT VT = Op.getSimpleValueType();
13855 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13856 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13857 DAG.getConstant(1, dl, VT));
13858 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13861 // Check whether an OR'd tree is PTEST-able.
13862 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13863 SelectionDAG &DAG) {
13864 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13866 if (!Subtarget->hasSSE41())
13869 if (!Op->hasOneUse())
13872 SDNode *N = Op.getNode();
13875 SmallVector<SDValue, 8> Opnds;
13876 DenseMap<SDValue, unsigned> VecInMap;
13877 SmallVector<SDValue, 8> VecIns;
13878 EVT VT = MVT::Other;
13880 // Recognize a special case where a vector is casted into wide integer to
13882 Opnds.push_back(N->getOperand(0));
13883 Opnds.push_back(N->getOperand(1));
13885 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13886 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13887 // BFS traverse all OR'd operands.
13888 if (I->getOpcode() == ISD::OR) {
13889 Opnds.push_back(I->getOperand(0));
13890 Opnds.push_back(I->getOperand(1));
13891 // Re-evaluate the number of nodes to be traversed.
13892 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13896 // Quit if a non-EXTRACT_VECTOR_ELT
13897 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13900 // Quit if without a constant index.
13901 SDValue Idx = I->getOperand(1);
13902 if (!isa<ConstantSDNode>(Idx))
13905 SDValue ExtractedFromVec = I->getOperand(0);
13906 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13907 if (M == VecInMap.end()) {
13908 VT = ExtractedFromVec.getValueType();
13909 // Quit if not 128/256-bit vector.
13910 if (!VT.is128BitVector() && !VT.is256BitVector())
13912 // Quit if not the same type.
13913 if (VecInMap.begin() != VecInMap.end() &&
13914 VT != VecInMap.begin()->first.getValueType())
13916 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13917 VecIns.push_back(ExtractedFromVec);
13919 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13922 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13923 "Not extracted from 128-/256-bit vector.");
13925 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13927 for (DenseMap<SDValue, unsigned>::const_iterator
13928 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13929 // Quit if not all elements are used.
13930 if (I->second != FullMask)
13934 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13936 // Cast all vectors into TestVT for PTEST.
13937 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13938 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13940 // If more than one full vectors are evaluated, OR them first before PTEST.
13941 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13942 // Each iteration will OR 2 nodes and append the result until there is only
13943 // 1 node left, i.e. the final OR'd value of all vectors.
13944 SDValue LHS = VecIns[Slot];
13945 SDValue RHS = VecIns[Slot + 1];
13946 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13949 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13950 VecIns.back(), VecIns.back());
13953 /// \brief return true if \c Op has a use that doesn't just read flags.
13954 static bool hasNonFlagsUse(SDValue Op) {
13955 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13957 SDNode *User = *UI;
13958 unsigned UOpNo = UI.getOperandNo();
13959 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13960 // Look pass truncate.
13961 UOpNo = User->use_begin().getOperandNo();
13962 User = *User->use_begin();
13965 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13966 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13972 /// Emit nodes that will be selected as "test Op0,Op0", or something
13974 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13975 SelectionDAG &DAG) const {
13976 if (Op.getValueType() == MVT::i1) {
13977 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13978 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13979 DAG.getConstant(0, dl, MVT::i8));
13981 // CF and OF aren't always set the way we want. Determine which
13982 // of these we need.
13983 bool NeedCF = false;
13984 bool NeedOF = false;
13987 case X86::COND_A: case X86::COND_AE:
13988 case X86::COND_B: case X86::COND_BE:
13991 case X86::COND_G: case X86::COND_GE:
13992 case X86::COND_L: case X86::COND_LE:
13993 case X86::COND_O: case X86::COND_NO: {
13994 // Check if we really need to set the
13995 // Overflow flag. If NoSignedWrap is present
13996 // that is not actually needed.
13997 switch (Op->getOpcode()) {
14002 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
14003 if (BinNode->Flags.hasNoSignedWrap())
14013 // See if we can use the EFLAGS value from the operand instead of
14014 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14015 // we prove that the arithmetic won't overflow, we can't use OF or CF.
14016 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14017 // Emit a CMP with 0, which is the TEST pattern.
14018 //if (Op.getValueType() == MVT::i1)
14019 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14020 // DAG.getConstant(0, MVT::i1));
14021 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14022 DAG.getConstant(0, dl, Op.getValueType()));
14024 unsigned Opcode = 0;
14025 unsigned NumOperands = 0;
14027 // Truncate operations may prevent the merge of the SETCC instruction
14028 // and the arithmetic instruction before it. Attempt to truncate the operands
14029 // of the arithmetic instruction and use a reduced bit-width instruction.
14030 bool NeedTruncation = false;
14031 SDValue ArithOp = Op;
14032 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14033 SDValue Arith = Op->getOperand(0);
14034 // Both the trunc and the arithmetic op need to have one user each.
14035 if (Arith->hasOneUse())
14036 switch (Arith.getOpcode()) {
14043 NeedTruncation = true;
14049 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14050 // which may be the result of a CAST. We use the variable 'Op', which is the
14051 // non-casted variable when we check for possible users.
14052 switch (ArithOp.getOpcode()) {
14054 // Due to an isel shortcoming, be conservative if this add is likely to be
14055 // selected as part of a load-modify-store instruction. When the root node
14056 // in a match is a store, isel doesn't know how to remap non-chain non-flag
14057 // uses of other nodes in the match, such as the ADD in this case. This
14058 // leads to the ADD being left around and reselected, with the result being
14059 // two adds in the output. Alas, even if none our users are stores, that
14060 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
14061 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
14062 // climbing the DAG back to the root, and it doesn't seem to be worth the
14064 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14065 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14066 if (UI->getOpcode() != ISD::CopyToReg &&
14067 UI->getOpcode() != ISD::SETCC &&
14068 UI->getOpcode() != ISD::STORE)
14071 if (ConstantSDNode *C =
14072 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14073 // An add of one will be selected as an INC.
14074 if (C->isOne() && !Subtarget->slowIncDec()) {
14075 Opcode = X86ISD::INC;
14080 // An add of negative one (subtract of one) will be selected as a DEC.
14081 if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14082 Opcode = X86ISD::DEC;
14088 // Otherwise use a regular EFLAGS-setting add.
14089 Opcode = X86ISD::ADD;
14094 // If we have a constant logical shift that's only used in a comparison
14095 // against zero turn it into an equivalent AND. This allows turning it into
14096 // a TEST instruction later.
14097 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14098 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14099 EVT VT = Op.getValueType();
14100 unsigned BitWidth = VT.getSizeInBits();
14101 unsigned ShAmt = Op->getConstantOperandVal(1);
14102 if (ShAmt >= BitWidth) // Avoid undefined shifts.
14104 APInt Mask = ArithOp.getOpcode() == ISD::SRL
14105 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14106 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14107 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14109 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14110 DAG.getConstant(Mask, dl, VT));
14111 DAG.ReplaceAllUsesWith(Op, New);
14117 // If the primary and result isn't used, don't bother using X86ISD::AND,
14118 // because a TEST instruction will be better.
14119 if (!hasNonFlagsUse(Op))
14125 // Due to the ISEL shortcoming noted above, be conservative if this op is
14126 // likely to be selected as part of a load-modify-store instruction.
14127 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14128 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14129 if (UI->getOpcode() == ISD::STORE)
14132 // Otherwise use a regular EFLAGS-setting instruction.
14133 switch (ArithOp.getOpcode()) {
14134 default: llvm_unreachable("unexpected operator!");
14135 case ISD::SUB: Opcode = X86ISD::SUB; break;
14136 case ISD::XOR: Opcode = X86ISD::XOR; break;
14137 case ISD::AND: Opcode = X86ISD::AND; break;
14139 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14140 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14141 if (EFLAGS.getNode())
14144 Opcode = X86ISD::OR;
14158 return SDValue(Op.getNode(), 1);
14164 // If we found that truncation is beneficial, perform the truncation and
14166 if (NeedTruncation) {
14167 EVT VT = Op.getValueType();
14168 SDValue WideVal = Op->getOperand(0);
14169 EVT WideVT = WideVal.getValueType();
14170 unsigned ConvertedOp = 0;
14171 // Use a target machine opcode to prevent further DAGCombine
14172 // optimizations that may separate the arithmetic operations
14173 // from the setcc node.
14174 switch (WideVal.getOpcode()) {
14176 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14177 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14178 case ISD::AND: ConvertedOp = X86ISD::AND; break;
14179 case ISD::OR: ConvertedOp = X86ISD::OR; break;
14180 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14184 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14185 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14186 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14187 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14188 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14194 // Emit a CMP with 0, which is the TEST pattern.
14195 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14196 DAG.getConstant(0, dl, Op.getValueType()));
14198 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14199 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14201 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14202 DAG.ReplaceAllUsesWith(Op, New);
14203 return SDValue(New.getNode(), 1);
14206 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14208 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14209 SDLoc dl, SelectionDAG &DAG) const {
14210 if (isNullConstant(Op1))
14211 return EmitTest(Op0, X86CC, dl, DAG);
14213 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14214 "Unexpected comparison operation for MVT::i1 operands");
14216 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14217 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14218 // Do the comparison at i32 if it's smaller, besides the Atom case.
14219 // This avoids subregister aliasing issues. Keep the smaller reference
14220 // if we're optimizing for size, however, as that'll allow better folding
14221 // of memory operations.
14222 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14223 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14224 !Subtarget->isAtom()) {
14225 unsigned ExtendOp =
14226 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14227 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14228 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14230 // Use SUB instead of CMP to enable CSE between SUB and CMP.
14231 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14232 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14234 return SDValue(Sub.getNode(), 1);
14236 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14239 /// Convert a comparison if required by the subtarget.
14240 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14241 SelectionDAG &DAG) const {
14242 // If the subtarget does not support the FUCOMI instruction, floating-point
14243 // comparisons have to be converted.
14244 if (Subtarget->hasCMov() ||
14245 Cmp.getOpcode() != X86ISD::CMP ||
14246 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14247 !Cmp.getOperand(1).getValueType().isFloatingPoint())
14250 // The instruction selector will select an FUCOM instruction instead of
14251 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14252 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14253 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14255 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14256 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14257 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14258 DAG.getConstant(8, dl, MVT::i8));
14259 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14261 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14262 assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14263 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14266 /// The minimum architected relative accuracy is 2^-12. We need one
14267 /// Newton-Raphson step to have a good float result (24 bits of precision).
14268 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14269 DAGCombinerInfo &DCI,
14270 unsigned &RefinementSteps,
14271 bool &UseOneConstNR) const {
14272 EVT VT = Op.getValueType();
14273 const char *RecipOp;
14275 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14276 // TODO: Add support for AVX512 (v16f32).
14277 // It is likely not profitable to do this for f64 because a double-precision
14278 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14279 // instructions: convert to single, rsqrtss, convert back to double, refine
14280 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14281 // along with FMA, this could be a throughput win.
14282 if (VT == MVT::f32 && Subtarget->hasSSE1())
14284 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14285 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14286 RecipOp = "vec-sqrtf";
14290 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14291 if (!Recips.isEnabled(RecipOp))
14294 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14295 UseOneConstNR = false;
14296 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14299 /// The minimum architected relative accuracy is 2^-12. We need one
14300 /// Newton-Raphson step to have a good float result (24 bits of precision).
14301 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14302 DAGCombinerInfo &DCI,
14303 unsigned &RefinementSteps) const {
14304 EVT VT = Op.getValueType();
14305 const char *RecipOp;
14307 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14308 // TODO: Add support for AVX512 (v16f32).
14309 // It is likely not profitable to do this for f64 because a double-precision
14310 // reciprocal estimate with refinement on x86 prior to FMA requires
14311 // 15 instructions: convert to single, rcpss, convert back to double, refine
14312 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14313 // along with FMA, this could be a throughput win.
14314 if (VT == MVT::f32 && Subtarget->hasSSE1())
14316 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14317 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14318 RecipOp = "vec-divf";
14322 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14323 if (!Recips.isEnabled(RecipOp))
14326 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14327 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14330 /// If we have at least two divisions that use the same divisor, convert to
14331 /// multplication by a reciprocal. This may need to be adjusted for a given
14332 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14333 /// This is because we still need one division to calculate the reciprocal and
14334 /// then we need two multiplies by that reciprocal as replacements for the
14335 /// original divisions.
14336 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14340 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14341 /// if it's possible.
14342 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14343 SDLoc dl, SelectionDAG &DAG) const {
14344 SDValue Op0 = And.getOperand(0);
14345 SDValue Op1 = And.getOperand(1);
14346 if (Op0.getOpcode() == ISD::TRUNCATE)
14347 Op0 = Op0.getOperand(0);
14348 if (Op1.getOpcode() == ISD::TRUNCATE)
14349 Op1 = Op1.getOperand(0);
14352 if (Op1.getOpcode() == ISD::SHL)
14353 std::swap(Op0, Op1);
14354 if (Op0.getOpcode() == ISD::SHL) {
14355 if (isOneConstant(Op0.getOperand(0))) {
14356 // If we looked past a truncate, check that it's only truncating away
14358 unsigned BitWidth = Op0.getValueSizeInBits();
14359 unsigned AndBitWidth = And.getValueSizeInBits();
14360 if (BitWidth > AndBitWidth) {
14362 DAG.computeKnownBits(Op0, Zeros, Ones);
14363 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14367 RHS = Op0.getOperand(1);
14369 } else if (Op1.getOpcode() == ISD::Constant) {
14370 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14371 uint64_t AndRHSVal = AndRHS->getZExtValue();
14372 SDValue AndLHS = Op0;
14374 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14375 LHS = AndLHS.getOperand(0);
14376 RHS = AndLHS.getOperand(1);
14379 // Use BT if the immediate can't be encoded in a TEST instruction.
14380 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14382 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14386 if (LHS.getNode()) {
14387 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
14388 // instruction. Since the shift amount is in-range-or-undefined, we know
14389 // that doing a bittest on the i32 value is ok. We extend to i32 because
14390 // the encoding for the i16 version is larger than the i32 version.
14391 // Also promote i16 to i32 for performance / code size reason.
14392 if (LHS.getValueType() == MVT::i8 ||
14393 LHS.getValueType() == MVT::i16)
14394 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14396 // If the operand types disagree, extend the shift amount to match. Since
14397 // BT ignores high bits (like shifts) we can use anyextend.
14398 if (LHS.getValueType() != RHS.getValueType())
14399 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14401 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14402 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14403 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14404 DAG.getConstant(Cond, dl, MVT::i8), BT);
14410 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14412 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14417 // SSE Condition code mapping:
14426 switch (SetCCOpcode) {
14427 default: llvm_unreachable("Unexpected SETCC condition");
14429 case ISD::SETEQ: SSECC = 0; break;
14431 case ISD::SETGT: Swap = true; // Fallthrough
14433 case ISD::SETOLT: SSECC = 1; break;
14435 case ISD::SETGE: Swap = true; // Fallthrough
14437 case ISD::SETOLE: SSECC = 2; break;
14438 case ISD::SETUO: SSECC = 3; break;
14440 case ISD::SETNE: SSECC = 4; break;
14441 case ISD::SETULE: Swap = true; // Fallthrough
14442 case ISD::SETUGE: SSECC = 5; break;
14443 case ISD::SETULT: Swap = true; // Fallthrough
14444 case ISD::SETUGT: SSECC = 6; break;
14445 case ISD::SETO: SSECC = 7; break;
14447 case ISD::SETONE: SSECC = 8; break;
14450 std::swap(Op0, Op1);
14455 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14456 // ones, and then concatenate the result back.
14457 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14458 MVT VT = Op.getSimpleValueType();
14460 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14461 "Unsupported value type for operation");
14463 unsigned NumElems = VT.getVectorNumElements();
14465 SDValue CC = Op.getOperand(2);
14467 // Extract the LHS vectors
14468 SDValue LHS = Op.getOperand(0);
14469 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14470 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14472 // Extract the RHS vectors
14473 SDValue RHS = Op.getOperand(1);
14474 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14475 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14477 // Issue the operation on the smaller types and concatenate the result back
14478 MVT EltVT = VT.getVectorElementType();
14479 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14480 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14481 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14482 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14485 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14486 SDValue Op0 = Op.getOperand(0);
14487 SDValue Op1 = Op.getOperand(1);
14488 SDValue CC = Op.getOperand(2);
14489 MVT VT = Op.getSimpleValueType();
14492 assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14493 "Unexpected type for boolean compare operation");
14494 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14495 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14496 DAG.getConstant(-1, dl, VT));
14497 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14498 DAG.getConstant(-1, dl, VT));
14499 switch (SetCCOpcode) {
14500 default: llvm_unreachable("Unexpected SETCC condition");
14502 // (x == y) -> ~(x ^ y)
14503 return DAG.getNode(ISD::XOR, dl, VT,
14504 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14505 DAG.getConstant(-1, dl, VT));
14507 // (x != y) -> (x ^ y)
14508 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14511 // (x > y) -> (x & ~y)
14512 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14515 // (x < y) -> (~x & y)
14516 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14519 // (x <= y) -> (~x | y)
14520 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14523 // (x >=y) -> (x | ~y)
14524 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14528 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14529 const X86Subtarget *Subtarget) {
14530 SDValue Op0 = Op.getOperand(0);
14531 SDValue Op1 = Op.getOperand(1);
14532 SDValue CC = Op.getOperand(2);
14533 MVT VT = Op.getSimpleValueType();
14536 assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14537 Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14538 "Cannot set masked compare for this operation");
14540 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14542 bool Unsigned = false;
14545 switch (SetCCOpcode) {
14546 default: llvm_unreachable("Unexpected SETCC condition");
14547 case ISD::SETNE: SSECC = 4; break;
14548 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14549 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14550 case ISD::SETLT: Swap = true; //fall-through
14551 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14552 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14553 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14554 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14555 case ISD::SETULE: Unsigned = true; //fall-through
14556 case ISD::SETLE: SSECC = 2; break;
14560 std::swap(Op0, Op1);
14562 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14563 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14564 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14565 DAG.getConstant(SSECC, dl, MVT::i8));
14568 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14569 /// operand \p Op1. If non-trivial (for example because it's not constant)
14570 /// return an empty value.
14571 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14573 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14577 MVT VT = Op1.getSimpleValueType();
14578 MVT EVT = VT.getVectorElementType();
14579 unsigned n = VT.getVectorNumElements();
14580 SmallVector<SDValue, 8> ULTOp1;
14582 for (unsigned i = 0; i < n; ++i) {
14583 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14584 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14587 // Avoid underflow.
14588 APInt Val = Elt->getAPIntValue();
14592 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14595 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14598 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14599 SelectionDAG &DAG) {
14600 SDValue Op0 = Op.getOperand(0);
14601 SDValue Op1 = Op.getOperand(1);
14602 SDValue CC = Op.getOperand(2);
14603 MVT VT = Op.getSimpleValueType();
14604 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14605 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14610 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14611 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14614 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14615 unsigned Opc = X86ISD::CMPP;
14616 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14617 assert(VT.getVectorNumElements() <= 16);
14618 Opc = X86ISD::CMPM;
14620 // In the two special cases we can't handle, emit two comparisons.
14623 unsigned CombineOpc;
14624 if (SetCCOpcode == ISD::SETUEQ) {
14625 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14627 assert(SetCCOpcode == ISD::SETONE);
14628 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14631 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14632 DAG.getConstant(CC0, dl, MVT::i8));
14633 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14634 DAG.getConstant(CC1, dl, MVT::i8));
14635 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14637 // Handle all other FP comparisons here.
14638 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14639 DAG.getConstant(SSECC, dl, MVT::i8));
14642 MVT VTOp0 = Op0.getSimpleValueType();
14643 assert(VTOp0 == Op1.getSimpleValueType() &&
14644 "Expected operands with same type!");
14645 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14646 "Invalid number of packed elements for source and destination!");
14648 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14649 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14650 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14651 // legalizer firstly checks if the first operand in input to the setcc has
14652 // a legal type. If so, then it promotes the return type to that same type.
14653 // Otherwise, the return type is promoted to the 'next legal type' which,
14654 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14656 // We reach this code only if the following two conditions are met:
14657 // 1. Both return type and operand type have been promoted to wider types
14658 // by the type legalizer.
14659 // 2. The original operand type has been promoted to a 256-bit vector.
14661 // Note that condition 2. only applies for AVX targets.
14662 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14663 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14666 // The non-AVX512 code below works under the assumption that source and
14667 // destination types are the same.
14668 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14669 "Value types for source and destination must be the same!");
14671 // Break 256-bit integer vector compare into smaller ones.
14672 if (VT.is256BitVector() && !Subtarget->hasInt256())
14673 return Lower256IntVSETCC(Op, DAG);
14675 MVT OpVT = Op1.getSimpleValueType();
14676 if (OpVT.getVectorElementType() == MVT::i1)
14677 return LowerBoolVSETCC_AVX512(Op, DAG);
14679 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14680 if (Subtarget->hasAVX512()) {
14681 if (Op1.getSimpleValueType().is512BitVector() ||
14682 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14683 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14684 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14686 // In AVX-512 architecture setcc returns mask with i1 elements,
14687 // But there is no compare instruction for i8 and i16 elements in KNL.
14688 // We are not talking about 512-bit operands in this case, these
14689 // types are illegal.
14691 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14692 OpVT.getVectorElementType().getSizeInBits() >= 8))
14693 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14694 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14697 // Lower using XOP integer comparisons.
14698 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14699 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14700 // Translate compare code to XOP PCOM compare mode.
14701 unsigned CmpMode = 0;
14702 switch (SetCCOpcode) {
14703 default: llvm_unreachable("Unexpected SETCC condition");
14705 case ISD::SETLT: CmpMode = 0x00; break;
14707 case ISD::SETLE: CmpMode = 0x01; break;
14709 case ISD::SETGT: CmpMode = 0x02; break;
14711 case ISD::SETGE: CmpMode = 0x03; break;
14712 case ISD::SETEQ: CmpMode = 0x04; break;
14713 case ISD::SETNE: CmpMode = 0x05; break;
14716 // Are we comparing unsigned or signed integers?
14717 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14718 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14720 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14721 DAG.getConstant(CmpMode, dl, MVT::i8));
14724 // We are handling one of the integer comparisons here. Since SSE only has
14725 // GT and EQ comparisons for integer, swapping operands and multiple
14726 // operations may be required for some comparisons.
14728 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14729 bool Subus = false;
14731 switch (SetCCOpcode) {
14732 default: llvm_unreachable("Unexpected SETCC condition");
14733 case ISD::SETNE: Invert = true;
14734 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14735 case ISD::SETLT: Swap = true;
14736 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14737 case ISD::SETGE: Swap = true;
14738 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14739 Invert = true; break;
14740 case ISD::SETULT: Swap = true;
14741 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14742 FlipSigns = true; break;
14743 case ISD::SETUGE: Swap = true;
14744 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14745 FlipSigns = true; Invert = true; break;
14748 // Special case: Use min/max operations for SETULE/SETUGE
14749 MVT VET = VT.getVectorElementType();
14751 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14752 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14755 switch (SetCCOpcode) {
14757 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14758 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14761 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14764 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14765 if (!MinMax && hasSubus) {
14766 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14768 // t = psubus Op0, Op1
14769 // pcmpeq t, <0..0>
14770 switch (SetCCOpcode) {
14772 case ISD::SETULT: {
14773 // If the comparison is against a constant we can turn this into a
14774 // setule. With psubus, setule does not require a swap. This is
14775 // beneficial because the constant in the register is no longer
14776 // destructed as the destination so it can be hoisted out of a loop.
14777 // Only do this pre-AVX since vpcmp* is no longer destructive.
14778 if (Subtarget->hasAVX())
14780 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14781 if (ULEOp1.getNode()) {
14783 Subus = true; Invert = false; Swap = false;
14787 // Psubus is better than flip-sign because it requires no inversion.
14788 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14789 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14793 Opc = X86ISD::SUBUS;
14799 std::swap(Op0, Op1);
14801 // Check that the operation in question is available (most are plain SSE2,
14802 // but PCMPGTQ and PCMPEQQ have different requirements).
14803 if (VT == MVT::v2i64) {
14804 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14805 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14807 // First cast everything to the right type.
14808 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14809 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14811 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14812 // bits of the inputs before performing those operations. The lower
14813 // compare is always unsigned.
14816 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14818 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14819 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14820 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14821 Sign, Zero, Sign, Zero);
14823 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14824 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14826 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14827 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14828 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14830 // Create masks for only the low parts/high parts of the 64 bit integers.
14831 static const int MaskHi[] = { 1, 1, 3, 3 };
14832 static const int MaskLo[] = { 0, 0, 2, 2 };
14833 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14834 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14835 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14837 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14838 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14841 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14843 return DAG.getBitcast(VT, Result);
14846 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14847 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14848 // pcmpeqd + pshufd + pand.
14849 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14851 // First cast everything to the right type.
14852 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14853 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14856 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14858 // Make sure the lower and upper halves are both all-ones.
14859 static const int Mask[] = { 1, 0, 3, 2 };
14860 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14861 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14864 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14866 return DAG.getBitcast(VT, Result);
14870 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14871 // bits of the inputs before performing those operations.
14873 MVT EltVT = VT.getVectorElementType();
14874 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14876 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14877 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14880 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14882 // If the logical-not of the result is required, perform that now.
14884 Result = DAG.getNOT(dl, Result, VT);
14887 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14890 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14891 getZeroVector(VT, Subtarget, DAG, dl));
14896 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14898 MVT VT = Op.getSimpleValueType();
14900 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14902 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14903 && "SetCC type must be 8-bit or 1-bit integer");
14904 SDValue Op0 = Op.getOperand(0);
14905 SDValue Op1 = Op.getOperand(1);
14907 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14909 // Optimize to BT if possible.
14910 // Lower (X & (1 << N)) == 0 to BT(X, N).
14911 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14912 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14913 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14914 isNullConstant(Op1) &&
14915 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14916 if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14918 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14923 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14925 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14926 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14928 // If the input is a setcc, then reuse the input setcc or use a new one with
14929 // the inverted condition.
14930 if (Op0.getOpcode() == X86ISD::SETCC) {
14931 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14932 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14936 CCode = X86::GetOppositeBranchCondition(CCode);
14937 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14938 DAG.getConstant(CCode, dl, MVT::i8),
14939 Op0.getOperand(1));
14941 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14945 if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14946 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14948 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14949 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14952 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14953 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14954 if (X86CC == X86::COND_INVALID)
14957 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14958 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14959 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14960 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14962 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14966 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14967 SDValue LHS = Op.getOperand(0);
14968 SDValue RHS = Op.getOperand(1);
14969 SDValue Carry = Op.getOperand(2);
14970 SDValue Cond = Op.getOperand(3);
14973 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14974 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14976 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14977 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14978 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14979 SDValue SetCC = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14980 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14981 if (Op.getSimpleValueType() == MVT::i1)
14982 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
14986 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14987 static bool isX86LogicalCmp(SDValue Op) {
14988 unsigned Opc = Op.getNode()->getOpcode();
14989 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14990 Opc == X86ISD::SAHF)
14992 if (Op.getResNo() == 1 &&
14993 (Opc == X86ISD::ADD ||
14994 Opc == X86ISD::SUB ||
14995 Opc == X86ISD::ADC ||
14996 Opc == X86ISD::SBB ||
14997 Opc == X86ISD::SMUL ||
14998 Opc == X86ISD::UMUL ||
14999 Opc == X86ISD::INC ||
15000 Opc == X86ISD::DEC ||
15001 Opc == X86ISD::OR ||
15002 Opc == X86ISD::XOR ||
15003 Opc == X86ISD::AND))
15006 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15012 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15013 if (V.getOpcode() != ISD::TRUNCATE)
15016 SDValue VOp0 = V.getOperand(0);
15017 unsigned InBits = VOp0.getValueSizeInBits();
15018 unsigned Bits = V.getValueSizeInBits();
15019 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15022 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15023 bool addTest = true;
15024 SDValue Cond = Op.getOperand(0);
15025 SDValue Op1 = Op.getOperand(1);
15026 SDValue Op2 = Op.getOperand(2);
15028 MVT VT = Op1.getSimpleValueType();
15031 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15032 // are available or VBLENDV if AVX is available.
15033 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
15034 if (Cond.getOpcode() == ISD::SETCC &&
15035 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15036 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15037 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
15038 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15039 int SSECC = translateX86FSETCC(
15040 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15043 if (Subtarget->hasAVX512()) {
15044 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15045 DAG.getConstant(SSECC, DL, MVT::i8));
15046 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15049 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15050 DAG.getConstant(SSECC, DL, MVT::i8));
15052 // If we have AVX, we can use a variable vector select (VBLENDV) instead
15053 // of 3 logic instructions for size savings and potentially speed.
15054 // Unfortunately, there is no scalar form of VBLENDV.
15056 // If either operand is a constant, don't try this. We can expect to
15057 // optimize away at least one of the logic instructions later in that
15058 // case, so that sequence would be faster than a variable blend.
15060 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15061 // uses XMM0 as the selection register. That may need just as many
15062 // instructions as the AND/ANDN/OR sequence due to register moves, so
15065 if (Subtarget->hasAVX() &&
15066 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15068 // Convert to vectors, do a VSELECT, and convert back to scalar.
15069 // All of the conversions should be optimized away.
15071 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15072 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15073 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15074 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15076 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15077 VCmp = DAG.getBitcast(VCmpVT, VCmp);
15079 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15081 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15082 VSel, DAG.getIntPtrConstant(0, DL));
15084 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15085 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15086 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15090 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15092 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15093 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15094 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15095 Op1Scalar = Op1.getOperand(0);
15097 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15098 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15099 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15100 Op2Scalar = Op2.getOperand(0);
15101 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15102 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15103 Op1Scalar.getValueType(),
15104 Cond, Op1Scalar, Op2Scalar);
15105 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15106 return DAG.getBitcast(VT, newSelect);
15107 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15108 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15109 DAG.getIntPtrConstant(0, DL));
15113 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15114 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15115 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15116 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15117 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15118 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15119 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15121 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15124 if (Cond.getOpcode() == ISD::SETCC) {
15125 SDValue NewCond = LowerSETCC(Cond, DAG);
15126 if (NewCond.getNode())
15130 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15131 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15132 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15133 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15134 if (Cond.getOpcode() == X86ISD::SETCC &&
15135 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15136 isNullConstant(Cond.getOperand(1).getOperand(1))) {
15137 SDValue Cmp = Cond.getOperand(1);
15139 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15141 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15142 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15143 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15145 SDValue CmpOp0 = Cmp.getOperand(0);
15146 // Apply further optimizations for special cases
15147 // (select (x != 0), -1, 0) -> neg & sbb
15148 // (select (x == 0), 0, -1) -> neg & sbb
15149 if (isNullConstant(Y) &&
15150 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15151 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15152 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15153 DAG.getConstant(0, DL,
15154 CmpOp0.getValueType()),
15156 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15157 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15158 SDValue(Neg.getNode(), 1));
15162 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15163 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15164 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15166 SDValue Res = // Res = 0 or -1.
15167 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15168 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15170 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15171 Res = DAG.getNOT(DL, Res, Res.getValueType());
15173 if (!isNullConstant(Op2))
15174 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15179 // Look past (and (setcc_carry (cmp ...)), 1).
15180 if (Cond.getOpcode() == ISD::AND &&
15181 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15182 isOneConstant(Cond.getOperand(1)))
15183 Cond = Cond.getOperand(0);
15185 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15186 // setting operand in place of the X86ISD::SETCC.
15187 unsigned CondOpcode = Cond.getOpcode();
15188 if (CondOpcode == X86ISD::SETCC ||
15189 CondOpcode == X86ISD::SETCC_CARRY) {
15190 CC = Cond.getOperand(0);
15192 SDValue Cmp = Cond.getOperand(1);
15193 unsigned Opc = Cmp.getOpcode();
15194 MVT VT = Op.getSimpleValueType();
15196 bool IllegalFPCMov = false;
15197 if (VT.isFloatingPoint() && !VT.isVector() &&
15198 !isScalarFPTypeInSSEReg(VT)) // FPStack?
15199 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15201 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15202 Opc == X86ISD::BT) { // FIXME
15206 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15207 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15208 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15209 Cond.getOperand(0).getValueType() != MVT::i8)) {
15210 SDValue LHS = Cond.getOperand(0);
15211 SDValue RHS = Cond.getOperand(1);
15212 unsigned X86Opcode;
15215 switch (CondOpcode) {
15216 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15217 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15218 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15219 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15220 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15221 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15222 default: llvm_unreachable("unexpected overflowing operator");
15224 if (CondOpcode == ISD::UMULO)
15225 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15228 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15230 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15232 if (CondOpcode == ISD::UMULO)
15233 Cond = X86Op.getValue(2);
15235 Cond = X86Op.getValue(1);
15237 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15242 // Look past the truncate if the high bits are known zero.
15243 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15244 Cond = Cond.getOperand(0);
15246 // We know the result of AND is compared against zero. Try to match
15248 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15249 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15250 CC = NewSetCC.getOperand(0);
15251 Cond = NewSetCC.getOperand(1);
15258 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15259 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15262 // a < b ? -1 : 0 -> RES = ~setcc_carry
15263 // a < b ? 0 : -1 -> RES = setcc_carry
15264 // a >= b ? -1 : 0 -> RES = setcc_carry
15265 // a >= b ? 0 : -1 -> RES = ~setcc_carry
15266 if (Cond.getOpcode() == X86ISD::SUB) {
15267 Cond = ConvertCmpIfNecessary(Cond, DAG);
15268 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15270 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15271 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15272 (isNullConstant(Op1) || isNullConstant(Op2))) {
15273 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15274 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15276 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15277 return DAG.getNOT(DL, Res, Res.getValueType());
15282 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15283 // widen the cmov and push the truncate through. This avoids introducing a new
15284 // branch during isel and doesn't add any extensions.
15285 if (Op.getValueType() == MVT::i8 &&
15286 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15287 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15288 if (T1.getValueType() == T2.getValueType() &&
15289 // Blacklist CopyFromReg to avoid partial register stalls.
15290 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15291 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15292 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15293 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15297 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15298 // condition is true.
15299 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15300 SDValue Ops[] = { Op2, Op1, CC, Cond };
15301 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15304 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15305 const X86Subtarget *Subtarget,
15306 SelectionDAG &DAG) {
15307 MVT VT = Op->getSimpleValueType(0);
15308 SDValue In = Op->getOperand(0);
15309 MVT InVT = In.getSimpleValueType();
15310 MVT VTElt = VT.getVectorElementType();
15311 MVT InVTElt = InVT.getVectorElementType();
15315 if ((InVTElt == MVT::i1) &&
15316 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15317 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15319 ((Subtarget->hasBWI() && VT.is512BitVector() &&
15320 VTElt.getSizeInBits() <= 16)) ||
15322 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15323 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15325 ((Subtarget->hasDQI() && VT.is512BitVector() &&
15326 VTElt.getSizeInBits() >= 32))))
15327 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15329 unsigned int NumElts = VT.getVectorNumElements();
15331 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15334 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15335 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15336 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15337 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15340 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15341 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15343 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15346 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15348 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15349 if (VT.is512BitVector())
15351 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15354 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15355 const X86Subtarget *Subtarget,
15356 SelectionDAG &DAG) {
15357 SDValue In = Op->getOperand(0);
15358 MVT VT = Op->getSimpleValueType(0);
15359 MVT InVT = In.getSimpleValueType();
15360 assert(VT.getSizeInBits() == InVT.getSizeInBits());
15362 MVT InSVT = InVT.getVectorElementType();
15363 assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15365 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15367 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15372 // SSE41 targets can use the pmovsx* instructions directly.
15373 if (Subtarget->hasSSE41())
15374 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15376 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15380 // As SRAI is only available on i16/i32 types, we expand only up to i32
15381 // and handle i64 separately.
15382 while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15383 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15384 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15385 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15386 Curr = DAG.getBitcast(CurrVT, Curr);
15389 SDValue SignExt = Curr;
15390 if (CurrVT != InVT) {
15391 unsigned SignExtShift =
15392 CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15393 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15394 DAG.getConstant(SignExtShift, dl, MVT::i8));
15400 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15401 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15402 DAG.getConstant(31, dl, MVT::i8));
15403 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15404 return DAG.getBitcast(VT, Ext);
15410 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15411 SelectionDAG &DAG) {
15412 MVT VT = Op->getSimpleValueType(0);
15413 SDValue In = Op->getOperand(0);
15414 MVT InVT = In.getSimpleValueType();
15417 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15418 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15420 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15421 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15422 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15425 if (Subtarget->hasInt256())
15426 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15428 // Optimize vectors in AVX mode
15429 // Sign extend v8i16 to v8i32 and
15432 // Divide input vector into two parts
15433 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15434 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15435 // concat the vectors to original VT
15437 unsigned NumElems = InVT.getVectorNumElements();
15438 SDValue Undef = DAG.getUNDEF(InVT);
15440 SmallVector<int,8> ShufMask1(NumElems, -1);
15441 for (unsigned i = 0; i != NumElems/2; ++i)
15444 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15446 SmallVector<int,8> ShufMask2(NumElems, -1);
15447 for (unsigned i = 0; i != NumElems/2; ++i)
15448 ShufMask2[i] = i + NumElems/2;
15450 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15452 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15453 VT.getVectorNumElements()/2);
15455 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15456 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15458 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15461 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15462 // may emit an illegal shuffle but the expansion is still better than scalar
15463 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15464 // we'll emit a shuffle and a arithmetic shift.
15465 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15466 // TODO: It is possible to support ZExt by zeroing the undef values during
15467 // the shuffle phase or after the shuffle.
15468 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15469 SelectionDAG &DAG) {
15470 MVT RegVT = Op.getSimpleValueType();
15471 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15472 assert(RegVT.isInteger() &&
15473 "We only custom lower integer vector sext loads.");
15475 // Nothing useful we can do without SSE2 shuffles.
15476 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15478 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15480 EVT MemVT = Ld->getMemoryVT();
15481 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15482 unsigned RegSz = RegVT.getSizeInBits();
15484 ISD::LoadExtType Ext = Ld->getExtensionType();
15486 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15487 && "Only anyext and sext are currently implemented.");
15488 assert(MemVT != RegVT && "Cannot extend to the same type");
15489 assert(MemVT.isVector() && "Must load a vector from memory");
15491 unsigned NumElems = RegVT.getVectorNumElements();
15492 unsigned MemSz = MemVT.getSizeInBits();
15493 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15495 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15496 // The only way in which we have a legal 256-bit vector result but not the
15497 // integer 256-bit operations needed to directly lower a sextload is if we
15498 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15499 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15500 // correctly legalized. We do this late to allow the canonical form of
15501 // sextload to persist throughout the rest of the DAG combiner -- it wants
15502 // to fold together any extensions it can, and so will fuse a sign_extend
15503 // of an sextload into a sextload targeting a wider value.
15505 if (MemSz == 128) {
15506 // Just switch this to a normal load.
15507 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15508 "it must be a legal 128-bit vector "
15510 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15511 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15512 Ld->isInvariant(), Ld->getAlignment());
15514 assert(MemSz < 128 &&
15515 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15516 // Do an sext load to a 128-bit vector type. We want to use the same
15517 // number of elements, but elements half as wide. This will end up being
15518 // recursively lowered by this routine, but will succeed as we definitely
15519 // have all the necessary features if we're using AVX1.
15521 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15522 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15524 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15525 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15526 Ld->isNonTemporal(), Ld->isInvariant(),
15527 Ld->getAlignment());
15530 // Replace chain users with the new chain.
15531 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15532 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15534 // Finally, do a normal sign-extend to the desired register.
15535 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15538 // All sizes must be a power of two.
15539 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15540 "Non-power-of-two elements are not custom lowered!");
15542 // Attempt to load the original value using scalar loads.
15543 // Find the largest scalar type that divides the total loaded size.
15544 MVT SclrLoadTy = MVT::i8;
15545 for (MVT Tp : MVT::integer_valuetypes()) {
15546 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15551 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15552 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15554 SclrLoadTy = MVT::f64;
15556 // Calculate the number of scalar loads that we need to perform
15557 // in order to load our vector from memory.
15558 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15560 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15561 "Can only lower sext loads with a single scalar load!");
15563 unsigned loadRegZize = RegSz;
15564 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15567 // Represent our vector as a sequence of elements which are the
15568 // largest scalar that we can load.
15569 EVT LoadUnitVecVT = EVT::getVectorVT(
15570 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15572 // Represent the data using the same element type that is stored in
15573 // memory. In practice, we ''widen'' MemVT.
15575 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15576 loadRegZize / MemVT.getScalarSizeInBits());
15578 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15579 "Invalid vector type");
15581 // We can't shuffle using an illegal type.
15582 assert(TLI.isTypeLegal(WideVecVT) &&
15583 "We only lower types that form legal widened vector types");
15585 SmallVector<SDValue, 8> Chains;
15586 SDValue Ptr = Ld->getBasePtr();
15587 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15588 TLI.getPointerTy(DAG.getDataLayout()));
15589 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15591 for (unsigned i = 0; i < NumLoads; ++i) {
15592 // Perform a single load.
15593 SDValue ScalarLoad =
15594 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15595 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15596 Ld->getAlignment());
15597 Chains.push_back(ScalarLoad.getValue(1));
15598 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15599 // another round of DAGCombining.
15601 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15603 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15604 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15606 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15609 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15611 // Bitcast the loaded value to a vector of the original element type, in
15612 // the size of the target vector type.
15613 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15614 unsigned SizeRatio = RegSz / MemSz;
15616 if (Ext == ISD::SEXTLOAD) {
15617 // If we have SSE4.1, we can directly emit a VSEXT node.
15618 if (Subtarget->hasSSE41()) {
15619 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15620 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15624 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15626 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15627 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15629 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15630 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15634 // Redistribute the loaded elements into the different locations.
15635 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15636 for (unsigned i = 0; i != NumElems; ++i)
15637 ShuffleVec[i * SizeRatio] = i;
15639 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15640 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15642 // Bitcast to the requested type.
15643 Shuff = DAG.getBitcast(RegVT, Shuff);
15644 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15648 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15649 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15650 // from the AND / OR.
15651 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15652 Opc = Op.getOpcode();
15653 if (Opc != ISD::OR && Opc != ISD::AND)
15655 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15656 Op.getOperand(0).hasOneUse() &&
15657 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15658 Op.getOperand(1).hasOneUse());
15661 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15662 // 1 and that the SETCC node has a single use.
15663 static bool isXor1OfSetCC(SDValue Op) {
15664 if (Op.getOpcode() != ISD::XOR)
15666 if (isOneConstant(Op.getOperand(1)))
15667 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15668 Op.getOperand(0).hasOneUse();
15672 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15673 bool addTest = true;
15674 SDValue Chain = Op.getOperand(0);
15675 SDValue Cond = Op.getOperand(1);
15676 SDValue Dest = Op.getOperand(2);
15679 bool Inverted = false;
15681 if (Cond.getOpcode() == ISD::SETCC) {
15682 // Check for setcc([su]{add,sub,mul}o == 0).
15683 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15684 isNullConstant(Cond.getOperand(1)) &&
15685 Cond.getOperand(0).getResNo() == 1 &&
15686 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15687 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15688 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15689 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15690 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15691 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15693 Cond = Cond.getOperand(0);
15695 SDValue NewCond = LowerSETCC(Cond, DAG);
15696 if (NewCond.getNode())
15701 // FIXME: LowerXALUO doesn't handle these!!
15702 else if (Cond.getOpcode() == X86ISD::ADD ||
15703 Cond.getOpcode() == X86ISD::SUB ||
15704 Cond.getOpcode() == X86ISD::SMUL ||
15705 Cond.getOpcode() == X86ISD::UMUL)
15706 Cond = LowerXALUO(Cond, DAG);
15709 // Look pass (and (setcc_carry (cmp ...)), 1).
15710 if (Cond.getOpcode() == ISD::AND &&
15711 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15712 isOneConstant(Cond.getOperand(1)))
15713 Cond = Cond.getOperand(0);
15715 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15716 // setting operand in place of the X86ISD::SETCC.
15717 unsigned CondOpcode = Cond.getOpcode();
15718 if (CondOpcode == X86ISD::SETCC ||
15719 CondOpcode == X86ISD::SETCC_CARRY) {
15720 CC = Cond.getOperand(0);
15722 SDValue Cmp = Cond.getOperand(1);
15723 unsigned Opc = Cmp.getOpcode();
15724 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15725 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15729 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15733 // These can only come from an arithmetic instruction with overflow,
15734 // e.g. SADDO, UADDO.
15735 Cond = Cond.getNode()->getOperand(1);
15741 CondOpcode = Cond.getOpcode();
15742 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15743 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15744 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15745 Cond.getOperand(0).getValueType() != MVT::i8)) {
15746 SDValue LHS = Cond.getOperand(0);
15747 SDValue RHS = Cond.getOperand(1);
15748 unsigned X86Opcode;
15751 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15752 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15754 switch (CondOpcode) {
15755 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15757 if (isOneConstant(RHS)) {
15758 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15761 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15762 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15764 if (isOneConstant(RHS)) {
15765 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15768 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15769 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15770 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15771 default: llvm_unreachable("unexpected overflowing operator");
15774 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15775 if (CondOpcode == ISD::UMULO)
15776 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15779 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15781 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15783 if (CondOpcode == ISD::UMULO)
15784 Cond = X86Op.getValue(2);
15786 Cond = X86Op.getValue(1);
15788 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15792 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15793 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15794 if (CondOpc == ISD::OR) {
15795 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15796 // two branches instead of an explicit OR instruction with a
15798 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15799 isX86LogicalCmp(Cmp)) {
15800 CC = Cond.getOperand(0).getOperand(0);
15801 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15802 Chain, Dest, CC, Cmp);
15803 CC = Cond.getOperand(1).getOperand(0);
15807 } else { // ISD::AND
15808 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15809 // two branches instead of an explicit AND instruction with a
15810 // separate test. However, we only do this if this block doesn't
15811 // have a fall-through edge, because this requires an explicit
15812 // jmp when the condition is false.
15813 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15814 isX86LogicalCmp(Cmp) &&
15815 Op.getNode()->hasOneUse()) {
15816 X86::CondCode CCode =
15817 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15818 CCode = X86::GetOppositeBranchCondition(CCode);
15819 CC = DAG.getConstant(CCode, dl, MVT::i8);
15820 SDNode *User = *Op.getNode()->use_begin();
15821 // Look for an unconditional branch following this conditional branch.
15822 // We need this because we need to reverse the successors in order
15823 // to implement FCMP_OEQ.
15824 if (User->getOpcode() == ISD::BR) {
15825 SDValue FalseBB = User->getOperand(1);
15827 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15828 assert(NewBR == User);
15832 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15833 Chain, Dest, CC, Cmp);
15834 X86::CondCode CCode =
15835 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15836 CCode = X86::GetOppositeBranchCondition(CCode);
15837 CC = DAG.getConstant(CCode, dl, MVT::i8);
15843 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15844 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15845 // It should be transformed during dag combiner except when the condition
15846 // is set by a arithmetics with overflow node.
15847 X86::CondCode CCode =
15848 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15849 CCode = X86::GetOppositeBranchCondition(CCode);
15850 CC = DAG.getConstant(CCode, dl, MVT::i8);
15851 Cond = Cond.getOperand(0).getOperand(1);
15853 } else if (Cond.getOpcode() == ISD::SETCC &&
15854 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15855 // For FCMP_OEQ, we can emit
15856 // two branches instead of an explicit AND instruction with a
15857 // separate test. However, we only do this if this block doesn't
15858 // have a fall-through edge, because this requires an explicit
15859 // jmp when the condition is false.
15860 if (Op.getNode()->hasOneUse()) {
15861 SDNode *User = *Op.getNode()->use_begin();
15862 // Look for an unconditional branch following this conditional branch.
15863 // We need this because we need to reverse the successors in order
15864 // to implement FCMP_OEQ.
15865 if (User->getOpcode() == ISD::BR) {
15866 SDValue FalseBB = User->getOperand(1);
15868 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15869 assert(NewBR == User);
15873 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15874 Cond.getOperand(0), Cond.getOperand(1));
15875 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15876 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15877 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15878 Chain, Dest, CC, Cmp);
15879 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15884 } else if (Cond.getOpcode() == ISD::SETCC &&
15885 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15886 // For FCMP_UNE, we can emit
15887 // two branches instead of an explicit AND instruction with a
15888 // separate test. However, we only do this if this block doesn't
15889 // have a fall-through edge, because this requires an explicit
15890 // jmp when the condition is false.
15891 if (Op.getNode()->hasOneUse()) {
15892 SDNode *User = *Op.getNode()->use_begin();
15893 // Look for an unconditional branch following this conditional branch.
15894 // We need this because we need to reverse the successors in order
15895 // to implement FCMP_UNE.
15896 if (User->getOpcode() == ISD::BR) {
15897 SDValue FalseBB = User->getOperand(1);
15899 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15900 assert(NewBR == User);
15903 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15904 Cond.getOperand(0), Cond.getOperand(1));
15905 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15906 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15907 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15908 Chain, Dest, CC, Cmp);
15909 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15919 // Look pass the truncate if the high bits are known zero.
15920 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15921 Cond = Cond.getOperand(0);
15923 // We know the result of AND is compared against zero. Try to match
15925 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15926 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15927 CC = NewSetCC.getOperand(0);
15928 Cond = NewSetCC.getOperand(1);
15935 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15936 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15937 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15939 Cond = ConvertCmpIfNecessary(Cond, DAG);
15940 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15941 Chain, Dest, CC, Cond);
15944 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15945 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15946 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15947 // that the guard pages used by the OS virtual memory manager are allocated in
15948 // correct sequence.
15950 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15951 SelectionDAG &DAG) const {
15952 MachineFunction &MF = DAG.getMachineFunction();
15953 bool SplitStack = MF.shouldSplitStack();
15954 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15959 SDNode *Node = Op.getNode();
15960 SDValue Chain = Op.getOperand(0);
15961 SDValue Size = Op.getOperand(1);
15962 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15963 EVT VT = Node->getValueType(0);
15965 // Chain the dynamic stack allocation so that it doesn't modify the stack
15966 // pointer when other instructions are using the stack.
15967 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15969 bool Is64Bit = Subtarget->is64Bit();
15970 MVT SPTy = getPointerTy(DAG.getDataLayout());
15974 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15975 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15976 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15977 " not tell us which reg is the stack pointer!");
15978 EVT VT = Node->getValueType(0);
15979 SDValue Tmp3 = Node->getOperand(2);
15981 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15982 Chain = SP.getValue(1);
15983 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15984 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15985 unsigned StackAlign = TFI.getStackAlignment();
15986 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15987 if (Align > StackAlign)
15988 Result = DAG.getNode(ISD::AND, dl, VT, Result,
15989 DAG.getConstant(-(uint64_t)Align, dl, VT));
15990 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15991 } else if (SplitStack) {
15992 MachineRegisterInfo &MRI = MF.getRegInfo();
15995 // The 64 bit implementation of segmented stacks needs to clobber both r10
15996 // r11. This makes it impossible to use it along with nested parameters.
15997 const Function *F = MF.getFunction();
15999 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16001 if (I->hasNestAttr())
16002 report_fatal_error("Cannot use segmented stacks with functions that "
16003 "have nested arguments.");
16006 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
16007 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16008 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16009 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16010 DAG.getRegister(Vreg, SPTy));
16013 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16015 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16016 Flag = Chain.getValue(1);
16017 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16019 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16021 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16022 unsigned SPReg = RegInfo->getStackRegister();
16023 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16024 Chain = SP.getValue(1);
16027 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16028 DAG.getConstant(-(uint64_t)Align, dl, VT));
16029 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16035 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
16036 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
16038 SDValue Ops[2] = {Result, Chain};
16039 return DAG.getMergeValues(Ops, dl);
16042 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16043 MachineFunction &MF = DAG.getMachineFunction();
16044 auto PtrVT = getPointerTy(MF.getDataLayout());
16045 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16047 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16050 if (!Subtarget->is64Bit() ||
16051 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16052 // vastart just stores the address of the VarArgsFrameIndex slot into the
16053 // memory location argument.
16054 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16055 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16056 MachinePointerInfo(SV), false, false, 0);
16060 // gp_offset (0 - 6 * 8)
16061 // fp_offset (48 - 48 + 8 * 16)
16062 // overflow_arg_area (point to parameters coming in memory).
16064 SmallVector<SDValue, 8> MemOps;
16065 SDValue FIN = Op.getOperand(1);
16067 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16068 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16070 FIN, MachinePointerInfo(SV), false, false, 0);
16071 MemOps.push_back(Store);
16074 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16075 Store = DAG.getStore(Op.getOperand(0), DL,
16076 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16078 FIN, MachinePointerInfo(SV, 4), false, false, 0);
16079 MemOps.push_back(Store);
16081 // Store ptr to overflow_arg_area
16082 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16083 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16084 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16085 MachinePointerInfo(SV, 8),
16087 MemOps.push_back(Store);
16089 // Store ptr to reg_save_area.
16090 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16091 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16092 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16093 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16094 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16095 MemOps.push_back(Store);
16096 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16099 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16100 assert(Subtarget->is64Bit() &&
16101 "LowerVAARG only handles 64-bit va_arg!");
16102 assert(Op.getNode()->getNumOperands() == 4);
16104 MachineFunction &MF = DAG.getMachineFunction();
16105 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16106 // The Win64 ABI uses char* instead of a structure.
16107 return DAG.expandVAArg(Op.getNode());
16109 SDValue Chain = Op.getOperand(0);
16110 SDValue SrcPtr = Op.getOperand(1);
16111 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16112 unsigned Align = Op.getConstantOperandVal(3);
16115 EVT ArgVT = Op.getNode()->getValueType(0);
16116 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16117 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16120 // Decide which area this value should be read from.
16121 // TODO: Implement the AMD64 ABI in its entirety. This simple
16122 // selection mechanism works only for the basic types.
16123 if (ArgVT == MVT::f80) {
16124 llvm_unreachable("va_arg for f80 not yet implemented");
16125 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16126 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
16127 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16128 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
16130 llvm_unreachable("Unhandled argument type in LowerVAARG");
16133 if (ArgMode == 2) {
16134 // Sanity Check: Make sure using fp_offset makes sense.
16135 assert(!Subtarget->useSoftFloat() &&
16136 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16137 Subtarget->hasSSE1());
16140 // Insert VAARG_64 node into the DAG
16141 // VAARG_64 returns two values: Variable Argument Address, Chain
16142 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16143 DAG.getConstant(ArgMode, dl, MVT::i8),
16144 DAG.getConstant(Align, dl, MVT::i32)};
16145 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16146 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16147 VTs, InstOps, MVT::i64,
16148 MachinePointerInfo(SV),
16150 /*Volatile=*/false,
16152 /*WriteMem=*/true);
16153 Chain = VAARG.getValue(1);
16155 // Load the next argument and return it
16156 return DAG.getLoad(ArgVT, dl,
16159 MachinePointerInfo(),
16160 false, false, false, 0);
16163 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16164 SelectionDAG &DAG) {
16165 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16166 // where a va_list is still an i8*.
16167 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16168 if (Subtarget->isCallingConvWin64(
16169 DAG.getMachineFunction().getFunction()->getCallingConv()))
16170 // Probably a Win64 va_copy.
16171 return DAG.expandVACopy(Op.getNode());
16173 SDValue Chain = Op.getOperand(0);
16174 SDValue DstPtr = Op.getOperand(1);
16175 SDValue SrcPtr = Op.getOperand(2);
16176 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16177 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16180 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16181 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16183 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16186 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16187 // amount is a constant. Takes immediate version of shift as input.
16188 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16189 SDValue SrcOp, uint64_t ShiftAmt,
16190 SelectionDAG &DAG) {
16191 MVT ElementType = VT.getVectorElementType();
16193 // Fold this packed shift into its first operand if ShiftAmt is 0.
16197 // Check for ShiftAmt >= element width
16198 if (ShiftAmt >= ElementType.getSizeInBits()) {
16199 if (Opc == X86ISD::VSRAI)
16200 ShiftAmt = ElementType.getSizeInBits() - 1;
16202 return DAG.getConstant(0, dl, VT);
16205 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16206 && "Unknown target vector shift-by-constant node");
16208 // Fold this packed vector shift into a build vector if SrcOp is a
16209 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16210 if (VT == SrcOp.getSimpleValueType() &&
16211 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16212 SmallVector<SDValue, 8> Elts;
16213 unsigned NumElts = SrcOp->getNumOperands();
16214 ConstantSDNode *ND;
16217 default: llvm_unreachable(nullptr);
16218 case X86ISD::VSHLI:
16219 for (unsigned i=0; i!=NumElts; ++i) {
16220 SDValue CurrentOp = SrcOp->getOperand(i);
16221 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16222 Elts.push_back(CurrentOp);
16225 ND = cast<ConstantSDNode>(CurrentOp);
16226 const APInt &C = ND->getAPIntValue();
16227 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16230 case X86ISD::VSRLI:
16231 for (unsigned i=0; i!=NumElts; ++i) {
16232 SDValue CurrentOp = SrcOp->getOperand(i);
16233 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16234 Elts.push_back(CurrentOp);
16237 ND = cast<ConstantSDNode>(CurrentOp);
16238 const APInt &C = ND->getAPIntValue();
16239 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16242 case X86ISD::VSRAI:
16243 for (unsigned i=0; i!=NumElts; ++i) {
16244 SDValue CurrentOp = SrcOp->getOperand(i);
16245 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16246 Elts.push_back(CurrentOp);
16249 ND = cast<ConstantSDNode>(CurrentOp);
16250 const APInt &C = ND->getAPIntValue();
16251 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16256 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16259 return DAG.getNode(Opc, dl, VT, SrcOp,
16260 DAG.getConstant(ShiftAmt, dl, MVT::i8));
16263 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16264 // may or may not be a constant. Takes immediate version of shift as input.
16265 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16266 SDValue SrcOp, SDValue ShAmt,
16267 SelectionDAG &DAG) {
16268 MVT SVT = ShAmt.getSimpleValueType();
16269 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16271 // Catch shift-by-constant.
16272 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16273 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16274 CShAmt->getZExtValue(), DAG);
16276 // Change opcode to non-immediate version
16278 default: llvm_unreachable("Unknown target vector shift node");
16279 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16280 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16281 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16284 const X86Subtarget &Subtarget =
16285 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16286 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16287 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16288 // Let the shuffle legalizer expand this shift amount node.
16289 SDValue Op0 = ShAmt.getOperand(0);
16290 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16291 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16293 // Need to build a vector containing shift amount.
16294 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16295 SmallVector<SDValue, 4> ShOps;
16296 ShOps.push_back(ShAmt);
16297 if (SVT == MVT::i32) {
16298 ShOps.push_back(DAG.getConstant(0, dl, SVT));
16299 ShOps.push_back(DAG.getUNDEF(SVT));
16301 ShOps.push_back(DAG.getUNDEF(SVT));
16303 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16304 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16307 // The return type has to be a 128-bit type with the same element
16308 // type as the input type.
16309 MVT EltVT = VT.getVectorElementType();
16310 MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16312 ShAmt = DAG.getBitcast(ShVT, ShAmt);
16313 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16316 /// \brief Return Mask with the necessary casting or extending
16317 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16318 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16319 const X86Subtarget *Subtarget,
16320 SelectionDAG &DAG, SDLoc dl) {
16322 if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16323 // Mask should be extended
16324 Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16325 MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16328 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16329 if (MaskVT == MVT::v64i1) {
16330 assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16331 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16333 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16334 DAG.getConstant(0, dl, MVT::i32));
16335 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16336 DAG.getConstant(1, dl, MVT::i32));
16338 Lo = DAG.getBitcast(MVT::v32i1, Lo);
16339 Hi = DAG.getBitcast(MVT::v32i1, Hi);
16341 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16343 // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16345 MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16346 return DAG.getBitcast(MaskVT,
16347 DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16351 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16352 Mask.getSimpleValueType().getSizeInBits());
16353 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16354 // are extracted by EXTRACT_SUBVECTOR.
16355 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16356 DAG.getBitcast(BitcastVT, Mask),
16357 DAG.getIntPtrConstant(0, dl));
16361 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16362 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16363 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16364 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16365 SDValue PreservedSrc,
16366 const X86Subtarget *Subtarget,
16367 SelectionDAG &DAG) {
16368 MVT VT = Op.getSimpleValueType();
16369 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16370 unsigned OpcodeSelect = ISD::VSELECT;
16373 if (isAllOnesConstant(Mask))
16376 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16378 switch (Op.getOpcode()) {
16380 case X86ISD::PCMPEQM:
16381 case X86ISD::PCMPGTM:
16383 case X86ISD::CMPMU:
16384 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16385 case X86ISD::VFPCLASS:
16386 case X86ISD::VFPCLASSS:
16387 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16388 case X86ISD::VTRUNC:
16389 case X86ISD::VTRUNCS:
16390 case X86ISD::VTRUNCUS:
16391 // We can't use ISD::VSELECT here because it is not always "Legal"
16392 // for the destination type. For example vpmovqb require only AVX512
16393 // and vselect that can operate on byte element type require BWI
16394 OpcodeSelect = X86ISD::SELECT;
16397 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16398 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16399 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16402 /// \brief Creates an SDNode for a predicated scalar operation.
16403 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16404 /// The mask is coming as MVT::i8 and it should be truncated
16405 /// to MVT::i1 while lowering masking intrinsics.
16406 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16407 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16408 /// for a scalar instruction.
16409 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16410 SDValue PreservedSrc,
16411 const X86Subtarget *Subtarget,
16412 SelectionDAG &DAG) {
16413 if (isAllOnesConstant(Mask))
16416 MVT VT = Op.getSimpleValueType();
16418 // The mask should be of type MVT::i1
16419 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16421 if (Op.getOpcode() == X86ISD::FSETCC)
16422 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16423 if (Op.getOpcode() == X86ISD::VFPCLASS ||
16424 Op.getOpcode() == X86ISD::VFPCLASSS)
16425 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16427 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16428 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16429 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16432 static int getSEHRegistrationNodeSize(const Function *Fn) {
16433 if (!Fn->hasPersonalityFn())
16434 report_fatal_error(
16435 "querying registration node size for function without personality");
16436 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16437 // WinEHStatePass for the full struct definition.
16438 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16439 case EHPersonality::MSVC_X86SEH: return 24;
16440 case EHPersonality::MSVC_CXX: return 16;
16443 report_fatal_error(
16444 "can only recover FP for 32-bit MSVC EH personality functions");
16447 /// When the MSVC runtime transfers control to us, either to an outlined
16448 /// function or when returning to a parent frame after catching an exception, we
16449 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16450 /// Here's the math:
16451 /// RegNodeBase = EntryEBP - RegNodeSize
16452 /// ParentFP = RegNodeBase - ParentFrameOffset
16453 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16454 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16455 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16456 SDValue EntryEBP) {
16457 MachineFunction &MF = DAG.getMachineFunction();
16460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16461 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16463 // It's possible that the parent function no longer has a personality function
16464 // if the exceptional code was optimized away, in which case we just return
16465 // the incoming EBP.
16466 if (!Fn->hasPersonalityFn())
16469 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16470 // registration, or the .set_setframe offset.
16471 MCSymbol *OffsetSym =
16472 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16473 GlobalValue::getRealLinkageName(Fn->getName()));
16474 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16475 SDValue ParentFrameOffset =
16476 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16478 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16479 // prologue to RBP in the parent function.
16480 const X86Subtarget &Subtarget =
16481 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16482 if (Subtarget.is64Bit())
16483 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16485 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16486 // RegNodeBase = EntryEBP - RegNodeSize
16487 // ParentFP = RegNodeBase - ParentFrameOffset
16488 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16489 DAG.getConstant(RegNodeSize, dl, PtrVT));
16490 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16493 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16494 SelectionDAG &DAG) {
16496 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16497 MVT VT = Op.getSimpleValueType();
16498 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16500 switch(IntrData->Type) {
16501 case INTR_TYPE_1OP:
16502 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16503 case INTR_TYPE_2OP:
16504 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16506 case INTR_TYPE_2OP_IMM8:
16507 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16508 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16509 case INTR_TYPE_3OP:
16510 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16511 Op.getOperand(2), Op.getOperand(3));
16512 case INTR_TYPE_4OP:
16513 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16514 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16515 case INTR_TYPE_1OP_MASK_RM: {
16516 SDValue Src = Op.getOperand(1);
16517 SDValue PassThru = Op.getOperand(2);
16518 SDValue Mask = Op.getOperand(3);
16519 SDValue RoundingMode;
16520 // We allways add rounding mode to the Node.
16521 // If the rounding mode is not specified, we add the
16522 // "current direction" mode.
16523 if (Op.getNumOperands() == 4)
16525 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16527 RoundingMode = Op.getOperand(4);
16528 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16529 if (IntrWithRoundingModeOpcode != 0)
16530 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16531 X86::STATIC_ROUNDING::CUR_DIRECTION)
16532 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16533 dl, Op.getValueType(), Src, RoundingMode),
16534 Mask, PassThru, Subtarget, DAG);
16535 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16537 Mask, PassThru, Subtarget, DAG);
16539 case INTR_TYPE_1OP_MASK: {
16540 SDValue Src = Op.getOperand(1);
16541 SDValue PassThru = Op.getOperand(2);
16542 SDValue Mask = Op.getOperand(3);
16543 // We add rounding mode to the Node when
16544 // - RM Opcode is specified and
16545 // - RM is not "current direction".
16546 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16547 if (IntrWithRoundingModeOpcode != 0) {
16548 SDValue Rnd = Op.getOperand(4);
16549 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16550 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16551 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16552 dl, Op.getValueType(),
16554 Mask, PassThru, Subtarget, DAG);
16557 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16558 Mask, PassThru, Subtarget, DAG);
16560 case INTR_TYPE_SCALAR_MASK: {
16561 SDValue Src1 = Op.getOperand(1);
16562 SDValue Src2 = Op.getOperand(2);
16563 SDValue passThru = Op.getOperand(3);
16564 SDValue Mask = Op.getOperand(4);
16565 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16566 Mask, passThru, Subtarget, DAG);
16568 case INTR_TYPE_SCALAR_MASK_RM: {
16569 SDValue Src1 = Op.getOperand(1);
16570 SDValue Src2 = Op.getOperand(2);
16571 SDValue Src0 = Op.getOperand(3);
16572 SDValue Mask = Op.getOperand(4);
16573 // There are 2 kinds of intrinsics in this group:
16574 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16575 // (2) With rounding mode and sae - 7 operands.
16576 if (Op.getNumOperands() == 6) {
16577 SDValue Sae = Op.getOperand(5);
16578 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16579 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16581 Mask, Src0, Subtarget, DAG);
16583 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16584 SDValue RoundingMode = Op.getOperand(5);
16585 SDValue Sae = Op.getOperand(6);
16586 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16587 RoundingMode, Sae),
16588 Mask, Src0, Subtarget, DAG);
16590 case INTR_TYPE_2OP_MASK:
16591 case INTR_TYPE_2OP_IMM8_MASK: {
16592 SDValue Src1 = Op.getOperand(1);
16593 SDValue Src2 = Op.getOperand(2);
16594 SDValue PassThru = Op.getOperand(3);
16595 SDValue Mask = Op.getOperand(4);
16597 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16598 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16600 // We specify 2 possible opcodes for intrinsics with rounding modes.
16601 // First, we check if the intrinsic may have non-default rounding mode,
16602 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16603 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16604 if (IntrWithRoundingModeOpcode != 0) {
16605 SDValue Rnd = Op.getOperand(5);
16606 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16607 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16608 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16609 dl, Op.getValueType(),
16611 Mask, PassThru, Subtarget, DAG);
16614 // TODO: Intrinsics should have fast-math-flags to propagate.
16615 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16616 Mask, PassThru, Subtarget, DAG);
16618 case INTR_TYPE_2OP_MASK_RM: {
16619 SDValue Src1 = Op.getOperand(1);
16620 SDValue Src2 = Op.getOperand(2);
16621 SDValue PassThru = Op.getOperand(3);
16622 SDValue Mask = Op.getOperand(4);
16623 // We specify 2 possible modes for intrinsics, with/without rounding
16625 // First, we check if the intrinsic have rounding mode (6 operands),
16626 // if not, we set rounding mode to "current".
16628 if (Op.getNumOperands() == 6)
16629 Rnd = Op.getOperand(5);
16631 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16632 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16634 Mask, PassThru, Subtarget, DAG);
16636 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16637 SDValue Src1 = Op.getOperand(1);
16638 SDValue Src2 = Op.getOperand(2);
16639 SDValue Src3 = Op.getOperand(3);
16640 SDValue PassThru = Op.getOperand(4);
16641 SDValue Mask = Op.getOperand(5);
16642 SDValue Sae = Op.getOperand(6);
16644 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16646 Mask, PassThru, Subtarget, DAG);
16648 case INTR_TYPE_3OP_MASK_RM: {
16649 SDValue Src1 = Op.getOperand(1);
16650 SDValue Src2 = Op.getOperand(2);
16651 SDValue Imm = Op.getOperand(3);
16652 SDValue PassThru = Op.getOperand(4);
16653 SDValue Mask = Op.getOperand(5);
16654 // We specify 2 possible modes for intrinsics, with/without rounding
16656 // First, we check if the intrinsic have rounding mode (7 operands),
16657 // if not, we set rounding mode to "current".
16659 if (Op.getNumOperands() == 7)
16660 Rnd = Op.getOperand(6);
16662 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16663 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16664 Src1, Src2, Imm, Rnd),
16665 Mask, PassThru, Subtarget, DAG);
16667 case INTR_TYPE_3OP_IMM8_MASK:
16668 case INTR_TYPE_3OP_MASK:
16669 case INSERT_SUBVEC: {
16670 SDValue Src1 = Op.getOperand(1);
16671 SDValue Src2 = Op.getOperand(2);
16672 SDValue Src3 = Op.getOperand(3);
16673 SDValue PassThru = Op.getOperand(4);
16674 SDValue Mask = Op.getOperand(5);
16676 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16677 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16678 else if (IntrData->Type == INSERT_SUBVEC) {
16679 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16680 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16681 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16682 Imm *= Src2.getSimpleValueType().getVectorNumElements();
16683 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16686 // We specify 2 possible opcodes for intrinsics with rounding modes.
16687 // First, we check if the intrinsic may have non-default rounding mode,
16688 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16689 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16690 if (IntrWithRoundingModeOpcode != 0) {
16691 SDValue Rnd = Op.getOperand(6);
16692 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16693 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16694 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16695 dl, Op.getValueType(),
16696 Src1, Src2, Src3, Rnd),
16697 Mask, PassThru, Subtarget, DAG);
16700 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16702 Mask, PassThru, Subtarget, DAG);
16704 case VPERM_3OP_MASKZ:
16705 case VPERM_3OP_MASK:{
16706 // Src2 is the PassThru
16707 SDValue Src1 = Op.getOperand(1);
16708 SDValue Src2 = Op.getOperand(2);
16709 SDValue Src3 = Op.getOperand(3);
16710 SDValue Mask = Op.getOperand(4);
16711 MVT VT = Op.getSimpleValueType();
16712 SDValue PassThru = SDValue();
16714 // set PassThru element
16715 if (IntrData->Type == VPERM_3OP_MASKZ)
16716 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16718 PassThru = DAG.getBitcast(VT, Src2);
16720 // Swap Src1 and Src2 in the node creation
16721 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16722 dl, Op.getValueType(),
16724 Mask, PassThru, Subtarget, DAG);
16728 case FMA_OP_MASK: {
16729 SDValue Src1 = Op.getOperand(1);
16730 SDValue Src2 = Op.getOperand(2);
16731 SDValue Src3 = Op.getOperand(3);
16732 SDValue Mask = Op.getOperand(4);
16733 MVT VT = Op.getSimpleValueType();
16734 SDValue PassThru = SDValue();
16736 // set PassThru element
16737 if (IntrData->Type == FMA_OP_MASKZ)
16738 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16739 else if (IntrData->Type == FMA_OP_MASK3)
16744 // We specify 2 possible opcodes for intrinsics with rounding modes.
16745 // First, we check if the intrinsic may have non-default rounding mode,
16746 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16747 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16748 if (IntrWithRoundingModeOpcode != 0) {
16749 SDValue Rnd = Op.getOperand(5);
16750 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16751 X86::STATIC_ROUNDING::CUR_DIRECTION)
16752 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16753 dl, Op.getValueType(),
16754 Src1, Src2, Src3, Rnd),
16755 Mask, PassThru, Subtarget, DAG);
16757 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16758 dl, Op.getValueType(),
16760 Mask, PassThru, Subtarget, DAG);
16762 case TERLOG_OP_MASK:
16763 case TERLOG_OP_MASKZ: {
16764 SDValue Src1 = Op.getOperand(1);
16765 SDValue Src2 = Op.getOperand(2);
16766 SDValue Src3 = Op.getOperand(3);
16767 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16768 SDValue Mask = Op.getOperand(5);
16769 MVT VT = Op.getSimpleValueType();
16770 SDValue PassThru = Src1;
16771 // Set PassThru element.
16772 if (IntrData->Type == TERLOG_OP_MASKZ)
16773 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16775 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16776 Src1, Src2, Src3, Src4),
16777 Mask, PassThru, Subtarget, DAG);
16780 // FPclass intrinsics with mask
16781 SDValue Src1 = Op.getOperand(1);
16782 MVT VT = Src1.getSimpleValueType();
16783 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16784 SDValue Imm = Op.getOperand(2);
16785 SDValue Mask = Op.getOperand(3);
16786 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16787 Mask.getSimpleValueType().getSizeInBits());
16788 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16789 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16790 DAG.getTargetConstant(0, dl, MaskVT),
16792 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16793 DAG.getUNDEF(BitcastVT), FPclassMask,
16794 DAG.getIntPtrConstant(0, dl));
16795 return DAG.getBitcast(Op.getValueType(), Res);
16798 SDValue Src1 = Op.getOperand(1);
16799 SDValue Imm = Op.getOperand(2);
16800 SDValue Mask = Op.getOperand(3);
16801 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16802 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16803 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16804 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16807 case CMP_MASK_CC: {
16808 // Comparison intrinsics with masks.
16809 // Example of transformation:
16810 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16811 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16813 // (v8i1 (insert_subvector undef,
16814 // (v2i1 (and (PCMPEQM %a, %b),
16815 // (extract_subvector
16816 // (v8i1 (bitcast %mask)), 0))), 0))))
16817 MVT VT = Op.getOperand(1).getSimpleValueType();
16818 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16819 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16820 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16821 Mask.getSimpleValueType().getSizeInBits());
16823 if (IntrData->Type == CMP_MASK_CC) {
16824 SDValue CC = Op.getOperand(3);
16825 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16826 // We specify 2 possible opcodes for intrinsics with rounding modes.
16827 // First, we check if the intrinsic may have non-default rounding mode,
16828 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16829 if (IntrData->Opc1 != 0) {
16830 SDValue Rnd = Op.getOperand(5);
16831 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16832 X86::STATIC_ROUNDING::CUR_DIRECTION)
16833 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16834 Op.getOperand(2), CC, Rnd);
16836 //default rounding mode
16838 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16839 Op.getOperand(2), CC);
16842 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16843 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16846 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16847 DAG.getTargetConstant(0, dl,
16850 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16851 DAG.getUNDEF(BitcastVT), CmpMask,
16852 DAG.getIntPtrConstant(0, dl));
16853 return DAG.getBitcast(Op.getValueType(), Res);
16855 case CMP_MASK_SCALAR_CC: {
16856 SDValue Src1 = Op.getOperand(1);
16857 SDValue Src2 = Op.getOperand(2);
16858 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16859 SDValue Mask = Op.getOperand(4);
16862 if (IntrData->Opc1 != 0) {
16863 SDValue Rnd = Op.getOperand(5);
16864 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16865 X86::STATIC_ROUNDING::CUR_DIRECTION)
16866 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16868 //default rounding mode
16870 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16872 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16873 DAG.getTargetConstant(0, dl,
16877 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16878 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16879 DAG.getValueType(MVT::i1));
16881 case COMI: { // Comparison intrinsics
16882 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16883 SDValue LHS = Op.getOperand(1);
16884 SDValue RHS = Op.getOperand(2);
16885 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16886 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16887 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16888 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16889 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16890 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16892 case COMI_RM: { // Comparison intrinsics with Sae
16893 SDValue LHS = Op.getOperand(1);
16894 SDValue RHS = Op.getOperand(2);
16895 SDValue CC = Op.getOperand(3);
16896 SDValue Sae = Op.getOperand(4);
16897 auto ComiType = TranslateX86ConstCondToX86CC(CC);
16898 // choose between ordered and unordered (comi/ucomi)
16899 unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16901 if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16902 X86::STATIC_ROUNDING::CUR_DIRECTION)
16903 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16905 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16906 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16907 DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16908 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16911 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16912 Op.getOperand(1), Op.getOperand(2), DAG);
16914 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16915 Op.getSimpleValueType(),
16917 Op.getOperand(2), DAG),
16918 Op.getOperand(4), Op.getOperand(3), Subtarget,
16920 case COMPRESS_EXPAND_IN_REG: {
16921 SDValue Mask = Op.getOperand(3);
16922 SDValue DataToCompress = Op.getOperand(1);
16923 SDValue PassThru = Op.getOperand(2);
16924 if (isAllOnesConstant(Mask)) // return data as is
16925 return Op.getOperand(1);
16927 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16929 Mask, PassThru, Subtarget, DAG);
16932 SDValue Mask = Op.getOperand(1);
16933 MVT MaskVT = MVT::getVectorVT(MVT::i1,
16934 Mask.getSimpleValueType().getSizeInBits());
16935 Mask = DAG.getBitcast(MaskVT, Mask);
16936 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16939 SDValue Mask = Op.getOperand(3);
16940 MVT VT = Op.getSimpleValueType();
16941 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16942 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16943 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16947 MVT VT = Op.getSimpleValueType();
16948 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16950 SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16951 SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16952 // Arguments should be swapped.
16953 SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16954 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16956 return DAG.getBitcast(VT, Res);
16958 case CONVERT_TO_MASK: {
16959 MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16960 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16961 MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16963 SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16965 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16966 DAG.getUNDEF(BitcastVT), CvtMask,
16967 DAG.getIntPtrConstant(0, dl));
16968 return DAG.getBitcast(Op.getValueType(), Res);
16970 case CONVERT_MASK_TO_VEC: {
16971 SDValue Mask = Op.getOperand(1);
16972 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16973 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16974 return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16976 case BRCST_SUBVEC_TO_VEC: {
16977 SDValue Src = Op.getOperand(1);
16978 SDValue Passthru = Op.getOperand(2);
16979 SDValue Mask = Op.getOperand(3);
16980 EVT resVT = Passthru.getValueType();
16981 SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16982 DAG.getUNDEF(resVT), Src,
16983 DAG.getIntPtrConstant(0, dl));
16985 if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16986 immVal = DAG.getConstant(0x44, dl, MVT::i8);
16988 immVal = DAG.getConstant(0, dl, MVT::i8);
16989 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16990 subVec, subVec, immVal),
16991 Mask, Passthru, Subtarget, DAG);
16999 default: return SDValue(); // Don't custom lower most intrinsics.
17001 case Intrinsic::x86_avx2_permd:
17002 case Intrinsic::x86_avx2_permps:
17003 // Operands intentionally swapped. Mask is last operand to intrinsic,
17004 // but second operand for node/instruction.
17005 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
17006 Op.getOperand(2), Op.getOperand(1));
17008 // ptest and testp intrinsics. The intrinsic these come from are designed to
17009 // return an integer value, not just an instruction so lower it to the ptest
17010 // or testp pattern and a setcc for the result.
17011 case Intrinsic::x86_sse41_ptestz:
17012 case Intrinsic::x86_sse41_ptestc:
17013 case Intrinsic::x86_sse41_ptestnzc:
17014 case Intrinsic::x86_avx_ptestz_256:
17015 case Intrinsic::x86_avx_ptestc_256:
17016 case Intrinsic::x86_avx_ptestnzc_256:
17017 case Intrinsic::x86_avx_vtestz_ps:
17018 case Intrinsic::x86_avx_vtestc_ps:
17019 case Intrinsic::x86_avx_vtestnzc_ps:
17020 case Intrinsic::x86_avx_vtestz_pd:
17021 case Intrinsic::x86_avx_vtestc_pd:
17022 case Intrinsic::x86_avx_vtestnzc_pd:
17023 case Intrinsic::x86_avx_vtestz_ps_256:
17024 case Intrinsic::x86_avx_vtestc_ps_256:
17025 case Intrinsic::x86_avx_vtestnzc_ps_256:
17026 case Intrinsic::x86_avx_vtestz_pd_256:
17027 case Intrinsic::x86_avx_vtestc_pd_256:
17028 case Intrinsic::x86_avx_vtestnzc_pd_256: {
17029 bool IsTestPacked = false;
17032 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17033 case Intrinsic::x86_avx_vtestz_ps:
17034 case Intrinsic::x86_avx_vtestz_pd:
17035 case Intrinsic::x86_avx_vtestz_ps_256:
17036 case Intrinsic::x86_avx_vtestz_pd_256:
17037 IsTestPacked = true; // Fallthrough
17038 case Intrinsic::x86_sse41_ptestz:
17039 case Intrinsic::x86_avx_ptestz_256:
17041 X86CC = X86::COND_E;
17043 case Intrinsic::x86_avx_vtestc_ps:
17044 case Intrinsic::x86_avx_vtestc_pd:
17045 case Intrinsic::x86_avx_vtestc_ps_256:
17046 case Intrinsic::x86_avx_vtestc_pd_256:
17047 IsTestPacked = true; // Fallthrough
17048 case Intrinsic::x86_sse41_ptestc:
17049 case Intrinsic::x86_avx_ptestc_256:
17051 X86CC = X86::COND_B;
17053 case Intrinsic::x86_avx_vtestnzc_ps:
17054 case Intrinsic::x86_avx_vtestnzc_pd:
17055 case Intrinsic::x86_avx_vtestnzc_ps_256:
17056 case Intrinsic::x86_avx_vtestnzc_pd_256:
17057 IsTestPacked = true; // Fallthrough
17058 case Intrinsic::x86_sse41_ptestnzc:
17059 case Intrinsic::x86_avx_ptestnzc_256:
17061 X86CC = X86::COND_A;
17065 SDValue LHS = Op.getOperand(1);
17066 SDValue RHS = Op.getOperand(2);
17067 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17068 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17069 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17070 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17071 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17073 case Intrinsic::x86_avx512_kortestz_w:
17074 case Intrinsic::x86_avx512_kortestc_w: {
17075 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17076 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17077 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17078 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17079 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17080 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17081 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17084 case Intrinsic::x86_sse42_pcmpistria128:
17085 case Intrinsic::x86_sse42_pcmpestria128:
17086 case Intrinsic::x86_sse42_pcmpistric128:
17087 case Intrinsic::x86_sse42_pcmpestric128:
17088 case Intrinsic::x86_sse42_pcmpistrio128:
17089 case Intrinsic::x86_sse42_pcmpestrio128:
17090 case Intrinsic::x86_sse42_pcmpistris128:
17091 case Intrinsic::x86_sse42_pcmpestris128:
17092 case Intrinsic::x86_sse42_pcmpistriz128:
17093 case Intrinsic::x86_sse42_pcmpestriz128: {
17097 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17098 case Intrinsic::x86_sse42_pcmpistria128:
17099 Opcode = X86ISD::PCMPISTRI;
17100 X86CC = X86::COND_A;
17102 case Intrinsic::x86_sse42_pcmpestria128:
17103 Opcode = X86ISD::PCMPESTRI;
17104 X86CC = X86::COND_A;
17106 case Intrinsic::x86_sse42_pcmpistric128:
17107 Opcode = X86ISD::PCMPISTRI;
17108 X86CC = X86::COND_B;
17110 case Intrinsic::x86_sse42_pcmpestric128:
17111 Opcode = X86ISD::PCMPESTRI;
17112 X86CC = X86::COND_B;
17114 case Intrinsic::x86_sse42_pcmpistrio128:
17115 Opcode = X86ISD::PCMPISTRI;
17116 X86CC = X86::COND_O;
17118 case Intrinsic::x86_sse42_pcmpestrio128:
17119 Opcode = X86ISD::PCMPESTRI;
17120 X86CC = X86::COND_O;
17122 case Intrinsic::x86_sse42_pcmpistris128:
17123 Opcode = X86ISD::PCMPISTRI;
17124 X86CC = X86::COND_S;
17126 case Intrinsic::x86_sse42_pcmpestris128:
17127 Opcode = X86ISD::PCMPESTRI;
17128 X86CC = X86::COND_S;
17130 case Intrinsic::x86_sse42_pcmpistriz128:
17131 Opcode = X86ISD::PCMPISTRI;
17132 X86CC = X86::COND_E;
17134 case Intrinsic::x86_sse42_pcmpestriz128:
17135 Opcode = X86ISD::PCMPESTRI;
17136 X86CC = X86::COND_E;
17139 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17140 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17141 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17142 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17143 DAG.getConstant(X86CC, dl, MVT::i8),
17144 SDValue(PCMP.getNode(), 1));
17145 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17148 case Intrinsic::x86_sse42_pcmpistri128:
17149 case Intrinsic::x86_sse42_pcmpestri128: {
17151 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17152 Opcode = X86ISD::PCMPISTRI;
17154 Opcode = X86ISD::PCMPESTRI;
17156 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17157 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17158 return DAG.getNode(Opcode, dl, VTs, NewOps);
17161 case Intrinsic::x86_seh_lsda: {
17162 // Compute the symbol for the LSDA. We know it'll get emitted later.
17163 MachineFunction &MF = DAG.getMachineFunction();
17164 SDValue Op1 = Op.getOperand(1);
17165 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17166 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17167 GlobalValue::getRealLinkageName(Fn->getName()));
17169 // Generate a simple absolute symbol reference. This intrinsic is only
17170 // supported on 32-bit Windows, which isn't PIC.
17171 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17172 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17175 case Intrinsic::x86_seh_recoverfp: {
17176 SDValue FnOp = Op.getOperand(1);
17177 SDValue IncomingFPOp = Op.getOperand(2);
17178 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17179 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17181 report_fatal_error(
17182 "llvm.x86.seh.recoverfp must take a function as the first argument");
17183 return recoverFramePointer(DAG, Fn, IncomingFPOp);
17186 case Intrinsic::localaddress: {
17187 // Returns one of the stack, base, or frame pointer registers, depending on
17188 // which is used to reference local variables.
17189 MachineFunction &MF = DAG.getMachineFunction();
17190 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17192 if (RegInfo->hasBasePointer(MF))
17193 Reg = RegInfo->getBaseRegister();
17194 else // This function handles the SP or FP case.
17195 Reg = RegInfo->getPtrSizedFrameRegister(MF);
17196 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17201 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17202 SDValue Src, SDValue Mask, SDValue Base,
17203 SDValue Index, SDValue ScaleOp, SDValue Chain,
17204 const X86Subtarget * Subtarget) {
17206 auto *C = cast<ConstantSDNode>(ScaleOp);
17207 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17208 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17209 Index.getSimpleValueType().getVectorNumElements());
17211 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17213 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17215 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17216 Mask.getSimpleValueType().getSizeInBits());
17218 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17219 // are extracted by EXTRACT_SUBVECTOR.
17220 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17221 DAG.getBitcast(BitcastVT, Mask),
17222 DAG.getIntPtrConstant(0, dl));
17224 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17225 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17226 SDValue Segment = DAG.getRegister(0, MVT::i32);
17227 if (Src.getOpcode() == ISD::UNDEF)
17228 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17229 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17230 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17231 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17232 return DAG.getMergeValues(RetOps, dl);
17235 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17236 SDValue Src, SDValue Mask, SDValue Base,
17237 SDValue Index, SDValue ScaleOp, SDValue Chain) {
17239 auto *C = cast<ConstantSDNode>(ScaleOp);
17240 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17241 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17242 SDValue Segment = DAG.getRegister(0, MVT::i32);
17243 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17244 Index.getSimpleValueType().getVectorNumElements());
17246 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17248 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17250 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17251 Mask.getSimpleValueType().getSizeInBits());
17253 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17254 // are extracted by EXTRACT_SUBVECTOR.
17255 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17256 DAG.getBitcast(BitcastVT, Mask),
17257 DAG.getIntPtrConstant(0, dl));
17259 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17260 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17261 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17262 return SDValue(Res, 1);
17265 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17266 SDValue Mask, SDValue Base, SDValue Index,
17267 SDValue ScaleOp, SDValue Chain) {
17269 auto *C = cast<ConstantSDNode>(ScaleOp);
17270 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17271 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17272 SDValue Segment = DAG.getRegister(0, MVT::i32);
17274 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17276 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17278 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17280 MaskInReg = DAG.getBitcast(MaskVT, Mask);
17281 //SDVTList VTs = DAG.getVTList(MVT::Other);
17282 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17283 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17284 return SDValue(Res, 0);
17287 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17288 // read performance monitor counters (x86_rdpmc).
17289 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17290 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17291 SmallVectorImpl<SDValue> &Results) {
17292 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17293 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17296 // The ECX register is used to select the index of the performance counter
17298 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17300 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17302 // Reads the content of a 64-bit performance counter and returns it in the
17303 // registers EDX:EAX.
17304 if (Subtarget->is64Bit()) {
17305 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17306 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17309 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17310 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17313 Chain = HI.getValue(1);
17315 if (Subtarget->is64Bit()) {
17316 // The EAX register is loaded with the low-order 32 bits. The EDX register
17317 // is loaded with the supported high-order bits of the counter.
17318 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17319 DAG.getConstant(32, DL, MVT::i8));
17320 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17321 Results.push_back(Chain);
17325 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17326 SDValue Ops[] = { LO, HI };
17327 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17328 Results.push_back(Pair);
17329 Results.push_back(Chain);
17332 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17333 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17334 // also used to custom lower READCYCLECOUNTER nodes.
17335 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17336 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17337 SmallVectorImpl<SDValue> &Results) {
17338 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17339 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17342 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17343 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17344 // and the EAX register is loaded with the low-order 32 bits.
17345 if (Subtarget->is64Bit()) {
17346 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17347 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17350 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17351 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17354 SDValue Chain = HI.getValue(1);
17356 if (Opcode == X86ISD::RDTSCP_DAG) {
17357 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17359 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17360 // the ECX register. Add 'ecx' explicitly to the chain.
17361 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17363 // Explicitly store the content of ECX at the location passed in input
17364 // to the 'rdtscp' intrinsic.
17365 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17366 MachinePointerInfo(), false, false, 0);
17369 if (Subtarget->is64Bit()) {
17370 // The EDX register is loaded with the high-order 32 bits of the MSR, and
17371 // the EAX register is loaded with the low-order 32 bits.
17372 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17373 DAG.getConstant(32, DL, MVT::i8));
17374 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17375 Results.push_back(Chain);
17379 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17380 SDValue Ops[] = { LO, HI };
17381 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17382 Results.push_back(Pair);
17383 Results.push_back(Chain);
17386 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17387 SelectionDAG &DAG) {
17388 SmallVector<SDValue, 2> Results;
17390 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17392 return DAG.getMergeValues(Results, DL);
17395 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17396 MachineFunction &MF = DAG.getMachineFunction();
17397 SDValue Chain = Op.getOperand(0);
17398 SDValue RegNode = Op.getOperand(2);
17399 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17401 report_fatal_error("EH registrations only live in functions using WinEH");
17403 // Cast the operand to an alloca, and remember the frame index.
17404 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17406 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17407 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17409 // Return the chain operand without making any DAG nodes.
17413 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17414 /// return truncate Store/MaskedStore Node
17415 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17419 SDValue Mask = Op.getOperand(4);
17420 SDValue DataToTruncate = Op.getOperand(3);
17421 SDValue Addr = Op.getOperand(2);
17422 SDValue Chain = Op.getOperand(0);
17424 MVT VT = DataToTruncate.getSimpleValueType();
17425 MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17427 if (isAllOnesConstant(Mask)) // return just a truncate store
17428 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17429 MachinePointerInfo(), SVT, false, false,
17430 SVT.getScalarSizeInBits()/8);
17432 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17433 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17434 Mask.getSimpleValueType().getSizeInBits());
17435 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17436 // are extracted by EXTRACT_SUBVECTOR.
17437 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17438 DAG.getBitcast(BitcastVT, Mask),
17439 DAG.getIntPtrConstant(0, dl));
17441 MachineMemOperand *MMO = DAG.getMachineFunction().
17442 getMachineMemOperand(MachinePointerInfo(),
17443 MachineMemOperand::MOStore, SVT.getStoreSize(),
17444 SVT.getScalarSizeInBits()/8);
17446 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17447 VMask, SVT, MMO, true);
17450 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17451 SelectionDAG &DAG) {
17452 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17454 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17456 if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17457 return MarkEHRegistrationNode(Op, DAG);
17458 if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17459 IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17460 IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17461 IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17462 // We need a frame pointer because this will get lowered to a PUSH/POP
17464 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17465 MFI->setHasCopyImplyingStackAdjustment(true);
17466 // Don't do anything here, we will expand these intrinsics out later
17467 // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17474 switch(IntrData->Type) {
17475 default: llvm_unreachable("Unknown Intrinsic Type");
17478 // Emit the node with the right value type.
17479 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17480 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17482 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17483 // Otherwise return the value from Rand, which is always 0, casted to i32.
17484 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17485 DAG.getConstant(1, dl, Op->getValueType(1)),
17486 DAG.getConstant(X86::COND_B, dl, MVT::i32),
17487 SDValue(Result.getNode(), 1) };
17488 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17489 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17492 // Return { result, isValid, chain }.
17493 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17494 SDValue(Result.getNode(), 2));
17497 //gather(v1, mask, index, base, scale);
17498 SDValue Chain = Op.getOperand(0);
17499 SDValue Src = Op.getOperand(2);
17500 SDValue Base = Op.getOperand(3);
17501 SDValue Index = Op.getOperand(4);
17502 SDValue Mask = Op.getOperand(5);
17503 SDValue Scale = Op.getOperand(6);
17504 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17508 //scatter(base, mask, index, v1, scale);
17509 SDValue Chain = Op.getOperand(0);
17510 SDValue Base = Op.getOperand(2);
17511 SDValue Mask = Op.getOperand(3);
17512 SDValue Index = Op.getOperand(4);
17513 SDValue Src = Op.getOperand(5);
17514 SDValue Scale = Op.getOperand(6);
17515 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17519 SDValue Hint = Op.getOperand(6);
17520 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17521 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17522 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17523 SDValue Chain = Op.getOperand(0);
17524 SDValue Mask = Op.getOperand(2);
17525 SDValue Index = Op.getOperand(3);
17526 SDValue Base = Op.getOperand(4);
17527 SDValue Scale = Op.getOperand(5);
17528 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17530 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17532 SmallVector<SDValue, 2> Results;
17533 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17535 return DAG.getMergeValues(Results, dl);
17537 // Read Performance Monitoring Counters.
17539 SmallVector<SDValue, 2> Results;
17540 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17541 return DAG.getMergeValues(Results, dl);
17543 // XTEST intrinsics.
17545 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17546 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17547 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17548 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17550 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17551 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17552 Ret, SDValue(InTrans.getNode(), 1));
17556 SmallVector<SDValue, 2> Results;
17557 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17558 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17559 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17560 DAG.getConstant(-1, dl, MVT::i8));
17561 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17562 Op.getOperand(4), GenCF.getValue(1));
17563 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17564 Op.getOperand(5), MachinePointerInfo(),
17566 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17567 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17569 Results.push_back(SetCC);
17570 Results.push_back(Store);
17571 return DAG.getMergeValues(Results, dl);
17573 case COMPRESS_TO_MEM: {
17574 SDValue Mask = Op.getOperand(4);
17575 SDValue DataToCompress = Op.getOperand(3);
17576 SDValue Addr = Op.getOperand(2);
17577 SDValue Chain = Op.getOperand(0);
17579 MVT VT = DataToCompress.getSimpleValueType();
17580 if (isAllOnesConstant(Mask)) // return just a store
17581 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17582 MachinePointerInfo(), false, false,
17583 VT.getScalarSizeInBits()/8);
17585 SDValue Compressed =
17586 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17587 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17588 return DAG.getStore(Chain, dl, Compressed, Addr,
17589 MachinePointerInfo(), false, false,
17590 VT.getScalarSizeInBits()/8);
17592 case TRUNCATE_TO_MEM_VI8:
17593 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17594 case TRUNCATE_TO_MEM_VI16:
17595 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17596 case TRUNCATE_TO_MEM_VI32:
17597 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17598 case EXPAND_FROM_MEM: {
17599 SDValue Mask = Op.getOperand(4);
17600 SDValue PassThru = Op.getOperand(3);
17601 SDValue Addr = Op.getOperand(2);
17602 SDValue Chain = Op.getOperand(0);
17603 MVT VT = Op.getSimpleValueType();
17605 if (isAllOnesConstant(Mask)) // return just a load
17606 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17607 false, VT.getScalarSizeInBits()/8);
17609 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17610 false, false, false,
17611 VT.getScalarSizeInBits()/8);
17613 SDValue Results[] = {
17614 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17615 Mask, PassThru, Subtarget, DAG), Chain};
17616 return DAG.getMergeValues(Results, dl);
17620 SDValue Mask = Op.getOperand(4);
17621 SDValue PassThru = Op.getOperand(3);
17622 SDValue Addr = Op.getOperand(2);
17623 SDValue Chain = Op.getOperand(0);
17624 MVT VT = Op.getSimpleValueType();
17626 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
17627 assert(MemIntr && "Expected MemIntrinsicSDNode!");
17629 if (isAllOnesConstant(Mask)) // return just a load
17630 return DAG.getLoad(VT, dl, Chain, Addr, MemIntr->getMemOperand());
17632 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17633 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17634 return DAG.getMaskedLoad(VT, dl, Chain, Addr, VMask, PassThru, VT,
17635 MemIntr->getMemOperand(), ISD::NON_EXTLOAD);
17640 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17641 SelectionDAG &DAG) const {
17642 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17643 MFI->setReturnAddressIsTaken(true);
17645 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17648 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17650 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17653 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17654 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17655 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17656 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17657 DAG.getNode(ISD::ADD, dl, PtrVT,
17658 FrameAddr, Offset),
17659 MachinePointerInfo(), false, false, false, 0);
17662 // Just load the return address.
17663 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17664 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17665 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17668 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17669 MachineFunction &MF = DAG.getMachineFunction();
17670 MachineFrameInfo *MFI = MF.getFrameInfo();
17671 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17672 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17673 EVT VT = Op.getValueType();
17675 MFI->setFrameAddressIsTaken(true);
17677 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17678 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17679 // is not possible to crawl up the stack without looking at the unwind codes
17681 int FrameAddrIndex = FuncInfo->getFAIndex();
17682 if (!FrameAddrIndex) {
17683 // Set up a frame object for the return address.
17684 unsigned SlotSize = RegInfo->getSlotSize();
17685 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17686 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17687 FuncInfo->setFAIndex(FrameAddrIndex);
17689 return DAG.getFrameIndex(FrameAddrIndex, VT);
17692 unsigned FrameReg =
17693 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17694 SDLoc dl(Op); // FIXME probably not meaningful
17695 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17696 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17697 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17698 "Invalid Frame Register!");
17699 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17701 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17702 MachinePointerInfo(),
17703 false, false, false, 0);
17707 // FIXME? Maybe this could be a TableGen attribute on some registers and
17708 // this table could be generated automatically from RegInfo.
17709 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17710 SelectionDAG &DAG) const {
17711 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17712 const MachineFunction &MF = DAG.getMachineFunction();
17714 unsigned Reg = StringSwitch<unsigned>(RegName)
17715 .Case("esp", X86::ESP)
17716 .Case("rsp", X86::RSP)
17717 .Case("ebp", X86::EBP)
17718 .Case("rbp", X86::RBP)
17721 if (Reg == X86::EBP || Reg == X86::RBP) {
17722 if (!TFI.hasFP(MF))
17723 report_fatal_error("register " + StringRef(RegName) +
17724 " is allocatable: function has no frame pointer");
17727 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17728 unsigned FrameReg =
17729 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17730 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17731 "Invalid Frame Register!");
17739 report_fatal_error("Invalid register name global variable");
17742 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17743 SelectionDAG &DAG) const {
17744 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17745 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17748 unsigned X86TargetLowering::getExceptionPointerRegister(
17749 const Constant *PersonalityFn) const {
17750 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17751 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17753 return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17756 unsigned X86TargetLowering::getExceptionSelectorRegister(
17757 const Constant *PersonalityFn) const {
17758 // Funclet personalities don't use selectors (the runtime does the selection).
17759 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17760 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17763 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17764 SDValue Chain = Op.getOperand(0);
17765 SDValue Offset = Op.getOperand(1);
17766 SDValue Handler = Op.getOperand(2);
17769 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17770 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17771 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17772 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17773 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17774 "Invalid Frame Register!");
17775 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17776 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17778 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17779 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17781 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17782 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17784 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17786 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17787 DAG.getRegister(StoreAddrReg, PtrVT));
17790 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17791 SelectionDAG &DAG) const {
17793 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17794 DAG.getVTList(MVT::i32, MVT::Other),
17795 Op.getOperand(0), Op.getOperand(1));
17798 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17799 SelectionDAG &DAG) const {
17801 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17802 Op.getOperand(0), Op.getOperand(1));
17805 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17806 return Op.getOperand(0);
17809 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17810 SelectionDAG &DAG) const {
17811 SDValue Root = Op.getOperand(0);
17812 SDValue Trmp = Op.getOperand(1); // trampoline
17813 SDValue FPtr = Op.getOperand(2); // nested function
17814 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17817 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17818 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17820 if (Subtarget->is64Bit()) {
17821 SDValue OutChains[6];
17823 // Large code-model.
17824 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17825 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17827 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17828 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17830 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17832 // Load the pointer to the nested function into R11.
17833 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17834 SDValue Addr = Trmp;
17835 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17836 Addr, MachinePointerInfo(TrmpAddr),
17839 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17840 DAG.getConstant(2, dl, MVT::i64));
17841 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17842 MachinePointerInfo(TrmpAddr, 2),
17845 // Load the 'nest' parameter value into R10.
17846 // R10 is specified in X86CallingConv.td
17847 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17848 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17849 DAG.getConstant(10, dl, MVT::i64));
17850 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17851 Addr, MachinePointerInfo(TrmpAddr, 10),
17854 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17855 DAG.getConstant(12, dl, MVT::i64));
17856 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17857 MachinePointerInfo(TrmpAddr, 12),
17860 // Jump to the nested function.
17861 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17862 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17863 DAG.getConstant(20, dl, MVT::i64));
17864 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17865 Addr, MachinePointerInfo(TrmpAddr, 20),
17868 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17869 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17870 DAG.getConstant(22, dl, MVT::i64));
17871 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17872 Addr, MachinePointerInfo(TrmpAddr, 22),
17875 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17877 const Function *Func =
17878 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17879 CallingConv::ID CC = Func->getCallingConv();
17884 llvm_unreachable("Unsupported calling convention");
17885 case CallingConv::C:
17886 case CallingConv::X86_StdCall: {
17887 // Pass 'nest' parameter in ECX.
17888 // Must be kept in sync with X86CallingConv.td
17889 NestReg = X86::ECX;
17891 // Check that ECX wasn't needed by an 'inreg' parameter.
17892 FunctionType *FTy = Func->getFunctionType();
17893 const AttributeSet &Attrs = Func->getAttributes();
17895 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17896 unsigned InRegCount = 0;
17899 for (FunctionType::param_iterator I = FTy->param_begin(),
17900 E = FTy->param_end(); I != E; ++I, ++Idx)
17901 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17902 auto &DL = DAG.getDataLayout();
17903 // FIXME: should only count parameters that are lowered to integers.
17904 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17907 if (InRegCount > 2) {
17908 report_fatal_error("Nest register in use - reduce number of inreg"
17914 case CallingConv::X86_FastCall:
17915 case CallingConv::X86_ThisCall:
17916 case CallingConv::Fast:
17917 // Pass 'nest' parameter in EAX.
17918 // Must be kept in sync with X86CallingConv.td
17919 NestReg = X86::EAX;
17923 SDValue OutChains[4];
17924 SDValue Addr, Disp;
17926 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17927 DAG.getConstant(10, dl, MVT::i32));
17928 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17930 // This is storing the opcode for MOV32ri.
17931 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17932 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17933 OutChains[0] = DAG.getStore(Root, dl,
17934 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17935 Trmp, MachinePointerInfo(TrmpAddr),
17938 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17939 DAG.getConstant(1, dl, MVT::i32));
17940 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17941 MachinePointerInfo(TrmpAddr, 1),
17944 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17945 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17946 DAG.getConstant(5, dl, MVT::i32));
17947 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17948 Addr, MachinePointerInfo(TrmpAddr, 5),
17951 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17952 DAG.getConstant(6, dl, MVT::i32));
17953 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17954 MachinePointerInfo(TrmpAddr, 6),
17957 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17961 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17962 SelectionDAG &DAG) const {
17964 The rounding mode is in bits 11:10 of FPSR, and has the following
17966 00 Round to nearest
17971 FLT_ROUNDS, on the other hand, expects the following:
17978 To perform the conversion, we do:
17979 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17982 MachineFunction &MF = DAG.getMachineFunction();
17983 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17984 unsigned StackAlignment = TFI.getStackAlignment();
17985 MVT VT = Op.getSimpleValueType();
17988 // Save FP Control Word to stack slot
17989 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17990 SDValue StackSlot =
17991 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17993 MachineMemOperand *MMO =
17994 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17995 MachineMemOperand::MOStore, 2, 2);
17997 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17998 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17999 DAG.getVTList(MVT::Other),
18000 Ops, MVT::i16, MMO);
18002 // Load FP Control Word from stack slot
18003 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
18004 MachinePointerInfo(), false, false, false, 0);
18006 // Transform as necessary
18008 DAG.getNode(ISD::SRL, DL, MVT::i16,
18009 DAG.getNode(ISD::AND, DL, MVT::i16,
18010 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
18011 DAG.getConstant(11, DL, MVT::i8));
18013 DAG.getNode(ISD::SRL, DL, MVT::i16,
18014 DAG.getNode(ISD::AND, DL, MVT::i16,
18015 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
18016 DAG.getConstant(9, DL, MVT::i8));
18019 DAG.getNode(ISD::AND, DL, MVT::i16,
18020 DAG.getNode(ISD::ADD, DL, MVT::i16,
18021 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
18022 DAG.getConstant(1, DL, MVT::i16)),
18023 DAG.getConstant(3, DL, MVT::i16));
18025 return DAG.getNode((VT.getSizeInBits() < 16 ?
18026 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
18029 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
18031 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
18032 // to 512-bit vector.
18033 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
18034 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
18035 // split the vector, perform operation on it's Lo a Hi part and
18036 // concatenate the results.
18037 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
18039 MVT VT = Op.getSimpleValueType();
18040 MVT EltVT = VT.getVectorElementType();
18041 unsigned NumElems = VT.getVectorNumElements();
18043 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
18044 // Extend to 512 bit vector.
18045 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18046 "Unsupported value type for operation");
18048 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
18049 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
18050 DAG.getUNDEF(NewVT),
18052 DAG.getIntPtrConstant(0, dl));
18053 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
18055 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
18056 DAG.getIntPtrConstant(0, dl));
18059 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
18060 "Unsupported element type");
18062 if (16 < NumElems) {
18063 // Split vector, it's Lo and Hi parts will be handled in next iteration.
18065 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
18066 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
18068 Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
18069 Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
18071 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
18074 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
18076 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18077 "Unsupported value type for operation");
18079 // Use native supported vector instruction vplzcntd.
18080 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18081 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18082 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18083 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18085 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18088 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18089 SelectionDAG &DAG) {
18090 MVT VT = Op.getSimpleValueType();
18092 unsigned NumBits = VT.getSizeInBits();
18095 if (VT.isVector() && Subtarget->hasAVX512())
18096 return LowerVectorCTLZ_AVX512(Op, DAG);
18098 Op = Op.getOperand(0);
18099 if (VT == MVT::i8) {
18100 // Zero extend to i32 since there is not an i8 bsr.
18102 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18105 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18106 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18107 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18109 // If src is zero (i.e. bsr sets ZF), returns NumBits.
18112 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18113 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18116 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18118 // Finally xor with NumBits-1.
18119 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18120 DAG.getConstant(NumBits - 1, dl, OpVT));
18123 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18127 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18128 SelectionDAG &DAG) {
18129 MVT VT = Op.getSimpleValueType();
18131 unsigned NumBits = VT.getSizeInBits();
18134 Op = Op.getOperand(0);
18135 if (VT == MVT::i8) {
18136 // Zero extend to i32 since there is not an i8 bsr.
18138 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18141 // Issue a bsr (scan bits in reverse).
18142 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18143 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18145 // And xor with NumBits-1.
18146 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18147 DAG.getConstant(NumBits - 1, dl, OpVT));
18150 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18154 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18155 MVT VT = Op.getSimpleValueType();
18156 unsigned NumBits = VT.getScalarSizeInBits();
18159 if (VT.isVector()) {
18160 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18162 SDValue N0 = Op.getOperand(0);
18163 SDValue Zero = DAG.getConstant(0, dl, VT);
18165 // lsb(x) = (x & -x)
18166 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18167 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18169 // cttz_undef(x) = (width - 1) - ctlz(lsb)
18170 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18171 TLI.isOperationLegal(ISD::CTLZ, VT)) {
18172 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18173 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18174 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18177 // cttz(x) = ctpop(lsb - 1)
18178 SDValue One = DAG.getConstant(1, dl, VT);
18179 return DAG.getNode(ISD::CTPOP, dl, VT,
18180 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18183 assert(Op.getOpcode() == ISD::CTTZ &&
18184 "Only scalar CTTZ requires custom lowering");
18186 // Issue a bsf (scan bits forward) which also sets EFLAGS.
18187 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18188 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18190 // If src is zero (i.e. bsf sets ZF), returns NumBits.
18193 DAG.getConstant(NumBits, dl, VT),
18194 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18197 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18200 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18201 // ones, and then concatenate the result back.
18202 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18203 MVT VT = Op.getSimpleValueType();
18205 assert(VT.is256BitVector() && VT.isInteger() &&
18206 "Unsupported value type for operation");
18208 unsigned NumElems = VT.getVectorNumElements();
18211 // Extract the LHS vectors
18212 SDValue LHS = Op.getOperand(0);
18213 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18214 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18216 // Extract the RHS vectors
18217 SDValue RHS = Op.getOperand(1);
18218 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18219 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18221 MVT EltVT = VT.getVectorElementType();
18222 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18224 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18225 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18226 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18229 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18230 if (Op.getValueType() == MVT::i1)
18231 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18232 Op.getOperand(0), Op.getOperand(1));
18233 assert(Op.getSimpleValueType().is256BitVector() &&
18234 Op.getSimpleValueType().isInteger() &&
18235 "Only handle AVX 256-bit vector integer operation");
18236 return Lower256IntArith(Op, DAG);
18239 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18240 if (Op.getValueType() == MVT::i1)
18241 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18242 Op.getOperand(0), Op.getOperand(1));
18243 assert(Op.getSimpleValueType().is256BitVector() &&
18244 Op.getSimpleValueType().isInteger() &&
18245 "Only handle AVX 256-bit vector integer operation");
18246 return Lower256IntArith(Op, DAG);
18249 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18250 assert(Op.getSimpleValueType().is256BitVector() &&
18251 Op.getSimpleValueType().isInteger() &&
18252 "Only handle AVX 256-bit vector integer operation");
18253 return Lower256IntArith(Op, DAG);
18256 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18257 SelectionDAG &DAG) {
18259 MVT VT = Op.getSimpleValueType();
18262 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18264 // Decompose 256-bit ops into smaller 128-bit ops.
18265 if (VT.is256BitVector() && !Subtarget->hasInt256())
18266 return Lower256IntArith(Op, DAG);
18268 SDValue A = Op.getOperand(0);
18269 SDValue B = Op.getOperand(1);
18271 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18272 // pairs, multiply and truncate.
18273 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18274 if (Subtarget->hasInt256()) {
18275 if (VT == MVT::v32i8) {
18276 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18277 SDValue Lo = DAG.getIntPtrConstant(0, dl);
18278 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18279 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18280 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18281 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18282 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18283 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18284 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18285 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18288 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18289 return DAG.getNode(
18290 ISD::TRUNCATE, dl, VT,
18291 DAG.getNode(ISD::MUL, dl, ExVT,
18292 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18293 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18296 assert(VT == MVT::v16i8 &&
18297 "Pre-AVX2 support only supports v16i8 multiplication");
18298 MVT ExVT = MVT::v8i16;
18300 // Extract the lo parts and sign extend to i16
18302 if (Subtarget->hasSSE41()) {
18303 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18304 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18306 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18307 -1, 4, -1, 5, -1, 6, -1, 7};
18308 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18309 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18310 ALo = DAG.getBitcast(ExVT, ALo);
18311 BLo = DAG.getBitcast(ExVT, BLo);
18312 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18313 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18316 // Extract the hi parts and sign extend to i16
18318 if (Subtarget->hasSSE41()) {
18319 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
18320 -1, -1, -1, -1, -1, -1, -1, -1};
18321 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18322 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18323 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18324 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18326 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
18327 -1, 12, -1, 13, -1, 14, -1, 15};
18328 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18329 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18330 AHi = DAG.getBitcast(ExVT, AHi);
18331 BHi = DAG.getBitcast(ExVT, BHi);
18332 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18333 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18336 // Multiply, mask the lower 8bits of the lo/hi results and pack
18337 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18338 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18339 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18340 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18341 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18344 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18345 if (VT == MVT::v4i32) {
18346 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18347 "Should not custom lower when pmuldq is available!");
18349 // Extract the odd parts.
18350 static const int UnpackMask[] = { 1, -1, 3, -1 };
18351 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18352 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18354 // Multiply the even parts.
18355 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18356 // Now multiply odd parts.
18357 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18359 Evens = DAG.getBitcast(VT, Evens);
18360 Odds = DAG.getBitcast(VT, Odds);
18362 // Merge the two vectors back together with a shuffle. This expands into 2
18364 static const int ShufMask[] = { 0, 4, 2, 6 };
18365 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18368 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18369 "Only know how to lower V2I64/V4I64/V8I64 multiply");
18371 // Ahi = psrlqi(a, 32);
18372 // Bhi = psrlqi(b, 32);
18374 // AloBlo = pmuludq(a, b);
18375 // AloBhi = pmuludq(a, Bhi);
18376 // AhiBlo = pmuludq(Ahi, b);
18378 // AloBhi = psllqi(AloBhi, 32);
18379 // AhiBlo = psllqi(AhiBlo, 32);
18380 // return AloBlo + AloBhi + AhiBlo;
18382 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18383 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18385 SDValue AhiBlo = Ahi;
18386 SDValue AloBhi = Bhi;
18387 // Bit cast to 32-bit vectors for MULUDQ
18388 MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18389 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18390 A = DAG.getBitcast(MulVT, A);
18391 B = DAG.getBitcast(MulVT, B);
18392 Ahi = DAG.getBitcast(MulVT, Ahi);
18393 Bhi = DAG.getBitcast(MulVT, Bhi);
18395 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18396 // After shifting right const values the result may be all-zero.
18397 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18398 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18399 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18401 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18402 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18403 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18406 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18407 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18410 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18411 assert(Subtarget->isTargetWin64() && "Unexpected target");
18412 EVT VT = Op.getValueType();
18413 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18414 "Unexpected return type for lowering");
18418 switch (Op->getOpcode()) {
18419 default: llvm_unreachable("Unexpected request for libcall!");
18420 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
18421 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
18422 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
18423 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
18424 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
18425 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18429 SDValue InChain = DAG.getEntryNode();
18431 TargetLowering::ArgListTy Args;
18432 TargetLowering::ArgListEntry Entry;
18433 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18434 EVT ArgVT = Op->getOperand(i).getValueType();
18435 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18436 "Unexpected argument type for lowering");
18437 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18438 Entry.Node = StackPtr;
18439 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18441 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18442 Entry.Ty = PointerType::get(ArgTy,0);
18443 Entry.isSExt = false;
18444 Entry.isZExt = false;
18445 Args.push_back(Entry);
18448 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18449 getPointerTy(DAG.getDataLayout()));
18451 TargetLowering::CallLoweringInfo CLI(DAG);
18452 CLI.setDebugLoc(dl).setChain(InChain)
18453 .setCallee(getLibcallCallingConv(LC),
18454 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18455 Callee, std::move(Args), 0)
18456 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18458 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18459 return DAG.getBitcast(VT, CallInfo.first);
18462 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18463 SelectionDAG &DAG) {
18464 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18465 MVT VT = Op0.getSimpleValueType();
18468 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18469 (VT == MVT::v8i32 && Subtarget->hasInt256()));
18471 // PMULxD operations multiply each even value (starting at 0) of LHS with
18472 // the related value of RHS and produce a widen result.
18473 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18474 // => <2 x i64> <ae|cg>
18476 // In other word, to have all the results, we need to perform two PMULxD:
18477 // 1. one with the even values.
18478 // 2. one with the odd values.
18479 // To achieve #2, with need to place the odd values at an even position.
18481 // Place the odd value at an even position (basically, shift all values 1
18482 // step to the left):
18483 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18484 // <a|b|c|d> => <b|undef|d|undef>
18485 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18486 // <e|f|g|h> => <f|undef|h|undef>
18487 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18489 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18491 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18492 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18494 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18495 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18496 // => <2 x i64> <ae|cg>
18497 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18498 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18499 // => <2 x i64> <bf|dh>
18500 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18502 // Shuffle it back into the right order.
18503 SDValue Highs, Lows;
18504 if (VT == MVT::v8i32) {
18505 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18506 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18507 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18508 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18510 const int HighMask[] = {1, 5, 3, 7};
18511 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18512 const int LowMask[] = {0, 4, 2, 6};
18513 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18516 // If we have a signed multiply but no PMULDQ fix up the high parts of a
18517 // unsigned multiply.
18518 if (IsSigned && !Subtarget->hasSSE41()) {
18519 SDValue ShAmt = DAG.getConstant(
18521 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18522 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18523 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18524 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18525 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18527 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18528 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18531 // The first result of MUL_LOHI is actually the low value, followed by the
18533 SDValue Ops[] = {Lows, Highs};
18534 return DAG.getMergeValues(Ops, dl);
18537 // Return true if the required (according to Opcode) shift-imm form is natively
18538 // supported by the Subtarget
18539 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18541 if (VT.getScalarSizeInBits() < 16)
18544 if (VT.is512BitVector() &&
18545 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18548 bool LShift = VT.is128BitVector() ||
18549 (VT.is256BitVector() && Subtarget->hasInt256());
18551 bool AShift = LShift && (Subtarget->hasVLX() ||
18552 (VT != MVT::v2i64 && VT != MVT::v4i64));
18553 return (Opcode == ISD::SRA) ? AShift : LShift;
18556 // The shift amount is a variable, but it is the same for all vector lanes.
18557 // These instructions are defined together with shift-immediate.
18559 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18561 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18564 // Return true if the required (according to Opcode) variable-shift form is
18565 // natively supported by the Subtarget
18566 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18569 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18572 // vXi16 supported only on AVX-512, BWI
18573 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18576 if (VT.is512BitVector() || Subtarget->hasVLX())
18579 bool LShift = VT.is128BitVector() || VT.is256BitVector();
18580 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
18581 return (Opcode == ISD::SRA) ? AShift : LShift;
18584 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18585 const X86Subtarget *Subtarget) {
18586 MVT VT = Op.getSimpleValueType();
18588 SDValue R = Op.getOperand(0);
18589 SDValue Amt = Op.getOperand(1);
18591 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18592 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18594 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18595 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18596 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18597 SDValue Ex = DAG.getBitcast(ExVT, R);
18599 if (ShiftAmt >= 32) {
18600 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18602 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18603 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18604 ShiftAmt - 32, DAG);
18605 if (VT == MVT::v2i64)
18606 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18607 if (VT == MVT::v4i64)
18608 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18609 {9, 1, 11, 3, 13, 5, 15, 7});
18611 // SRA upper i32, SHL whole i64 and select lower i32.
18612 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18615 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18616 Lower = DAG.getBitcast(ExVT, Lower);
18617 if (VT == MVT::v2i64)
18618 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18619 if (VT == MVT::v4i64)
18620 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18621 {8, 1, 10, 3, 12, 5, 14, 7});
18623 return DAG.getBitcast(VT, Ex);
18626 // Optimize shl/srl/sra with constant shift amount.
18627 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18628 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18629 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18631 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18632 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18634 // i64 SRA needs to be performed as partial shifts.
18635 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18636 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18637 return ArithmeticShiftRight64(ShiftAmt);
18639 if (VT == MVT::v16i8 ||
18640 (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18641 VT == MVT::v64i8) {
18642 unsigned NumElts = VT.getVectorNumElements();
18643 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18645 // Simple i8 add case
18646 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18647 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18649 // ashr(R, 7) === cmp_slt(R, 0)
18650 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18651 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18652 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18655 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18656 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18659 if (Op.getOpcode() == ISD::SHL) {
18660 // Make a large shift.
18661 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18663 SHL = DAG.getBitcast(VT, SHL);
18664 // Zero out the rightmost bits.
18665 return DAG.getNode(ISD::AND, dl, VT, SHL,
18666 DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18668 if (Op.getOpcode() == ISD::SRL) {
18669 // Make a large shift.
18670 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18672 SRL = DAG.getBitcast(VT, SRL);
18673 // Zero out the leftmost bits.
18674 return DAG.getNode(ISD::AND, dl, VT, SRL,
18675 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18677 if (Op.getOpcode() == ISD::SRA) {
18678 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18679 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18681 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18682 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18683 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18686 llvm_unreachable("Unknown shift opcode.");
18691 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18692 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18693 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18695 // Peek through any splat that was introduced for i64 shift vectorization.
18696 int SplatIndex = -1;
18697 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18698 if (SVN->isSplat()) {
18699 SplatIndex = SVN->getSplatIndex();
18700 Amt = Amt.getOperand(0);
18701 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18702 "Splat shuffle referencing second operand");
18705 if (Amt.getOpcode() != ISD::BITCAST ||
18706 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18709 Amt = Amt.getOperand(0);
18710 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18711 VT.getVectorNumElements();
18712 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18713 uint64_t ShiftAmt = 0;
18714 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18715 for (unsigned i = 0; i != Ratio; ++i) {
18716 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18720 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18723 // Check remaining shift amounts (if not a splat).
18724 if (SplatIndex < 0) {
18725 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18726 uint64_t ShAmt = 0;
18727 for (unsigned j = 0; j != Ratio; ++j) {
18728 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18732 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18734 if (ShAmt != ShiftAmt)
18739 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18740 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18742 if (Op.getOpcode() == ISD::SRA)
18743 return ArithmeticShiftRight64(ShiftAmt);
18749 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18750 const X86Subtarget* Subtarget) {
18751 MVT VT = Op.getSimpleValueType();
18753 SDValue R = Op.getOperand(0);
18754 SDValue Amt = Op.getOperand(1);
18756 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18757 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18759 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18760 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18762 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18764 MVT EltVT = VT.getVectorElementType();
18766 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18767 // Check if this build_vector node is doing a splat.
18768 // If so, then set BaseShAmt equal to the splat value.
18769 BaseShAmt = BV->getSplatValue();
18770 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18771 BaseShAmt = SDValue();
18773 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18774 Amt = Amt.getOperand(0);
18776 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18777 if (SVN && SVN->isSplat()) {
18778 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18779 SDValue InVec = Amt.getOperand(0);
18780 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18781 assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18782 "Unexpected shuffle index found!");
18783 BaseShAmt = InVec.getOperand(SplatIdx);
18784 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18785 if (ConstantSDNode *C =
18786 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18787 if (C->getZExtValue() == SplatIdx)
18788 BaseShAmt = InVec.getOperand(1);
18793 // Avoid introducing an extract element from a shuffle.
18794 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18795 DAG.getIntPtrConstant(SplatIdx, dl));
18799 if (BaseShAmt.getNode()) {
18800 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18801 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18802 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18803 else if (EltVT.bitsLT(MVT::i32))
18804 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18806 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18810 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18811 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18812 Amt.getOpcode() == ISD::BITCAST &&
18813 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18814 Amt = Amt.getOperand(0);
18815 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18816 VT.getVectorNumElements();
18817 std::vector<SDValue> Vals(Ratio);
18818 for (unsigned i = 0; i != Ratio; ++i)
18819 Vals[i] = Amt.getOperand(i);
18820 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18821 for (unsigned j = 0; j != Ratio; ++j)
18822 if (Vals[j] != Amt.getOperand(i + j))
18826 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18827 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18832 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18833 SelectionDAG &DAG) {
18834 MVT VT = Op.getSimpleValueType();
18836 SDValue R = Op.getOperand(0);
18837 SDValue Amt = Op.getOperand(1);
18839 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18840 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18842 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18845 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18848 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18851 // XOP has 128-bit variable logical/arithmetic shifts.
18852 // +ve/-ve Amt = shift left/right.
18853 if (Subtarget->hasXOP() &&
18854 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18855 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18856 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18857 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18858 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18860 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18861 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18862 if (Op.getOpcode() == ISD::SRA)
18863 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18866 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18867 // shifts per-lane and then shuffle the partial results back together.
18868 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18869 // Splat the shift amounts so the scalar shifts above will catch it.
18870 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18871 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18872 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18873 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18874 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18877 // i64 vector arithmetic shift can be emulated with the transform:
18878 // M = lshr(SIGN_BIT, Amt)
18879 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18880 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18881 Op.getOpcode() == ISD::SRA) {
18882 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18883 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18884 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18885 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18886 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18890 // If possible, lower this packed shift into a vector multiply instead of
18891 // expanding it into a sequence of scalar shifts.
18892 // Do this only if the vector shift count is a constant build_vector.
18893 if (Op.getOpcode() == ISD::SHL &&
18894 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18895 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18896 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18897 SmallVector<SDValue, 8> Elts;
18898 MVT SVT = VT.getVectorElementType();
18899 unsigned SVTBits = SVT.getSizeInBits();
18900 APInt One(SVTBits, 1);
18901 unsigned NumElems = VT.getVectorNumElements();
18903 for (unsigned i=0; i !=NumElems; ++i) {
18904 SDValue Op = Amt->getOperand(i);
18905 if (Op->getOpcode() == ISD::UNDEF) {
18906 Elts.push_back(Op);
18910 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18911 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18912 uint64_t ShAmt = C.getZExtValue();
18913 if (ShAmt >= SVTBits) {
18914 Elts.push_back(DAG.getUNDEF(SVT));
18917 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18919 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18920 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18923 // Lower SHL with variable shift amount.
18924 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18925 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18927 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18928 DAG.getConstant(0x3f800000U, dl, VT));
18929 Op = DAG.getBitcast(MVT::v4f32, Op);
18930 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18931 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18934 // If possible, lower this shift as a sequence of two shifts by
18935 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18937 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18939 // Could be rewritten as:
18940 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18942 // The advantage is that the two shifts from the example would be
18943 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18944 // the vector shift into four scalar shifts plus four pairs of vector
18946 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18947 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18948 unsigned TargetOpcode = X86ISD::MOVSS;
18949 bool CanBeSimplified;
18950 // The splat value for the first packed shift (the 'X' from the example).
18951 SDValue Amt1 = Amt->getOperand(0);
18952 // The splat value for the second packed shift (the 'Y' from the example).
18953 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18954 Amt->getOperand(2);
18956 // See if it is possible to replace this node with a sequence of
18957 // two shifts followed by a MOVSS/MOVSD
18958 if (VT == MVT::v4i32) {
18959 // Check if it is legal to use a MOVSS.
18960 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18961 Amt2 == Amt->getOperand(3);
18962 if (!CanBeSimplified) {
18963 // Otherwise, check if we can still simplify this node using a MOVSD.
18964 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18965 Amt->getOperand(2) == Amt->getOperand(3);
18966 TargetOpcode = X86ISD::MOVSD;
18967 Amt2 = Amt->getOperand(2);
18970 // Do similar checks for the case where the machine value type
18972 CanBeSimplified = Amt1 == Amt->getOperand(1);
18973 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18974 CanBeSimplified = Amt2 == Amt->getOperand(i);
18976 if (!CanBeSimplified) {
18977 TargetOpcode = X86ISD::MOVSD;
18978 CanBeSimplified = true;
18979 Amt2 = Amt->getOperand(4);
18980 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18981 CanBeSimplified = Amt1 == Amt->getOperand(i);
18982 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18983 CanBeSimplified = Amt2 == Amt->getOperand(j);
18987 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18988 isa<ConstantSDNode>(Amt2)) {
18989 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18990 MVT CastVT = MVT::v4i32;
18992 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18993 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18995 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18996 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18997 if (TargetOpcode == X86ISD::MOVSD)
18998 CastVT = MVT::v2i64;
18999 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
19000 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
19001 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
19003 return DAG.getBitcast(VT, Result);
19007 // v4i32 Non Uniform Shifts.
19008 // If the shift amount is constant we can shift each lane using the SSE2
19009 // immediate shifts, else we need to zero-extend each lane to the lower i64
19010 // and shift using the SSE2 variable shifts.
19011 // The separate results can then be blended together.
19012 if (VT == MVT::v4i32) {
19013 unsigned Opc = Op.getOpcode();
19014 SDValue Amt0, Amt1, Amt2, Amt3;
19015 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
19016 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
19017 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
19018 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
19019 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
19021 // ISD::SHL is handled above but we include it here for completeness.
19024 llvm_unreachable("Unknown target vector shift node");
19026 Opc = X86ISD::VSHL;
19029 Opc = X86ISD::VSRL;
19032 Opc = X86ISD::VSRA;
19035 // The SSE2 shifts use the lower i64 as the same shift amount for
19036 // all lanes and the upper i64 is ignored. These shuffle masks
19037 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
19038 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19039 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
19040 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
19041 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
19042 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
19045 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
19046 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
19047 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
19048 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
19049 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
19050 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
19051 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
19054 if (VT == MVT::v16i8 ||
19055 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
19056 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
19057 unsigned ShiftOpcode = Op->getOpcode();
19059 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
19060 // On SSE41 targets we make use of the fact that VSELECT lowers
19061 // to PBLENDVB which selects bytes based just on the sign bit.
19062 if (Subtarget->hasSSE41()) {
19063 V0 = DAG.getBitcast(VT, V0);
19064 V1 = DAG.getBitcast(VT, V1);
19065 Sel = DAG.getBitcast(VT, Sel);
19066 return DAG.getBitcast(SelVT,
19067 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
19069 // On pre-SSE41 targets we test for the sign bit by comparing to
19070 // zero - a negative value will set all bits of the lanes to true
19071 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
19072 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
19073 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
19074 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19077 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19078 // We can safely do this using i16 shifts as we're only interested in
19079 // the 3 lower bits of each byte.
19080 Amt = DAG.getBitcast(ExtVT, Amt);
19081 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19082 Amt = DAG.getBitcast(VT, Amt);
19084 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19085 // r = VSELECT(r, shift(r, 4), a);
19087 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19088 R = SignBitSelect(VT, Amt, M, R);
19091 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19093 // r = VSELECT(r, shift(r, 2), a);
19094 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19095 R = SignBitSelect(VT, Amt, M, R);
19098 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19100 // return VSELECT(r, shift(r, 1), a);
19101 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19102 R = SignBitSelect(VT, Amt, M, R);
19106 if (Op->getOpcode() == ISD::SRA) {
19107 // For SRA we need to unpack each byte to the higher byte of a i16 vector
19108 // so we can correctly sign extend. We don't care what happens to the
19110 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19111 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19112 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19113 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19114 ALo = DAG.getBitcast(ExtVT, ALo);
19115 AHi = DAG.getBitcast(ExtVT, AHi);
19116 RLo = DAG.getBitcast(ExtVT, RLo);
19117 RHi = DAG.getBitcast(ExtVT, RHi);
19119 // r = VSELECT(r, shift(r, 4), a);
19120 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19121 DAG.getConstant(4, dl, ExtVT));
19122 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19123 DAG.getConstant(4, dl, ExtVT));
19124 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19125 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19128 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19129 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19131 // r = VSELECT(r, shift(r, 2), a);
19132 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19133 DAG.getConstant(2, dl, ExtVT));
19134 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19135 DAG.getConstant(2, dl, ExtVT));
19136 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19137 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19140 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19141 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19143 // r = VSELECT(r, shift(r, 1), a);
19144 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19145 DAG.getConstant(1, dl, ExtVT));
19146 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19147 DAG.getConstant(1, dl, ExtVT));
19148 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19149 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19151 // Logical shift the result back to the lower byte, leaving a zero upper
19153 // meaning that we can safely pack with PACKUSWB.
19155 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19157 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19158 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19162 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19163 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19164 // solution better.
19165 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19166 MVT ExtVT = MVT::v8i32;
19168 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19169 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19170 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19171 return DAG.getNode(ISD::TRUNCATE, dl, VT,
19172 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19175 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19176 MVT ExtVT = MVT::v8i32;
19177 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19178 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19179 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19180 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19181 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19182 ALo = DAG.getBitcast(ExtVT, ALo);
19183 AHi = DAG.getBitcast(ExtVT, AHi);
19184 RLo = DAG.getBitcast(ExtVT, RLo);
19185 RHi = DAG.getBitcast(ExtVT, RHi);
19186 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19187 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19188 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19189 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19190 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19193 if (VT == MVT::v8i16) {
19194 unsigned ShiftOpcode = Op->getOpcode();
19196 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19197 // On SSE41 targets we make use of the fact that VSELECT lowers
19198 // to PBLENDVB which selects bytes based just on the sign bit.
19199 if (Subtarget->hasSSE41()) {
19200 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19201 V0 = DAG.getBitcast(ExtVT, V0);
19202 V1 = DAG.getBitcast(ExtVT, V1);
19203 Sel = DAG.getBitcast(ExtVT, Sel);
19204 return DAG.getBitcast(
19205 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19207 // On pre-SSE41 targets we splat the sign bit - a negative value will
19208 // set all bits of the lanes to true and VSELECT uses that in
19209 // its OR(AND(V0,C),AND(V1,~C)) lowering.
19211 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19212 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19215 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19216 if (Subtarget->hasSSE41()) {
19217 // On SSE41 targets we need to replicate the shift mask in both
19218 // bytes for PBLENDVB.
19221 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19222 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19224 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19227 // r = VSELECT(r, shift(r, 8), a);
19228 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19229 R = SignBitSelect(Amt, M, R);
19232 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19234 // r = VSELECT(r, shift(r, 4), a);
19235 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19236 R = SignBitSelect(Amt, M, R);
19239 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19241 // r = VSELECT(r, shift(r, 2), a);
19242 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19243 R = SignBitSelect(Amt, M, R);
19246 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19248 // return VSELECT(r, shift(r, 1), a);
19249 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19250 R = SignBitSelect(Amt, M, R);
19254 // Decompose 256-bit shifts into smaller 128-bit shifts.
19255 if (VT.is256BitVector()) {
19256 unsigned NumElems = VT.getVectorNumElements();
19257 MVT EltVT = VT.getVectorElementType();
19258 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19260 // Extract the two vectors
19261 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19262 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19264 // Recreate the shift amount vectors
19265 SDValue Amt1, Amt2;
19266 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19267 // Constant shift amount
19268 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19269 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19270 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19272 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19273 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19275 // Variable shift amount
19276 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19277 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19280 // Issue new vector shifts for the smaller types
19281 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19282 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19284 // Concatenate the result back
19285 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19291 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19292 SelectionDAG &DAG) {
19293 MVT VT = Op.getSimpleValueType();
19295 SDValue R = Op.getOperand(0);
19296 SDValue Amt = Op.getOperand(1);
19298 assert(VT.isVector() && "Custom lowering only for vector rotates!");
19299 assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19300 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19302 // XOP has 128-bit vector variable + immediate rotates.
19303 // +ve/-ve Amt = rotate left/right.
19305 // Split 256-bit integers.
19306 if (VT.is256BitVector())
19307 return Lower256IntArith(Op, DAG);
19309 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19311 // Attempt to rotate by immediate.
19312 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19313 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19314 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19315 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19316 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19317 DAG.getConstant(RotateAmt, DL, MVT::i8));
19321 // Use general rotate by variable (per-element).
19322 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19325 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19326 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19327 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19328 // looks for this combo and may remove the "setcc" instruction if the "setcc"
19329 // has only one use.
19330 SDNode *N = Op.getNode();
19331 SDValue LHS = N->getOperand(0);
19332 SDValue RHS = N->getOperand(1);
19333 unsigned BaseOp = 0;
19336 switch (Op.getOpcode()) {
19337 default: llvm_unreachable("Unknown ovf instruction!");
19339 // A subtract of one will be selected as a INC. Note that INC doesn't
19340 // set CF, so we can't do this for UADDO.
19341 if (isOneConstant(RHS)) {
19342 BaseOp = X86ISD::INC;
19343 Cond = X86::COND_O;
19346 BaseOp = X86ISD::ADD;
19347 Cond = X86::COND_O;
19350 BaseOp = X86ISD::ADD;
19351 Cond = X86::COND_B;
19354 // A subtract of one will be selected as a DEC. Note that DEC doesn't
19355 // set CF, so we can't do this for USUBO.
19356 if (isOneConstant(RHS)) {
19357 BaseOp = X86ISD::DEC;
19358 Cond = X86::COND_O;
19361 BaseOp = X86ISD::SUB;
19362 Cond = X86::COND_O;
19365 BaseOp = X86ISD::SUB;
19366 Cond = X86::COND_B;
19369 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19370 Cond = X86::COND_O;
19372 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19373 if (N->getValueType(0) == MVT::i8) {
19374 BaseOp = X86ISD::UMUL8;
19375 Cond = X86::COND_O;
19378 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19380 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19383 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19384 DAG.getConstant(X86::COND_O, DL, MVT::i32),
19385 SDValue(Sum.getNode(), 2));
19387 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19391 // Also sets EFLAGS.
19392 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19393 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19396 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19397 DAG.getConstant(Cond, DL, MVT::i32),
19398 SDValue(Sum.getNode(), 1));
19400 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19403 /// Returns true if the operand type is exactly twice the native width, and
19404 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19405 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19406 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19407 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19408 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19411 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19412 else if (OpWidth == 128)
19413 return Subtarget->hasCmpxchg16b();
19418 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19419 return needsCmpXchgNb(SI->getValueOperand()->getType());
19422 // Note: this turns large loads into lock cmpxchg8b/16b.
19423 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19424 TargetLowering::AtomicExpansionKind
19425 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19426 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19427 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19428 : AtomicExpansionKind::None;
19431 TargetLowering::AtomicExpansionKind
19432 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19433 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19434 Type *MemType = AI->getType();
19436 // If the operand is too big, we must see if cmpxchg8/16b is available
19437 // and default to library calls otherwise.
19438 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19439 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19440 : AtomicExpansionKind::None;
19443 AtomicRMWInst::BinOp Op = AI->getOperation();
19446 llvm_unreachable("Unknown atomic operation");
19447 case AtomicRMWInst::Xchg:
19448 case AtomicRMWInst::Add:
19449 case AtomicRMWInst::Sub:
19450 // It's better to use xadd, xsub or xchg for these in all cases.
19451 return AtomicExpansionKind::None;
19452 case AtomicRMWInst::Or:
19453 case AtomicRMWInst::And:
19454 case AtomicRMWInst::Xor:
19455 // If the atomicrmw's result isn't actually used, we can just add a "lock"
19456 // prefix to a normal instruction for these operations.
19457 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19458 : AtomicExpansionKind::None;
19459 case AtomicRMWInst::Nand:
19460 case AtomicRMWInst::Max:
19461 case AtomicRMWInst::Min:
19462 case AtomicRMWInst::UMax:
19463 case AtomicRMWInst::UMin:
19464 // These always require a non-trivial set of data operations on x86. We must
19465 // use a cmpxchg loop.
19466 return AtomicExpansionKind::CmpXChg;
19470 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19471 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19472 // no-sse2). There isn't any reason to disable it if the target processor
19474 return Subtarget.hasSSE2() || Subtarget.is64Bit();
19478 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19479 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19480 Type *MemType = AI->getType();
19481 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19482 // there is no benefit in turning such RMWs into loads, and it is actually
19483 // harmful as it introduces a mfence.
19484 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19487 auto Builder = IRBuilder<>(AI);
19488 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19489 auto SynchScope = AI->getSynchScope();
19490 // We must restrict the ordering to avoid generating loads with Release or
19491 // ReleaseAcquire orderings.
19492 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19493 auto Ptr = AI->getPointerOperand();
19495 // Before the load we need a fence. Here is an example lifted from
19496 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19499 // x.store(1, relaxed);
19500 // r1 = y.fetch_add(0, release);
19502 // y.fetch_add(42, acquire);
19503 // r2 = x.load(relaxed);
19504 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19505 // lowered to just a load without a fence. A mfence flushes the store buffer,
19506 // making the optimization clearly correct.
19507 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19508 // otherwise, we might be able to be more aggressive on relaxed idempotent
19509 // rmw. In practice, they do not look useful, so we don't try to be
19510 // especially clever.
19511 if (SynchScope == SingleThread)
19512 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19513 // the IR level, so we must wrap it in an intrinsic.
19516 if (!hasMFENCE(*Subtarget))
19517 // FIXME: it might make sense to use a locked operation here but on a
19518 // different cache-line to prevent cache-line bouncing. In practice it
19519 // is probably a small win, and x86 processors without mfence are rare
19520 // enough that we do not bother.
19524 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19525 Builder.CreateCall(MFence, {});
19527 // Finally we can emit the atomic load.
19528 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19529 AI->getType()->getPrimitiveSizeInBits());
19530 Loaded->setAtomic(Order, SynchScope);
19531 AI->replaceAllUsesWith(Loaded);
19532 AI->eraseFromParent();
19536 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19537 SelectionDAG &DAG) {
19539 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19540 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19541 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19542 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19544 // The only fence that needs an instruction is a sequentially-consistent
19545 // cross-thread fence.
19546 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19547 if (hasMFENCE(*Subtarget))
19548 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19550 SDValue Chain = Op.getOperand(0);
19551 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19553 DAG.getRegister(X86::ESP, MVT::i32), // Base
19554 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
19555 DAG.getRegister(0, MVT::i32), // Index
19556 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
19557 DAG.getRegister(0, MVT::i32), // Segment.
19561 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19562 return SDValue(Res, 0);
19565 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19566 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19569 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19570 SelectionDAG &DAG) {
19571 MVT T = Op.getSimpleValueType();
19575 switch(T.SimpleTy) {
19576 default: llvm_unreachable("Invalid value type!");
19577 case MVT::i8: Reg = X86::AL; size = 1; break;
19578 case MVT::i16: Reg = X86::AX; size = 2; break;
19579 case MVT::i32: Reg = X86::EAX; size = 4; break;
19581 assert(Subtarget->is64Bit() && "Node not type legal!");
19582 Reg = X86::RAX; size = 8;
19585 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19586 Op.getOperand(2), SDValue());
19587 SDValue Ops[] = { cpIn.getValue(0),
19590 DAG.getTargetConstant(size, DL, MVT::i8),
19591 cpIn.getValue(1) };
19592 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19593 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19594 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19598 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19599 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19600 MVT::i32, cpOut.getValue(2));
19601 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19602 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19605 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19606 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19607 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19611 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19612 SelectionDAG &DAG) {
19613 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19614 MVT DstVT = Op.getSimpleValueType();
19616 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
19617 SrcVT == MVT::i64) {
19618 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19619 if (DstVT != MVT::f64)
19620 // This conversion needs to be expanded.
19623 SDValue Op0 = Op->getOperand(0);
19624 SmallVector<SDValue, 16> Elts;
19628 if (SrcVT.isVector()) {
19629 NumElts = SrcVT.getVectorNumElements();
19630 SVT = SrcVT.getVectorElementType();
19632 // Widen the vector in input in the case of MVT::v2i32.
19633 // Example: from MVT::v2i32 to MVT::v4i32.
19634 for (unsigned i = 0, e = NumElts; i != e; ++i)
19635 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
19636 DAG.getIntPtrConstant(i, dl)));
19638 assert(SrcVT == MVT::i64 && !Subtarget->is64Bit() &&
19639 "Unexpected source type in LowerBITCAST");
19640 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19641 DAG.getIntPtrConstant(0, dl)));
19642 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19643 DAG.getIntPtrConstant(1, dl)));
19647 // Explicitly mark the extra elements as Undef.
19648 Elts.append(NumElts, DAG.getUNDEF(SVT));
19650 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19651 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19652 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19653 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19654 DAG.getIntPtrConstant(0, dl));
19657 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19658 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19659 assert((DstVT == MVT::i64 ||
19660 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19661 "Unexpected custom BITCAST");
19662 // i64 <=> MMX conversions are Legal.
19663 if (SrcVT==MVT::i64 && DstVT.isVector())
19665 if (DstVT==MVT::i64 && SrcVT.isVector())
19667 // MMX <=> MMX conversions are Legal.
19668 if (SrcVT.isVector() && DstVT.isVector())
19670 // All other conversions need to be expanded.
19674 /// Compute the horizontal sum of bytes in V for the elements of VT.
19676 /// Requires V to be a byte vector and VT to be an integer vector type with
19677 /// wider elements than V's type. The width of the elements of VT determines
19678 /// how many bytes of V are summed horizontally to produce each element of the
19680 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19681 const X86Subtarget *Subtarget,
19682 SelectionDAG &DAG) {
19684 MVT ByteVecVT = V.getSimpleValueType();
19685 MVT EltVT = VT.getVectorElementType();
19686 int NumElts = VT.getVectorNumElements();
19687 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19688 "Expected value to have byte element type.");
19689 assert(EltVT != MVT::i8 &&
19690 "Horizontal byte sum only makes sense for wider elements!");
19691 unsigned VecSize = VT.getSizeInBits();
19692 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19694 // PSADBW instruction horizontally add all bytes and leave the result in i64
19695 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19696 if (EltVT == MVT::i64) {
19697 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19698 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19699 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19700 return DAG.getBitcast(VT, V);
19703 if (EltVT == MVT::i32) {
19704 // We unpack the low half and high half into i32s interleaved with zeros so
19705 // that we can use PSADBW to horizontally sum them. The most useful part of
19706 // this is that it lines up the results of two PSADBW instructions to be
19707 // two v2i64 vectors which concatenated are the 4 population counts. We can
19708 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19709 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19710 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19711 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19713 // Do the horizontal sums into two v2i64s.
19714 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19715 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19716 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19717 DAG.getBitcast(ByteVecVT, Low), Zeros);
19718 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19719 DAG.getBitcast(ByteVecVT, High), Zeros);
19721 // Merge them together.
19722 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19723 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19724 DAG.getBitcast(ShortVecVT, Low),
19725 DAG.getBitcast(ShortVecVT, High));
19727 return DAG.getBitcast(VT, V);
19730 // The only element type left is i16.
19731 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19733 // To obtain pop count for each i16 element starting from the pop count for
19734 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19735 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19736 // directly supported.
19737 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19738 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19739 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19740 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19741 DAG.getBitcast(ByteVecVT, V));
19742 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19745 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19746 const X86Subtarget *Subtarget,
19747 SelectionDAG &DAG) {
19748 MVT VT = Op.getSimpleValueType();
19749 MVT EltVT = VT.getVectorElementType();
19750 unsigned VecSize = VT.getSizeInBits();
19752 // Implement a lookup table in register by using an algorithm based on:
19753 // http://wm.ite.pl/articles/sse-popcount.html
19755 // The general idea is that every lower byte nibble in the input vector is an
19756 // index into a in-register pre-computed pop count table. We then split up the
19757 // input vector in two new ones: (1) a vector with only the shifted-right
19758 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19759 // masked out higher ones) for each byte. PSHUB is used separately with both
19760 // to index the in-register table. Next, both are added and the result is a
19761 // i8 vector where each element contains the pop count for input byte.
19763 // To obtain the pop count for elements != i8, we follow up with the same
19764 // approach and use additional tricks as described below.
19766 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19767 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19768 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19769 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19771 int NumByteElts = VecSize / 8;
19772 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19773 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19774 SmallVector<SDValue, 16> LUTVec;
19775 for (int i = 0; i < NumByteElts; ++i)
19776 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19777 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19778 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19779 DAG.getConstant(0x0F, DL, MVT::i8));
19780 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19783 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19784 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19785 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19788 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19790 // The input vector is used as the shuffle mask that index elements into the
19791 // LUT. After counting low and high nibbles, add the vector to obtain the
19792 // final pop count per i8 element.
19793 SDValue HighPopCnt =
19794 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19795 SDValue LowPopCnt =
19796 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19797 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19799 if (EltVT == MVT::i8)
19802 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19805 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19806 const X86Subtarget *Subtarget,
19807 SelectionDAG &DAG) {
19808 MVT VT = Op.getSimpleValueType();
19809 assert(VT.is128BitVector() &&
19810 "Only 128-bit vector bitmath lowering supported.");
19812 int VecSize = VT.getSizeInBits();
19813 MVT EltVT = VT.getVectorElementType();
19814 int Len = EltVT.getSizeInBits();
19816 // This is the vectorized version of the "best" algorithm from
19817 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19818 // with a minor tweak to use a series of adds + shifts instead of vector
19819 // multiplications. Implemented for all integer vector types. We only use
19820 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19821 // much faster, even faster than using native popcnt instructions.
19823 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19824 MVT VT = V.getSimpleValueType();
19825 SmallVector<SDValue, 32> Shifters(
19826 VT.getVectorNumElements(),
19827 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19828 return DAG.getNode(OpCode, DL, VT, V,
19829 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19831 auto GetMask = [&](SDValue V, APInt Mask) {
19832 MVT VT = V.getSimpleValueType();
19833 SmallVector<SDValue, 32> Masks(
19834 VT.getVectorNumElements(),
19835 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19836 return DAG.getNode(ISD::AND, DL, VT, V,
19837 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19840 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19841 // x86, so set the SRL type to have elements at least i16 wide. This is
19842 // correct because all of our SRLs are followed immediately by a mask anyways
19843 // that handles any bits that sneak into the high bits of the byte elements.
19844 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19848 // v = v - ((v >> 1) & 0x55555555...)
19850 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19851 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19852 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19854 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19855 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19856 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19857 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19858 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19860 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19861 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19862 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19863 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19865 // At this point, V contains the byte-wise population count, and we are
19866 // merely doing a horizontal sum if necessary to get the wider element
19868 if (EltVT == MVT::i8)
19871 return LowerHorizontalByteSum(
19872 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19876 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19877 SelectionDAG &DAG) {
19878 MVT VT = Op.getSimpleValueType();
19879 // FIXME: Need to add AVX-512 support here!
19880 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19881 "Unknown CTPOP type to handle");
19882 SDLoc DL(Op.getNode());
19883 SDValue Op0 = Op.getOperand(0);
19885 if (!Subtarget->hasSSSE3()) {
19886 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19887 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19888 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19891 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19892 unsigned NumElems = VT.getVectorNumElements();
19894 // Extract each 128-bit vector, compute pop count and concat the result.
19895 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19896 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19898 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19899 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19900 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19903 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19906 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19907 SelectionDAG &DAG) {
19908 assert(Op.getSimpleValueType().isVector() &&
19909 "We only do custom lowering for vector population count.");
19910 return LowerVectorCTPOP(Op, Subtarget, DAG);
19913 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19914 SDNode *Node = Op.getNode();
19916 EVT T = Node->getValueType(0);
19917 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19918 DAG.getConstant(0, dl, T), Node->getOperand(2));
19919 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19920 cast<AtomicSDNode>(Node)->getMemoryVT(),
19921 Node->getOperand(0),
19922 Node->getOperand(1), negOp,
19923 cast<AtomicSDNode>(Node)->getMemOperand(),
19924 cast<AtomicSDNode>(Node)->getOrdering(),
19925 cast<AtomicSDNode>(Node)->getSynchScope());
19928 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19929 SDNode *Node = Op.getNode();
19931 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19933 // Convert seq_cst store -> xchg
19934 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19935 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19936 // (The only way to get a 16-byte store is cmpxchg16b)
19937 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19938 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19939 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19940 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19941 cast<AtomicSDNode>(Node)->getMemoryVT(),
19942 Node->getOperand(0),
19943 Node->getOperand(1), Node->getOperand(2),
19944 cast<AtomicSDNode>(Node)->getMemOperand(),
19945 cast<AtomicSDNode>(Node)->getOrdering(),
19946 cast<AtomicSDNode>(Node)->getSynchScope());
19947 return Swap.getValue(1);
19949 // Other atomic stores have a simple pattern.
19953 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19954 MVT VT = Op.getNode()->getSimpleValueType(0);
19956 // Let legalize expand this if it isn't a legal type yet.
19957 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19960 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19963 bool ExtraOp = false;
19964 switch (Op.getOpcode()) {
19965 default: llvm_unreachable("Invalid code");
19966 case ISD::ADDC: Opc = X86ISD::ADD; break;
19967 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19968 case ISD::SUBC: Opc = X86ISD::SUB; break;
19969 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19973 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19975 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19976 Op.getOperand(1), Op.getOperand(2));
19979 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19980 SelectionDAG &DAG) {
19981 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19983 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19984 // which returns the values as { float, float } (in XMM0) or
19985 // { double, double } (which is returned in XMM0, XMM1).
19987 SDValue Arg = Op.getOperand(0);
19988 EVT ArgVT = Arg.getValueType();
19989 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19991 TargetLowering::ArgListTy Args;
19992 TargetLowering::ArgListEntry Entry;
19996 Entry.isSExt = false;
19997 Entry.isZExt = false;
19998 Args.push_back(Entry);
20000 bool isF64 = ArgVT == MVT::f64;
20001 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
20002 // the small struct {f32, f32} is returned in (eax, edx). For f64,
20003 // the results are returned via SRet in memory.
20004 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
20005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20007 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
20009 Type *RetTy = isF64
20010 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
20011 : (Type*)VectorType::get(ArgTy, 4);
20013 TargetLowering::CallLoweringInfo CLI(DAG);
20014 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
20015 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
20017 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
20020 // Returned in xmm0 and xmm1.
20021 return CallResult.first;
20023 // Returned in bits 0:31 and 32:64 xmm0.
20024 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20025 CallResult.first, DAG.getIntPtrConstant(0, dl));
20026 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20027 CallResult.first, DAG.getIntPtrConstant(1, dl));
20028 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
20029 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
20032 /// Widen a vector input to a vector of NVT. The
20033 /// input vector must have the same element type as NVT.
20034 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
20035 bool FillWithZeroes = false) {
20036 // Check if InOp already has the right width.
20037 MVT InVT = InOp.getSimpleValueType();
20041 if (InOp.isUndef())
20042 return DAG.getUNDEF(NVT);
20044 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
20045 "input and widen element type must match");
20047 unsigned InNumElts = InVT.getVectorNumElements();
20048 unsigned WidenNumElts = NVT.getVectorNumElements();
20049 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
20050 "Unexpected request for vector widening");
20052 EVT EltVT = NVT.getVectorElementType();
20055 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
20056 InOp.getNumOperands() == 2) {
20057 SDValue N1 = InOp.getOperand(1);
20058 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
20060 InOp = InOp.getOperand(0);
20061 InVT = InOp.getSimpleValueType();
20062 InNumElts = InVT.getVectorNumElements();
20065 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
20066 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
20067 SmallVector<SDValue, 16> Ops;
20068 for (unsigned i = 0; i < InNumElts; ++i)
20069 Ops.push_back(InOp.getOperand(i));
20071 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
20072 DAG.getUNDEF(EltVT);
20073 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
20074 Ops.push_back(FillVal);
20075 return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
20077 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
20079 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
20080 InOp, DAG.getIntPtrConstant(0, dl));
20083 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
20084 SelectionDAG &DAG) {
20085 assert(Subtarget->hasAVX512() &&
20086 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20088 // X86 scatter kills mask register, so its type should be added to
20089 // the list of return values.
20090 // If the "scatter" has 2 return values, it is already handled.
20091 if (Op.getNode()->getNumValues() == 2)
20094 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20095 SDValue Src = N->getValue();
20096 MVT VT = Src.getSimpleValueType();
20097 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20100 SDValue NewScatter;
20101 SDValue Index = N->getIndex();
20102 SDValue Mask = N->getMask();
20103 SDValue Chain = N->getChain();
20104 SDValue BasePtr = N->getBasePtr();
20105 MVT MemVT = N->getMemoryVT().getSimpleVT();
20106 MVT IndexVT = Index.getSimpleValueType();
20107 MVT MaskVT = Mask.getSimpleValueType();
20109 if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20110 // The v2i32 value was promoted to v2i64.
20111 // Now we "redo" the type legalizer's work and widen the original
20112 // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20114 assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20115 "Unexpected memory type");
20116 int ShuffleMask[] = {0, 2, -1, -1};
20117 Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20118 DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20119 // Now we have 4 elements instead of 2.
20120 // Expand the index.
20121 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20122 Index = ExtendToType(Index, NewIndexVT, DAG);
20124 // Expand the mask with zeroes
20125 // Mask may be <2 x i64> or <2 x i1> at this moment
20126 assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20127 "Unexpected mask type");
20128 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20129 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20133 unsigned NumElts = VT.getVectorNumElements();
20134 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20135 !Index.getSimpleValueType().is512BitVector()) {
20136 // AVX512F supports only 512-bit vectors. Or data or index should
20137 // be 512 bit wide. If now the both index and data are 256-bit, but
20138 // the vector contains 8 elements, we just sign-extend the index
20139 if (IndexVT == MVT::v8i32)
20140 // Just extend index
20141 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20143 // The minimal number of elts in scatter is 8
20146 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20147 // Use original index here, do not modify the index twice
20148 Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20149 if (IndexVT.getScalarType() == MVT::i32)
20150 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20153 // At this point we have promoted mask operand
20154 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20155 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20156 // Use the original mask here, do not modify the mask twice
20157 Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20159 // The value that should be stored
20160 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20161 Src = ExtendToType(Src, NewVT, DAG);
20164 // If the mask is "wide" at this point - truncate it to i1 vector
20165 MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20166 Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20168 // The mask is killed by scatter, add it to the values
20169 SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20170 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20171 NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20172 N->getMemOperand());
20173 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20174 return SDValue(NewScatter.getNode(), 0);
20177 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20178 SelectionDAG &DAG) {
20180 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20181 MVT VT = Op.getSimpleValueType();
20182 SDValue Mask = N->getMask();
20185 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20186 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20187 // This operation is legal for targets with VLX, but without
20188 // VLX the vector should be widened to 512 bit
20189 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20190 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20191 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20192 SDValue Src0 = N->getSrc0();
20193 Src0 = ExtendToType(Src0, WideDataVT, DAG);
20194 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20195 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20196 N->getBasePtr(), Mask, Src0,
20197 N->getMemoryVT(), N->getMemOperand(),
20198 N->getExtensionType());
20200 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20201 NewLoad.getValue(0),
20202 DAG.getIntPtrConstant(0, dl));
20203 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20204 return DAG.getMergeValues(RetOps, dl);
20209 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20210 SelectionDAG &DAG) {
20211 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20212 SDValue DataToStore = N->getValue();
20213 MVT VT = DataToStore.getSimpleValueType();
20214 SDValue Mask = N->getMask();
20217 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20218 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20219 // This operation is legal for targets with VLX, but without
20220 // VLX the vector should be widened to 512 bit
20221 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20222 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20223 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20224 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20225 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20226 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20227 Mask, N->getMemoryVT(), N->getMemOperand(),
20228 N->isTruncatingStore());
20233 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20234 SelectionDAG &DAG) {
20235 assert(Subtarget->hasAVX512() &&
20236 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20238 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20240 MVT VT = Op.getSimpleValueType();
20241 SDValue Index = N->getIndex();
20242 SDValue Mask = N->getMask();
20243 SDValue Src0 = N->getValue();
20244 MVT IndexVT = Index.getSimpleValueType();
20245 MVT MaskVT = Mask.getSimpleValueType();
20247 unsigned NumElts = VT.getVectorNumElements();
20248 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20250 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20251 !Index.getSimpleValueType().is512BitVector()) {
20252 // AVX512F supports only 512-bit vectors. Or data or index should
20253 // be 512 bit wide. If now the both index and data are 256-bit, but
20254 // the vector contains 8 elements, we just sign-extend the index
20255 if (NumElts == 8) {
20256 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20257 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
20258 N->getOperand(3), Index };
20259 DAG.UpdateNodeOperands(N, Ops);
20263 // Minimal number of elements in Gather
20266 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20267 Index = ExtendToType(Index, NewIndexVT, DAG);
20268 if (IndexVT.getScalarType() == MVT::i32)
20269 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20272 MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20273 // At this point we have promoted mask operand
20274 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20275 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20276 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20277 Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20279 // The pass-thru value
20280 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20281 Src0 = ExtendToType(Src0, NewVT, DAG);
20283 SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20284 SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20285 N->getMemoryVT(), dl, Ops,
20286 N->getMemOperand());
20287 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20288 NewGather.getValue(0),
20289 DAG.getIntPtrConstant(0, dl));
20290 SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20291 return DAG.getMergeValues(RetOps, dl);
20296 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20297 SelectionDAG &DAG) const {
20298 // TODO: Eventually, the lowering of these nodes should be informed by or
20299 // deferred to the GC strategy for the function in which they appear. For
20300 // now, however, they must be lowered to something. Since they are logically
20301 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20302 // require special handling for these nodes), lower them as literal NOOPs for
20304 SmallVector<SDValue, 2> Ops;
20306 Ops.push_back(Op.getOperand(0));
20307 if (Op->getGluedNode())
20308 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20311 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20312 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20317 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20318 SelectionDAG &DAG) const {
20319 // TODO: Eventually, the lowering of these nodes should be informed by or
20320 // deferred to the GC strategy for the function in which they appear. For
20321 // now, however, they must be lowered to something. Since they are logically
20322 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20323 // require special handling for these nodes), lower them as literal NOOPs for
20325 SmallVector<SDValue, 2> Ops;
20327 Ops.push_back(Op.getOperand(0));
20328 if (Op->getGluedNode())
20329 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20332 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20333 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20338 /// LowerOperation - Provide custom lowering hooks for some operations.
20340 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20341 switch (Op.getOpcode()) {
20342 default: llvm_unreachable("Should not custom lower this!");
20343 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20344 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20345 return LowerCMP_SWAP(Op, Subtarget, DAG);
20346 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
20347 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
20348 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
20349 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
20350 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20351 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
20352 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
20353 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20354 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
20355 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20356 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20357 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
20358 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
20359 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
20360 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
20361 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
20362 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
20363 case ISD::SHL_PARTS:
20364 case ISD::SRA_PARTS:
20365 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
20366 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
20367 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
20368 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
20369 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
20370 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20371 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
20372 case ISD::SIGN_EXTEND_VECTOR_INREG:
20373 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20374 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
20375 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
20376 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
20377 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
20379 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
20380 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
20381 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
20382 case ISD::SETCC: return LowerSETCC(Op, DAG);
20383 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
20384 case ISD::SELECT: return LowerSELECT(Op, DAG);
20385 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
20386 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
20387 case ISD::VASTART: return LowerVASTART(Op, DAG);
20388 case ISD::VAARG: return LowerVAARG(Op, DAG);
20389 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
20390 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20391 case ISD::INTRINSIC_VOID:
20392 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20393 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
20394 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
20395 case ISD::FRAME_TO_ARGS_OFFSET:
20396 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20397 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20398 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
20399 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
20400 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
20401 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
20402 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
20403 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
20404 case ISD::CTLZ: return LowerCTLZ(Op, Subtarget, DAG);
20405 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20407 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
20408 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
20409 case ISD::UMUL_LOHI:
20410 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
20411 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
20414 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
20420 case ISD::UMULO: return LowerXALUO(Op, DAG);
20421 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20422 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
20426 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20427 case ISD::ADD: return LowerADD(Op, DAG);
20428 case ISD::SUB: return LowerSUB(Op, DAG);
20432 case ISD::UMIN: return LowerMINMAX(Op, DAG);
20433 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
20434 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
20435 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
20436 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
20437 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
20438 case ISD::GC_TRANSITION_START:
20439 return LowerGC_TRANSITION_START(Op, DAG);
20440 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
20444 /// ReplaceNodeResults - Replace a node with an illegal result type
20445 /// with a new node built out of custom code.
20446 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20447 SmallVectorImpl<SDValue>&Results,
20448 SelectionDAG &DAG) const {
20450 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20451 switch (N->getOpcode()) {
20453 llvm_unreachable("Do not know how to custom type legalize this operation!");
20454 case X86ISD::AVG: {
20455 // Legalize types for X86ISD::AVG by expanding vectors.
20456 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20458 auto InVT = N->getValueType(0);
20459 auto InVTSize = InVT.getSizeInBits();
20460 const unsigned RegSize =
20461 (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20462 assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20463 "512-bit vector requires AVX512");
20464 assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20465 "256-bit vector requires AVX2");
20467 auto ElemVT = InVT.getVectorElementType();
20468 auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20469 RegSize / ElemVT.getSizeInBits());
20470 assert(RegSize % InVT.getSizeInBits() == 0);
20471 unsigned NumConcat = RegSize / InVT.getSizeInBits();
20473 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20474 Ops[0] = N->getOperand(0);
20475 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20476 Ops[0] = N->getOperand(1);
20477 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20479 SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20480 Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20481 DAG.getIntPtrConstant(0, dl)));
20484 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20485 case X86ISD::FMINC:
20487 case X86ISD::FMAXC:
20488 case X86ISD::FMAX: {
20489 EVT VT = N->getValueType(0);
20490 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20491 SDValue UNDEF = DAG.getUNDEF(VT);
20492 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20493 N->getOperand(0), UNDEF);
20494 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20495 N->getOperand(1), UNDEF);
20496 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20499 case ISD::SIGN_EXTEND_INREG:
20504 // We don't want to expand or promote these.
20511 case ISD::UDIVREM: {
20512 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20513 Results.push_back(V);
20516 case ISD::FP_TO_SINT:
20517 case ISD::FP_TO_UINT: {
20518 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20520 std::pair<SDValue,SDValue> Vals =
20521 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20522 SDValue FIST = Vals.first, StackSlot = Vals.second;
20523 if (FIST.getNode()) {
20524 EVT VT = N->getValueType(0);
20525 // Return a load from the stack slot.
20526 if (StackSlot.getNode())
20527 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20528 MachinePointerInfo(),
20529 false, false, false, 0));
20531 Results.push_back(FIST);
20535 case ISD::UINT_TO_FP: {
20536 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20537 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20538 N->getValueType(0) != MVT::v2f32)
20540 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20542 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20544 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20545 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20546 DAG.getBitcast(MVT::v2i64, VBias));
20547 Or = DAG.getBitcast(MVT::v2f64, Or);
20548 // TODO: Are there any fast-math-flags to propagate here?
20549 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20550 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20553 case ISD::FP_ROUND: {
20554 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20556 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20557 Results.push_back(V);
20560 case ISD::FP_EXTEND: {
20561 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20562 // No other ValueType for FP_EXTEND should reach this point.
20563 assert(N->getValueType(0) == MVT::v2f32 &&
20564 "Do not know how to legalize this Node");
20567 case ISD::INTRINSIC_W_CHAIN: {
20568 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20570 default : llvm_unreachable("Do not know how to custom type "
20571 "legalize this intrinsic operation!");
20572 case Intrinsic::x86_rdtsc:
20573 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20575 case Intrinsic::x86_rdtscp:
20576 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20578 case Intrinsic::x86_rdpmc:
20579 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20582 case ISD::INTRINSIC_WO_CHAIN: {
20583 if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20584 Results.push_back(V);
20587 case ISD::READCYCLECOUNTER: {
20588 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20591 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20592 EVT T = N->getValueType(0);
20593 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20594 bool Regs64bit = T == MVT::i128;
20595 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20596 SDValue cpInL, cpInH;
20597 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20598 DAG.getConstant(0, dl, HalfT));
20599 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20600 DAG.getConstant(1, dl, HalfT));
20601 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20602 Regs64bit ? X86::RAX : X86::EAX,
20604 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20605 Regs64bit ? X86::RDX : X86::EDX,
20606 cpInH, cpInL.getValue(1));
20607 SDValue swapInL, swapInH;
20608 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20609 DAG.getConstant(0, dl, HalfT));
20610 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20611 DAG.getConstant(1, dl, HalfT));
20612 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20613 Regs64bit ? X86::RBX : X86::EBX,
20614 swapInL, cpInH.getValue(1));
20615 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20616 Regs64bit ? X86::RCX : X86::ECX,
20617 swapInH, swapInL.getValue(1));
20618 SDValue Ops[] = { swapInH.getValue(0),
20620 swapInH.getValue(1) };
20621 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20622 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20623 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20624 X86ISD::LCMPXCHG8_DAG;
20625 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20626 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20627 Regs64bit ? X86::RAX : X86::EAX,
20628 HalfT, Result.getValue(1));
20629 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20630 Regs64bit ? X86::RDX : X86::EDX,
20631 HalfT, cpOutL.getValue(2));
20632 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20634 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20635 MVT::i32, cpOutH.getValue(2));
20637 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20638 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20639 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20641 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20642 Results.push_back(Success);
20643 Results.push_back(EFLAGS.getValue(1));
20646 case ISD::ATOMIC_SWAP:
20647 case ISD::ATOMIC_LOAD_ADD:
20648 case ISD::ATOMIC_LOAD_SUB:
20649 case ISD::ATOMIC_LOAD_AND:
20650 case ISD::ATOMIC_LOAD_OR:
20651 case ISD::ATOMIC_LOAD_XOR:
20652 case ISD::ATOMIC_LOAD_NAND:
20653 case ISD::ATOMIC_LOAD_MIN:
20654 case ISD::ATOMIC_LOAD_MAX:
20655 case ISD::ATOMIC_LOAD_UMIN:
20656 case ISD::ATOMIC_LOAD_UMAX:
20657 case ISD::ATOMIC_LOAD: {
20658 // Delegate to generic TypeLegalization. Situations we can really handle
20659 // should have already been dealt with by AtomicExpandPass.cpp.
20662 case ISD::BITCAST: {
20663 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20664 EVT DstVT = N->getValueType(0);
20665 EVT SrcVT = N->getOperand(0)->getValueType(0);
20667 if (SrcVT != MVT::f64 ||
20668 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20671 unsigned NumElts = DstVT.getVectorNumElements();
20672 EVT SVT = DstVT.getVectorElementType();
20673 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20674 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20675 MVT::v2f64, N->getOperand(0));
20676 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20678 if (ExperimentalVectorWideningLegalization) {
20679 // If we are legalizing vectors by widening, we already have the desired
20680 // legal vector type, just return it.
20681 Results.push_back(ToVecInt);
20685 SmallVector<SDValue, 8> Elts;
20686 for (unsigned i = 0, e = NumElts; i != e; ++i)
20687 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20688 ToVecInt, DAG.getIntPtrConstant(i, dl)));
20690 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20695 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20696 switch ((X86ISD::NodeType)Opcode) {
20697 case X86ISD::FIRST_NUMBER: break;
20698 case X86ISD::BSF: return "X86ISD::BSF";
20699 case X86ISD::BSR: return "X86ISD::BSR";
20700 case X86ISD::SHLD: return "X86ISD::SHLD";
20701 case X86ISD::SHRD: return "X86ISD::SHRD";
20702 case X86ISD::FAND: return "X86ISD::FAND";
20703 case X86ISD::FANDN: return "X86ISD::FANDN";
20704 case X86ISD::FOR: return "X86ISD::FOR";
20705 case X86ISD::FXOR: return "X86ISD::FXOR";
20706 case X86ISD::FILD: return "X86ISD::FILD";
20707 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
20708 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20709 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20710 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20711 case X86ISD::FLD: return "X86ISD::FLD";
20712 case X86ISD::FST: return "X86ISD::FST";
20713 case X86ISD::CALL: return "X86ISD::CALL";
20714 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
20715 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
20716 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
20717 case X86ISD::BT: return "X86ISD::BT";
20718 case X86ISD::CMP: return "X86ISD::CMP";
20719 case X86ISD::COMI: return "X86ISD::COMI";
20720 case X86ISD::UCOMI: return "X86ISD::UCOMI";
20721 case X86ISD::CMPM: return "X86ISD::CMPM";
20722 case X86ISD::CMPMU: return "X86ISD::CMPMU";
20723 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
20724 case X86ISD::SETCC: return "X86ISD::SETCC";
20725 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
20726 case X86ISD::FSETCC: return "X86ISD::FSETCC";
20727 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
20728 case X86ISD::CMOV: return "X86ISD::CMOV";
20729 case X86ISD::BRCOND: return "X86ISD::BRCOND";
20730 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
20731 case X86ISD::IRET: return "X86ISD::IRET";
20732 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
20733 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
20734 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
20735 case X86ISD::Wrapper: return "X86ISD::Wrapper";
20736 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
20737 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
20738 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
20739 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
20740 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
20741 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
20742 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
20743 case X86ISD::PINSRB: return "X86ISD::PINSRB";
20744 case X86ISD::PINSRW: return "X86ISD::PINSRW";
20745 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
20746 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
20747 case X86ISD::ANDNP: return "X86ISD::ANDNP";
20748 case X86ISD::PSIGN: return "X86ISD::PSIGN";
20749 case X86ISD::BLENDI: return "X86ISD::BLENDI";
20750 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
20751 case X86ISD::ADDUS: return "X86ISD::ADDUS";
20752 case X86ISD::SUBUS: return "X86ISD::SUBUS";
20753 case X86ISD::HADD: return "X86ISD::HADD";
20754 case X86ISD::HSUB: return "X86ISD::HSUB";
20755 case X86ISD::FHADD: return "X86ISD::FHADD";
20756 case X86ISD::FHSUB: return "X86ISD::FHSUB";
20757 case X86ISD::ABS: return "X86ISD::ABS";
20758 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
20759 case X86ISD::FMAX: return "X86ISD::FMAX";
20760 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
20761 case X86ISD::FMIN: return "X86ISD::FMIN";
20762 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
20763 case X86ISD::FMAXC: return "X86ISD::FMAXC";
20764 case X86ISD::FMINC: return "X86ISD::FMINC";
20765 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
20766 case X86ISD::FRCP: return "X86ISD::FRCP";
20767 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
20768 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
20769 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
20770 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
20771 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
20772 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
20773 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
20774 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
20775 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
20776 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
20777 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
20778 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
20779 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
20780 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
20781 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
20782 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
20783 case X86ISD::VZEXT: return "X86ISD::VZEXT";
20784 case X86ISD::VSEXT: return "X86ISD::VSEXT";
20785 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
20786 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
20787 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
20788 case X86ISD::VINSERT: return "X86ISD::VINSERT";
20789 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
20790 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
20791 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
20792 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
20793 case X86ISD::CVT2MASK: return "X86ISD::CVT2MASK";
20794 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
20795 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
20796 case X86ISD::VSHL: return "X86ISD::VSHL";
20797 case X86ISD::VSRL: return "X86ISD::VSRL";
20798 case X86ISD::VSRA: return "X86ISD::VSRA";
20799 case X86ISD::VSHLI: return "X86ISD::VSHLI";
20800 case X86ISD::VSRLI: return "X86ISD::VSRLI";
20801 case X86ISD::VSRAI: return "X86ISD::VSRAI";
20802 case X86ISD::VROTLI: return "X86ISD::VROTLI";
20803 case X86ISD::VROTRI: return "X86ISD::VROTRI";
20804 case X86ISD::CMPP: return "X86ISD::CMPP";
20805 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
20806 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
20807 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
20808 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
20809 case X86ISD::ADD: return "X86ISD::ADD";
20810 case X86ISD::SUB: return "X86ISD::SUB";
20811 case X86ISD::ADC: return "X86ISD::ADC";
20812 case X86ISD::SBB: return "X86ISD::SBB";
20813 case X86ISD::SMUL: return "X86ISD::SMUL";
20814 case X86ISD::UMUL: return "X86ISD::UMUL";
20815 case X86ISD::SMUL8: return "X86ISD::SMUL8";
20816 case X86ISD::UMUL8: return "X86ISD::UMUL8";
20817 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20818 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20819 case X86ISD::INC: return "X86ISD::INC";
20820 case X86ISD::DEC: return "X86ISD::DEC";
20821 case X86ISD::OR: return "X86ISD::OR";
20822 case X86ISD::XOR: return "X86ISD::XOR";
20823 case X86ISD::AND: return "X86ISD::AND";
20824 case X86ISD::BEXTR: return "X86ISD::BEXTR";
20825 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
20826 case X86ISD::PTEST: return "X86ISD::PTEST";
20827 case X86ISD::TESTP: return "X86ISD::TESTP";
20828 case X86ISD::TESTM: return "X86ISD::TESTM";
20829 case X86ISD::TESTNM: return "X86ISD::TESTNM";
20830 case X86ISD::KORTEST: return "X86ISD::KORTEST";
20831 case X86ISD::KTEST: return "X86ISD::KTEST";
20832 case X86ISD::PACKSS: return "X86ISD::PACKSS";
20833 case X86ISD::PACKUS: return "X86ISD::PACKUS";
20834 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
20835 case X86ISD::VALIGN: return "X86ISD::VALIGN";
20836 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
20837 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
20838 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
20839 case X86ISD::SHUFP: return "X86ISD::SHUFP";
20840 case X86ISD::SHUF128: return "X86ISD::SHUF128";
20841 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
20842 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
20843 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
20844 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
20845 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
20846 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
20847 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
20848 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
20849 case X86ISD::MOVSD: return "X86ISD::MOVSD";
20850 case X86ISD::MOVSS: return "X86ISD::MOVSS";
20851 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
20852 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
20853 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
20854 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
20855 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
20856 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
20857 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
20858 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
20859 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
20860 case X86ISD::VPERMV: return "X86ISD::VPERMV";
20861 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
20862 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
20863 case X86ISD::VPERMI: return "X86ISD::VPERMI";
20864 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
20865 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
20866 case X86ISD::VRANGE: return "X86ISD::VRANGE";
20867 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
20868 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
20869 case X86ISD::PSADBW: return "X86ISD::PSADBW";
20870 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
20871 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20872 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
20873 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
20874 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
20875 case X86ISD::MFENCE: return "X86ISD::MFENCE";
20876 case X86ISD::SFENCE: return "X86ISD::SFENCE";
20877 case X86ISD::LFENCE: return "X86ISD::LFENCE";
20878 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
20879 case X86ISD::SAHF: return "X86ISD::SAHF";
20880 case X86ISD::RDRAND: return "X86ISD::RDRAND";
20881 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20882 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20883 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20884 case X86ISD::VPROT: return "X86ISD::VPROT";
20885 case X86ISD::VPROTI: return "X86ISD::VPROTI";
20886 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20887 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20888 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20889 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20890 case X86ISD::FMADD: return "X86ISD::FMADD";
20891 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20892 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20893 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20894 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20895 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20896 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20897 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20898 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20899 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20900 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20901 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20902 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20903 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20904 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20905 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20906 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20907 case X86ISD::XTEST: return "X86ISD::XTEST";
20908 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20909 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20910 case X86ISD::SELECT: return "X86ISD::SELECT";
20911 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20912 case X86ISD::RCP28: return "X86ISD::RCP28";
20913 case X86ISD::EXP2: return "X86ISD::EXP2";
20914 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20915 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20916 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20917 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20918 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20919 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20920 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20921 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20922 case X86ISD::ADDS: return "X86ISD::ADDS";
20923 case X86ISD::SUBS: return "X86ISD::SUBS";
20924 case X86ISD::AVG: return "X86ISD::AVG";
20925 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20926 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20927 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20928 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20929 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20930 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20931 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
20936 // isLegalAddressingMode - Return true if the addressing mode represented
20937 // by AM is legal for this target, for a load/store of the specified type.
20938 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20939 const AddrMode &AM, Type *Ty,
20940 unsigned AS) const {
20941 // X86 supports extremely general addressing modes.
20942 CodeModel::Model M = getTargetMachine().getCodeModel();
20943 Reloc::Model R = getTargetMachine().getRelocationModel();
20945 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20946 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20951 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20953 // If a reference to this global requires an extra load, we can't fold it.
20954 if (isGlobalStubReference(GVFlags))
20957 // If BaseGV requires a register for the PIC base, we cannot also have a
20958 // BaseReg specified.
20959 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20962 // If lower 4G is not available, then we must use rip-relative addressing.
20963 if ((M != CodeModel::Small || R != Reloc::Static) &&
20964 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20968 switch (AM.Scale) {
20974 // These scales always work.
20979 // These scales are formed with basereg+scalereg. Only accept if there is
20984 default: // Other stuff never works.
20991 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20992 unsigned Bits = Ty->getScalarSizeInBits();
20994 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20995 // particularly cheaper than those without.
20999 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
21000 // variable shifts just as cheap as scalar ones.
21001 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
21004 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
21005 // fully general vector.
21009 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
21010 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
21012 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
21013 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
21014 return NumBits1 > NumBits2;
21017 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
21018 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
21021 if (!isTypeLegal(EVT::getEVT(Ty1)))
21024 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
21026 // Assuming the caller doesn't have a zeroext or signext return parameter,
21027 // truncation all the way down to i1 is valid.
21031 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
21032 return isInt<32>(Imm);
21035 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
21036 // Can also use sub to handle negated immediates.
21037 return isInt<32>(Imm);
21040 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
21041 if (!VT1.isInteger() || !VT2.isInteger())
21043 unsigned NumBits1 = VT1.getSizeInBits();
21044 unsigned NumBits2 = VT2.getSizeInBits();
21045 return NumBits1 > NumBits2;
21048 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
21049 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21050 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
21053 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
21054 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21055 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
21058 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
21059 EVT VT1 = Val.getValueType();
21060 if (isZExtFree(VT1, VT2))
21063 if (Val.getOpcode() != ISD::LOAD)
21066 if (!VT1.isSimple() || !VT1.isInteger() ||
21067 !VT2.isSimple() || !VT2.isInteger())
21070 switch (VT1.getSimpleVT().SimpleTy) {
21075 // X86 has 8, 16, and 32-bit zero-extending loads.
21082 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
21085 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
21086 if (!Subtarget->hasAnyFMA())
21089 VT = VT.getScalarType();
21091 if (!VT.isSimple())
21094 switch (VT.getSimpleVT().SimpleTy) {
21105 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21106 // i16 instructions are longer (0x66 prefix) and potentially slower.
21107 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21110 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21111 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21112 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21113 /// are assumed to be legal.
21115 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21117 if (!VT.isSimple())
21120 // Not for i1 vectors
21121 if (VT.getSimpleVT().getScalarType() == MVT::i1)
21124 // Very little shuffling can be done for 64-bit vectors right now.
21125 if (VT.getSimpleVT().getSizeInBits() == 64)
21128 // We only care that the types being shuffled are legal. The lowering can
21129 // handle any possible shuffle mask that results.
21130 return isTypeLegal(VT.getSimpleVT());
21134 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21136 // Just delegate to the generic legality, clear masks aren't special.
21137 return isShuffleMaskLegal(Mask, VT);
21140 //===----------------------------------------------------------------------===//
21141 // X86 Scheduler Hooks
21142 //===----------------------------------------------------------------------===//
21144 /// Utility function to emit xbegin specifying the start of an RTM region.
21145 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21146 const TargetInstrInfo *TII) {
21147 DebugLoc DL = MI->getDebugLoc();
21149 const BasicBlock *BB = MBB->getBasicBlock();
21150 MachineFunction::iterator I = ++MBB->getIterator();
21152 // For the v = xbegin(), we generate
21163 MachineBasicBlock *thisMBB = MBB;
21164 MachineFunction *MF = MBB->getParent();
21165 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21166 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21167 MF->insert(I, mainMBB);
21168 MF->insert(I, sinkMBB);
21170 // Transfer the remainder of BB and its successor edges to sinkMBB.
21171 sinkMBB->splice(sinkMBB->begin(), MBB,
21172 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21173 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21177 // # fallthrough to mainMBB
21178 // # abortion to sinkMBB
21179 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21180 thisMBB->addSuccessor(mainMBB);
21181 thisMBB->addSuccessor(sinkMBB);
21185 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21186 mainMBB->addSuccessor(sinkMBB);
21189 // EAX is live into the sinkMBB
21190 sinkMBB->addLiveIn(X86::EAX);
21191 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21192 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21195 MI->eraseFromParent();
21199 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21200 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21201 // in the .td file.
21202 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21203 const TargetInstrInfo *TII) {
21205 switch (MI->getOpcode()) {
21206 default: llvm_unreachable("illegal opcode!");
21207 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
21208 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21209 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
21210 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21211 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
21212 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21213 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
21214 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21217 DebugLoc dl = MI->getDebugLoc();
21218 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21220 unsigned NumArgs = MI->getNumOperands();
21221 for (unsigned i = 1; i < NumArgs; ++i) {
21222 MachineOperand &Op = MI->getOperand(i);
21223 if (!(Op.isReg() && Op.isImplicit()))
21224 MIB.addOperand(Op);
21226 if (MI->hasOneMemOperand())
21227 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21229 BuildMI(*BB, MI, dl,
21230 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21231 .addReg(X86::XMM0);
21233 MI->eraseFromParent();
21237 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21238 // defs in an instruction pattern
21239 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21240 const TargetInstrInfo *TII) {
21242 switch (MI->getOpcode()) {
21243 default: llvm_unreachable("illegal opcode!");
21244 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
21245 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21246 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
21247 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21248 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
21249 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21250 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
21251 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21254 DebugLoc dl = MI->getDebugLoc();
21255 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21257 unsigned NumArgs = MI->getNumOperands(); // remove the results
21258 for (unsigned i = 1; i < NumArgs; ++i) {
21259 MachineOperand &Op = MI->getOperand(i);
21260 if (!(Op.isReg() && Op.isImplicit()))
21261 MIB.addOperand(Op);
21263 if (MI->hasOneMemOperand())
21264 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21266 BuildMI(*BB, MI, dl,
21267 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21270 MI->eraseFromParent();
21274 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21275 const X86Subtarget *Subtarget) {
21276 DebugLoc dl = MI->getDebugLoc();
21277 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21279 // insert input VAL into EAX
21280 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21281 .addReg(MI->getOperand(0).getReg());
21282 // insert zero to ECX
21283 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21286 // insert zero to EDX
21287 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21290 // insert WRPKRU instruction
21291 BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21293 MI->eraseFromParent(); // The pseudo is gone now.
21297 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21298 const X86Subtarget *Subtarget) {
21299 DebugLoc dl = MI->getDebugLoc();
21300 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21302 // insert zero to ECX
21303 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21306 // insert RDPKRU instruction
21307 BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21308 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21311 MI->eraseFromParent(); // The pseudo is gone now.
21315 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21316 const X86Subtarget *Subtarget) {
21317 DebugLoc dl = MI->getDebugLoc();
21318 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21319 // Address into RAX/EAX, other two args into ECX, EDX.
21320 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21321 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21322 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21323 for (int i = 0; i < X86::AddrNumOperands; ++i)
21324 MIB.addOperand(MI->getOperand(i));
21326 unsigned ValOps = X86::AddrNumOperands;
21327 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21328 .addReg(MI->getOperand(ValOps).getReg());
21329 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21330 .addReg(MI->getOperand(ValOps+1).getReg());
21332 // The instruction doesn't actually take any operands though.
21333 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21335 MI->eraseFromParent(); // The pseudo is gone now.
21339 MachineBasicBlock *
21340 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21341 MachineBasicBlock *MBB) const {
21342 // Emit va_arg instruction on X86-64.
21344 // Operands to this pseudo-instruction:
21345 // 0 ) Output : destination address (reg)
21346 // 1-5) Input : va_list address (addr, i64mem)
21347 // 6 ) ArgSize : Size (in bytes) of vararg type
21348 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21349 // 8 ) Align : Alignment of type
21350 // 9 ) EFLAGS (implicit-def)
21352 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21353 static_assert(X86::AddrNumOperands == 5,
21354 "VAARG_64 assumes 5 address operands");
21356 unsigned DestReg = MI->getOperand(0).getReg();
21357 MachineOperand &Base = MI->getOperand(1);
21358 MachineOperand &Scale = MI->getOperand(2);
21359 MachineOperand &Index = MI->getOperand(3);
21360 MachineOperand &Disp = MI->getOperand(4);
21361 MachineOperand &Segment = MI->getOperand(5);
21362 unsigned ArgSize = MI->getOperand(6).getImm();
21363 unsigned ArgMode = MI->getOperand(7).getImm();
21364 unsigned Align = MI->getOperand(8).getImm();
21366 // Memory Reference
21367 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21368 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21369 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21371 // Machine Information
21372 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21373 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21374 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21375 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21376 DebugLoc DL = MI->getDebugLoc();
21378 // struct va_list {
21381 // i64 overflow_area (address)
21382 // i64 reg_save_area (address)
21384 // sizeof(va_list) = 24
21385 // alignment(va_list) = 8
21387 unsigned TotalNumIntRegs = 6;
21388 unsigned TotalNumXMMRegs = 8;
21389 bool UseGPOffset = (ArgMode == 1);
21390 bool UseFPOffset = (ArgMode == 2);
21391 unsigned MaxOffset = TotalNumIntRegs * 8 +
21392 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21394 /* Align ArgSize to a multiple of 8 */
21395 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21396 bool NeedsAlign = (Align > 8);
21398 MachineBasicBlock *thisMBB = MBB;
21399 MachineBasicBlock *overflowMBB;
21400 MachineBasicBlock *offsetMBB;
21401 MachineBasicBlock *endMBB;
21403 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
21404 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
21405 unsigned OffsetReg = 0;
21407 if (!UseGPOffset && !UseFPOffset) {
21408 // If we only pull from the overflow region, we don't create a branch.
21409 // We don't need to alter control flow.
21410 OffsetDestReg = 0; // unused
21411 OverflowDestReg = DestReg;
21413 offsetMBB = nullptr;
21414 overflowMBB = thisMBB;
21417 // First emit code to check if gp_offset (or fp_offset) is below the bound.
21418 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21419 // If not, pull from overflow_area. (branch to overflowMBB)
21424 // offsetMBB overflowMBB
21429 // Registers for the PHI in endMBB
21430 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21431 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21433 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21434 MachineFunction *MF = MBB->getParent();
21435 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21436 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21437 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21439 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21441 // Insert the new basic blocks
21442 MF->insert(MBBIter, offsetMBB);
21443 MF->insert(MBBIter, overflowMBB);
21444 MF->insert(MBBIter, endMBB);
21446 // Transfer the remainder of MBB and its successor edges to endMBB.
21447 endMBB->splice(endMBB->begin(), thisMBB,
21448 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21449 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21451 // Make offsetMBB and overflowMBB successors of thisMBB
21452 thisMBB->addSuccessor(offsetMBB);
21453 thisMBB->addSuccessor(overflowMBB);
21455 // endMBB is a successor of both offsetMBB and overflowMBB
21456 offsetMBB->addSuccessor(endMBB);
21457 overflowMBB->addSuccessor(endMBB);
21459 // Load the offset value into a register
21460 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21461 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21465 .addDisp(Disp, UseFPOffset ? 4 : 0)
21466 .addOperand(Segment)
21467 .setMemRefs(MMOBegin, MMOEnd);
21469 // Check if there is enough room left to pull this argument.
21470 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21472 .addImm(MaxOffset + 8 - ArgSizeA8);
21474 // Branch to "overflowMBB" if offset >= max
21475 // Fall through to "offsetMBB" otherwise
21476 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21477 .addMBB(overflowMBB);
21480 // In offsetMBB, emit code to use the reg_save_area.
21482 assert(OffsetReg != 0);
21484 // Read the reg_save_area address.
21485 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21486 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21491 .addOperand(Segment)
21492 .setMemRefs(MMOBegin, MMOEnd);
21494 // Zero-extend the offset
21495 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21496 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21499 .addImm(X86::sub_32bit);
21501 // Add the offset to the reg_save_area to get the final address.
21502 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21503 .addReg(OffsetReg64)
21504 .addReg(RegSaveReg);
21506 // Compute the offset for the next argument
21507 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21508 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21510 .addImm(UseFPOffset ? 16 : 8);
21512 // Store it back into the va_list.
21513 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21517 .addDisp(Disp, UseFPOffset ? 4 : 0)
21518 .addOperand(Segment)
21519 .addReg(NextOffsetReg)
21520 .setMemRefs(MMOBegin, MMOEnd);
21523 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21528 // Emit code to use overflow area
21531 // Load the overflow_area address into a register.
21532 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21533 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21538 .addOperand(Segment)
21539 .setMemRefs(MMOBegin, MMOEnd);
21541 // If we need to align it, do so. Otherwise, just copy the address
21542 // to OverflowDestReg.
21544 // Align the overflow address
21545 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21546 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21548 // aligned_addr = (addr + (align-1)) & ~(align-1)
21549 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21550 .addReg(OverflowAddrReg)
21553 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21555 .addImm(~(uint64_t)(Align-1));
21557 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21558 .addReg(OverflowAddrReg);
21561 // Compute the next overflow address after this argument.
21562 // (the overflow address should be kept 8-byte aligned)
21563 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21564 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21565 .addReg(OverflowDestReg)
21566 .addImm(ArgSizeA8);
21568 // Store the new overflow address.
21569 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21574 .addOperand(Segment)
21575 .addReg(NextAddrReg)
21576 .setMemRefs(MMOBegin, MMOEnd);
21578 // If we branched, emit the PHI to the front of endMBB.
21580 BuildMI(*endMBB, endMBB->begin(), DL,
21581 TII->get(X86::PHI), DestReg)
21582 .addReg(OffsetDestReg).addMBB(offsetMBB)
21583 .addReg(OverflowDestReg).addMBB(overflowMBB);
21586 // Erase the pseudo instruction
21587 MI->eraseFromParent();
21592 MachineBasicBlock *
21593 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21595 MachineBasicBlock *MBB) const {
21596 // Emit code to save XMM registers to the stack. The ABI says that the
21597 // number of registers to save is given in %al, so it's theoretically
21598 // possible to do an indirect jump trick to avoid saving all of them,
21599 // however this code takes a simpler approach and just executes all
21600 // of the stores if %al is non-zero. It's less code, and it's probably
21601 // easier on the hardware branch predictor, and stores aren't all that
21602 // expensive anyway.
21604 // Create the new basic blocks. One block contains all the XMM stores,
21605 // and one block is the final destination regardless of whether any
21606 // stores were performed.
21607 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21608 MachineFunction *F = MBB->getParent();
21609 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21610 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21611 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21612 F->insert(MBBIter, XMMSaveMBB);
21613 F->insert(MBBIter, EndMBB);
21615 // Transfer the remainder of MBB and its successor edges to EndMBB.
21616 EndMBB->splice(EndMBB->begin(), MBB,
21617 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21618 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21620 // The original block will now fall through to the XMM save block.
21621 MBB->addSuccessor(XMMSaveMBB);
21622 // The XMMSaveMBB will fall through to the end block.
21623 XMMSaveMBB->addSuccessor(EndMBB);
21625 // Now add the instructions.
21626 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21627 DebugLoc DL = MI->getDebugLoc();
21629 unsigned CountReg = MI->getOperand(0).getReg();
21630 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21631 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21633 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21634 // If %al is 0, branch around the XMM save block.
21635 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21636 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21637 MBB->addSuccessor(EndMBB);
21640 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21641 // that was just emitted, but clearly shouldn't be "saved".
21642 assert((MI->getNumOperands() <= 3 ||
21643 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21644 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21645 && "Expected last argument to be EFLAGS");
21646 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21647 // In the XMM save block, save all the XMM argument registers.
21648 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21649 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21650 MachineMemOperand *MMO = F->getMachineMemOperand(
21651 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21652 MachineMemOperand::MOStore,
21653 /*Size=*/16, /*Align=*/16);
21654 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21655 .addFrameIndex(RegSaveFrameIndex)
21656 .addImm(/*Scale=*/1)
21657 .addReg(/*IndexReg=*/0)
21658 .addImm(/*Disp=*/Offset)
21659 .addReg(/*Segment=*/0)
21660 .addReg(MI->getOperand(i).getReg())
21661 .addMemOperand(MMO);
21664 MI->eraseFromParent(); // The pseudo instruction is gone now.
21669 // The EFLAGS operand of SelectItr might be missing a kill marker
21670 // because there were multiple uses of EFLAGS, and ISel didn't know
21671 // which to mark. Figure out whether SelectItr should have had a
21672 // kill marker, and set it if it should. Returns the correct kill
21674 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21675 MachineBasicBlock* BB,
21676 const TargetRegisterInfo* TRI) {
21677 // Scan forward through BB for a use/def of EFLAGS.
21678 MachineBasicBlock::iterator miI(std::next(SelectItr));
21679 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21680 const MachineInstr& mi = *miI;
21681 if (mi.readsRegister(X86::EFLAGS))
21683 if (mi.definesRegister(X86::EFLAGS))
21684 break; // Should have kill-flag - update below.
21687 // If we hit the end of the block, check whether EFLAGS is live into a
21689 if (miI == BB->end()) {
21690 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21691 sEnd = BB->succ_end();
21692 sItr != sEnd; ++sItr) {
21693 MachineBasicBlock* succ = *sItr;
21694 if (succ->isLiveIn(X86::EFLAGS))
21699 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21700 // out. SelectMI should have a kill flag on EFLAGS.
21701 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21705 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21706 // together with other CMOV pseudo-opcodes into a single basic-block with
21707 // conditional jump around it.
21708 static bool isCMOVPseudo(MachineInstr *MI) {
21709 switch (MI->getOpcode()) {
21710 case X86::CMOV_FR32:
21711 case X86::CMOV_FR64:
21712 case X86::CMOV_GR8:
21713 case X86::CMOV_GR16:
21714 case X86::CMOV_GR32:
21715 case X86::CMOV_RFP32:
21716 case X86::CMOV_RFP64:
21717 case X86::CMOV_RFP80:
21718 case X86::CMOV_V2F64:
21719 case X86::CMOV_V2I64:
21720 case X86::CMOV_V4F32:
21721 case X86::CMOV_V4F64:
21722 case X86::CMOV_V4I64:
21723 case X86::CMOV_V16F32:
21724 case X86::CMOV_V8F32:
21725 case X86::CMOV_V8F64:
21726 case X86::CMOV_V8I64:
21727 case X86::CMOV_V8I1:
21728 case X86::CMOV_V16I1:
21729 case X86::CMOV_V32I1:
21730 case X86::CMOV_V64I1:
21738 MachineBasicBlock *
21739 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21740 MachineBasicBlock *BB) const {
21741 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21742 DebugLoc DL = MI->getDebugLoc();
21744 // To "insert" a SELECT_CC instruction, we actually have to insert the
21745 // diamond control-flow pattern. The incoming instruction knows the
21746 // destination vreg to set, the condition code register to branch on, the
21747 // true/false values to select between, and a branch opcode to use.
21748 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21749 MachineFunction::iterator It = ++BB->getIterator();
21754 // cmpTY ccX, r1, r2
21756 // fallthrough --> copy0MBB
21757 MachineBasicBlock *thisMBB = BB;
21758 MachineFunction *F = BB->getParent();
21760 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21761 // as described above, by inserting a BB, and then making a PHI at the join
21762 // point to select the true and false operands of the CMOV in the PHI.
21764 // The code also handles two different cases of multiple CMOV opcodes
21768 // In this case, there are multiple CMOVs in a row, all which are based on
21769 // the same condition setting (or the exact opposite condition setting).
21770 // In this case we can lower all the CMOVs using a single inserted BB, and
21771 // then make a number of PHIs at the join point to model the CMOVs. The only
21772 // trickiness here, is that in a case like:
21774 // t2 = CMOV cond1 t1, f1
21775 // t3 = CMOV cond1 t2, f2
21777 // when rewriting this into PHIs, we have to perform some renaming on the
21778 // temps since you cannot have a PHI operand refer to a PHI result earlier
21779 // in the same block. The "simple" but wrong lowering would be:
21781 // t2 = PHI t1(BB1), f1(BB2)
21782 // t3 = PHI t2(BB1), f2(BB2)
21784 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21785 // renaming is to note that on the path through BB1, t2 is really just a
21786 // copy of t1, and do that renaming, properly generating:
21788 // t2 = PHI t1(BB1), f1(BB2)
21789 // t3 = PHI t1(BB1), f2(BB2)
21791 // Case 2, we lower cascaded CMOVs such as
21793 // (CMOV (CMOV F, T, cc1), T, cc2)
21795 // to two successives branches. For that, we look for another CMOV as the
21796 // following instruction.
21798 // Without this, we would add a PHI between the two jumps, which ends up
21799 // creating a few copies all around. For instance, for
21801 // (sitofp (zext (fcmp une)))
21803 // we would generate:
21805 // ucomiss %xmm1, %xmm0
21806 // movss <1.0f>, %xmm0
21807 // movaps %xmm0, %xmm1
21809 // xorps %xmm1, %xmm1
21812 // movaps %xmm1, %xmm0
21816 // because this custom-inserter would have generated:
21828 // A: X = ...; Y = ...
21830 // C: Z = PHI [X, A], [Y, B]
21832 // E: PHI [X, C], [Z, D]
21834 // If we lower both CMOVs in a single step, we can instead generate:
21846 // A: X = ...; Y = ...
21848 // E: PHI [X, A], [X, C], [Y, D]
21850 // Which, in our sitofp/fcmp example, gives us something like:
21852 // ucomiss %xmm1, %xmm0
21853 // movss <1.0f>, %xmm0
21856 // xorps %xmm0, %xmm0
21860 MachineInstr *CascadedCMOV = nullptr;
21861 MachineInstr *LastCMOV = MI;
21862 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21863 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21864 MachineBasicBlock::iterator NextMIIt =
21865 std::next(MachineBasicBlock::iterator(MI));
21867 // Check for case 1, where there are multiple CMOVs with the same condition
21868 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
21869 // number of jumps the most.
21871 if (isCMOVPseudo(MI)) {
21872 // See if we have a string of CMOVS with the same condition.
21873 while (NextMIIt != BB->end() &&
21874 isCMOVPseudo(NextMIIt) &&
21875 (NextMIIt->getOperand(3).getImm() == CC ||
21876 NextMIIt->getOperand(3).getImm() == OppCC)) {
21877 LastCMOV = &*NextMIIt;
21882 // This checks for case 2, but only do this if we didn't already find
21883 // case 1, as indicated by LastCMOV == MI.
21884 if (LastCMOV == MI &&
21885 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21886 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21887 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg() &&
21888 NextMIIt->getOperand(1).isKill()) {
21889 CascadedCMOV = &*NextMIIt;
21892 MachineBasicBlock *jcc1MBB = nullptr;
21894 // If we have a cascaded CMOV, we lower it to two successive branches to
21895 // the same block. EFLAGS is used by both, so mark it as live in the second.
21896 if (CascadedCMOV) {
21897 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21898 F->insert(It, jcc1MBB);
21899 jcc1MBB->addLiveIn(X86::EFLAGS);
21902 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21903 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21904 F->insert(It, copy0MBB);
21905 F->insert(It, sinkMBB);
21907 // If the EFLAGS register isn't dead in the terminator, then claim that it's
21908 // live into the sink and copy blocks.
21909 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21911 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21912 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21913 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21914 copy0MBB->addLiveIn(X86::EFLAGS);
21915 sinkMBB->addLiveIn(X86::EFLAGS);
21918 // Transfer the remainder of BB and its successor edges to sinkMBB.
21919 sinkMBB->splice(sinkMBB->begin(), BB,
21920 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21921 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21923 // Add the true and fallthrough blocks as its successors.
21924 if (CascadedCMOV) {
21925 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21926 BB->addSuccessor(jcc1MBB);
21928 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21929 // jump to the sinkMBB.
21930 jcc1MBB->addSuccessor(copy0MBB);
21931 jcc1MBB->addSuccessor(sinkMBB);
21933 BB->addSuccessor(copy0MBB);
21936 // The true block target of the first (or only) branch is always sinkMBB.
21937 BB->addSuccessor(sinkMBB);
21939 // Create the conditional branch instruction.
21940 unsigned Opc = X86::GetCondBranchFromCond(CC);
21941 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21943 if (CascadedCMOV) {
21944 unsigned Opc2 = X86::GetCondBranchFromCond(
21945 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21946 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21950 // %FalseValue = ...
21951 // # fallthrough to sinkMBB
21952 copy0MBB->addSuccessor(sinkMBB);
21955 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21957 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21958 MachineBasicBlock::iterator MIItEnd =
21959 std::next(MachineBasicBlock::iterator(LastCMOV));
21960 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21961 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21962 MachineInstrBuilder MIB;
21964 // As we are creating the PHIs, we have to be careful if there is more than
21965 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21966 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21967 // That also means that PHI construction must work forward from earlier to
21968 // later, and that the code must maintain a mapping from earlier PHI's
21969 // destination registers, and the registers that went into the PHI.
21971 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21972 unsigned DestReg = MIIt->getOperand(0).getReg();
21973 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21974 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21976 // If this CMOV we are generating is the opposite condition from
21977 // the jump we generated, then we have to swap the operands for the
21978 // PHI that is going to be generated.
21979 if (MIIt->getOperand(3).getImm() == OppCC)
21980 std::swap(Op1Reg, Op2Reg);
21982 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21983 Op1Reg = RegRewriteTable[Op1Reg].first;
21985 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21986 Op2Reg = RegRewriteTable[Op2Reg].second;
21988 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21989 TII->get(X86::PHI), DestReg)
21990 .addReg(Op1Reg).addMBB(copy0MBB)
21991 .addReg(Op2Reg).addMBB(thisMBB);
21993 // Add this PHI to the rewrite table.
21994 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21997 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21998 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21999 if (CascadedCMOV) {
22000 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
22001 // Copy the PHI result to the register defined by the second CMOV.
22002 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
22003 DL, TII->get(TargetOpcode::COPY),
22004 CascadedCMOV->getOperand(0).getReg())
22005 .addReg(MI->getOperand(0).getReg());
22006 CascadedCMOV->eraseFromParent();
22009 // Now remove the CMOV(s).
22010 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
22011 (MIIt++)->eraseFromParent();
22016 MachineBasicBlock *
22017 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
22018 MachineBasicBlock *BB) const {
22019 // Combine the following atomic floating-point modification pattern:
22020 // a.store(reg OP a.load(acquire), release)
22021 // Transform them into:
22022 // OPss (%gpr), %xmm
22023 // movss %xmm, (%gpr)
22024 // Or sd equivalent for 64-bit operations.
22026 switch (MI->getOpcode()) {
22027 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
22028 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
22029 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
22031 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22032 DebugLoc DL = MI->getDebugLoc();
22033 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
22034 MachineOperand MSrc = MI->getOperand(0);
22035 unsigned VSrc = MI->getOperand(5).getReg();
22036 const MachineOperand &Disp = MI->getOperand(3);
22037 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
22038 bool hasDisp = Disp.isGlobal() || Disp.isImm();
22039 if (hasDisp && MSrc.isReg())
22040 MSrc.setIsKill(false);
22041 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
22042 .addOperand(/*Base=*/MSrc)
22043 .addImm(/*Scale=*/1)
22044 .addReg(/*Index=*/0)
22045 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22047 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
22048 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
22050 .addOperand(/*Base=*/MSrc)
22051 .addImm(/*Scale=*/1)
22052 .addReg(/*Index=*/0)
22053 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22054 .addReg(/*Segment=*/0);
22055 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
22056 MI->eraseFromParent(); // The pseudo instruction is gone now.
22060 MachineBasicBlock *
22061 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
22062 MachineBasicBlock *BB) const {
22063 MachineFunction *MF = BB->getParent();
22064 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22065 DebugLoc DL = MI->getDebugLoc();
22066 const BasicBlock *LLVM_BB = BB->getBasicBlock();
22068 assert(MF->shouldSplitStack());
22070 const bool Is64Bit = Subtarget->is64Bit();
22071 const bool IsLP64 = Subtarget->isTarget64BitLP64();
22073 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
22074 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
22077 // ... [Till the alloca]
22078 // If stacklet is not large enough, jump to mallocMBB
22081 // Allocate by subtracting from RSP
22082 // Jump to continueMBB
22085 // Allocate by call to runtime
22089 // [rest of original BB]
22092 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22093 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22094 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22096 MachineRegisterInfo &MRI = MF->getRegInfo();
22097 const TargetRegisterClass *AddrRegClass =
22098 getRegClassFor(getPointerTy(MF->getDataLayout()));
22100 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22101 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22102 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22103 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22104 sizeVReg = MI->getOperand(1).getReg(),
22105 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22107 MachineFunction::iterator MBBIter = ++BB->getIterator();
22109 MF->insert(MBBIter, bumpMBB);
22110 MF->insert(MBBIter, mallocMBB);
22111 MF->insert(MBBIter, continueMBB);
22113 continueMBB->splice(continueMBB->begin(), BB,
22114 std::next(MachineBasicBlock::iterator(MI)), BB->end());
22115 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22117 // Add code to the main basic block to check if the stack limit has been hit,
22118 // and if so, jump to mallocMBB otherwise to bumpMBB.
22119 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22120 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22121 .addReg(tmpSPVReg).addReg(sizeVReg);
22122 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22123 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22124 .addReg(SPLimitVReg);
22125 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22127 // bumpMBB simply decreases the stack pointer, since we know the current
22128 // stacklet has enough space.
22129 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22130 .addReg(SPLimitVReg);
22131 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22132 .addReg(SPLimitVReg);
22133 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22135 // Calls into a routine in libgcc to allocate more space from the heap.
22136 const uint32_t *RegMask =
22137 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22139 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22141 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22142 .addExternalSymbol("__morestack_allocate_stack_space")
22143 .addRegMask(RegMask)
22144 .addReg(X86::RDI, RegState::Implicit)
22145 .addReg(X86::RAX, RegState::ImplicitDefine);
22146 } else if (Is64Bit) {
22147 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22149 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22150 .addExternalSymbol("__morestack_allocate_stack_space")
22151 .addRegMask(RegMask)
22152 .addReg(X86::EDI, RegState::Implicit)
22153 .addReg(X86::EAX, RegState::ImplicitDefine);
22155 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22157 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22158 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22159 .addExternalSymbol("__morestack_allocate_stack_space")
22160 .addRegMask(RegMask)
22161 .addReg(X86::EAX, RegState::ImplicitDefine);
22165 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22168 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22169 .addReg(IsLP64 ? X86::RAX : X86::EAX);
22170 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22172 // Set up the CFG correctly.
22173 BB->addSuccessor(bumpMBB);
22174 BB->addSuccessor(mallocMBB);
22175 mallocMBB->addSuccessor(continueMBB);
22176 bumpMBB->addSuccessor(continueMBB);
22178 // Take care of the PHI nodes.
22179 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22180 MI->getOperand(0).getReg())
22181 .addReg(mallocPtrVReg).addMBB(mallocMBB)
22182 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22184 // Delete the original pseudo instruction.
22185 MI->eraseFromParent();
22188 return continueMBB;
22191 MachineBasicBlock *
22192 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22193 MachineBasicBlock *BB) const {
22194 assert(!Subtarget->isTargetMachO());
22195 DebugLoc DL = MI->getDebugLoc();
22196 MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22197 *BB->getParent(), *BB, MI, DL, false);
22198 MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22199 MI->eraseFromParent(); // The pseudo instruction is gone now.
22203 MachineBasicBlock *
22204 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22205 MachineBasicBlock *BB) const {
22206 MachineFunction *MF = BB->getParent();
22207 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22208 MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22209 DebugLoc DL = MI->getDebugLoc();
22211 assert(!isAsynchronousEHPersonality(
22212 classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22213 "SEH does not use catchret!");
22215 // Only 32-bit EH needs to worry about manually restoring stack pointers.
22216 if (!Subtarget->is32Bit())
22219 // C++ EH creates a new target block to hold the restore code, and wires up
22220 // the new block to the return destination with a normal JMP_4.
22221 MachineBasicBlock *RestoreMBB =
22222 MF->CreateMachineBasicBlock(BB->getBasicBlock());
22223 assert(BB->succ_size() == 1);
22224 MF->insert(std::next(BB->getIterator()), RestoreMBB);
22225 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22226 BB->addSuccessor(RestoreMBB);
22227 MI->getOperand(0).setMBB(RestoreMBB);
22229 auto RestoreMBBI = RestoreMBB->begin();
22230 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22231 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22235 MachineBasicBlock *
22236 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22237 MachineBasicBlock *BB) const {
22238 MachineFunction *MF = BB->getParent();
22239 const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22240 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22241 // Only 32-bit SEH requires special handling for catchpad.
22242 if (IsSEH && Subtarget->is32Bit()) {
22243 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22244 DebugLoc DL = MI->getDebugLoc();
22245 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22247 MI->eraseFromParent();
22251 MachineBasicBlock *
22252 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22253 MachineBasicBlock *BB) const {
22254 // This is pretty easy. We're taking the value that we received from
22255 // our load from the relocation, sticking it in either RDI (x86-64)
22256 // or EAX and doing an indirect call. The return value will then
22257 // be in the normal return register.
22258 MachineFunction *F = BB->getParent();
22259 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22260 DebugLoc DL = MI->getDebugLoc();
22262 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22263 assert(MI->getOperand(3).isGlobal() && "This should be a global");
22265 // Get a register mask for the lowered call.
22266 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22267 // proper register mask.
22268 const uint32_t *RegMask =
22269 Subtarget->is64Bit() ?
22270 Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22271 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22272 if (Subtarget->is64Bit()) {
22273 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22274 TII->get(X86::MOV64rm), X86::RDI)
22276 .addImm(0).addReg(0)
22277 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22278 MI->getOperand(3).getTargetFlags())
22280 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22281 addDirectMem(MIB, X86::RDI);
22282 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22283 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22284 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22285 TII->get(X86::MOV32rm), X86::EAX)
22287 .addImm(0).addReg(0)
22288 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22289 MI->getOperand(3).getTargetFlags())
22291 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22292 addDirectMem(MIB, X86::EAX);
22293 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22295 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22296 TII->get(X86::MOV32rm), X86::EAX)
22297 .addReg(TII->getGlobalBaseReg(F))
22298 .addImm(0).addReg(0)
22299 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22300 MI->getOperand(3).getTargetFlags())
22302 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22303 addDirectMem(MIB, X86::EAX);
22304 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22307 MI->eraseFromParent(); // The pseudo instruction is gone now.
22311 MachineBasicBlock *
22312 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22313 MachineBasicBlock *MBB) const {
22314 DebugLoc DL = MI->getDebugLoc();
22315 MachineFunction *MF = MBB->getParent();
22316 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22317 MachineRegisterInfo &MRI = MF->getRegInfo();
22319 const BasicBlock *BB = MBB->getBasicBlock();
22320 MachineFunction::iterator I = ++MBB->getIterator();
22322 // Memory Reference
22323 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22324 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22327 unsigned MemOpndSlot = 0;
22329 unsigned CurOp = 0;
22331 DstReg = MI->getOperand(CurOp++).getReg();
22332 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22333 assert(RC->hasType(MVT::i32) && "Invalid destination!");
22334 unsigned mainDstReg = MRI.createVirtualRegister(RC);
22335 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22337 MemOpndSlot = CurOp;
22339 MVT PVT = getPointerTy(MF->getDataLayout());
22340 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22341 "Invalid Pointer Size!");
22343 // For v = setjmp(buf), we generate
22346 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22347 // SjLjSetup restoreMBB
22353 // v = phi(main, restore)
22356 // if base pointer being used, load it from frame
22359 MachineBasicBlock *thisMBB = MBB;
22360 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22361 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22362 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22363 MF->insert(I, mainMBB);
22364 MF->insert(I, sinkMBB);
22365 MF->push_back(restoreMBB);
22366 restoreMBB->setHasAddressTaken();
22368 MachineInstrBuilder MIB;
22370 // Transfer the remainder of BB and its successor edges to sinkMBB.
22371 sinkMBB->splice(sinkMBB->begin(), MBB,
22372 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22373 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22376 unsigned PtrStoreOpc = 0;
22377 unsigned LabelReg = 0;
22378 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22379 Reloc::Model RM = MF->getTarget().getRelocationModel();
22380 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22381 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22383 // Prepare IP either in reg or imm.
22384 if (!UseImmLabel) {
22385 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22386 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22387 LabelReg = MRI.createVirtualRegister(PtrRC);
22388 if (Subtarget->is64Bit()) {
22389 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22393 .addMBB(restoreMBB)
22396 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22397 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22398 .addReg(XII->getGlobalBaseReg(MF))
22401 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22405 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22407 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22408 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22409 if (i == X86::AddrDisp)
22410 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22412 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22415 MIB.addReg(LabelReg);
22417 MIB.addMBB(restoreMBB);
22418 MIB.setMemRefs(MMOBegin, MMOEnd);
22420 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22421 .addMBB(restoreMBB);
22423 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22424 MIB.addRegMask(RegInfo->getNoPreservedMask());
22425 thisMBB->addSuccessor(mainMBB);
22426 thisMBB->addSuccessor(restoreMBB);
22430 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22431 mainMBB->addSuccessor(sinkMBB);
22434 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22435 TII->get(X86::PHI), DstReg)
22436 .addReg(mainDstReg).addMBB(mainMBB)
22437 .addReg(restoreDstReg).addMBB(restoreMBB);
22440 if (RegInfo->hasBasePointer(*MF)) {
22441 const bool Uses64BitFramePtr =
22442 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22443 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22444 X86FI->setRestoreBasePointer(MF);
22445 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22446 unsigned BasePtr = RegInfo->getBaseRegister();
22447 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22448 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22449 FramePtr, true, X86FI->getRestoreBasePointerOffset())
22450 .setMIFlag(MachineInstr::FrameSetup);
22452 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22453 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22454 restoreMBB->addSuccessor(sinkMBB);
22456 MI->eraseFromParent();
22460 MachineBasicBlock *
22461 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22462 MachineBasicBlock *MBB) const {
22463 DebugLoc DL = MI->getDebugLoc();
22464 MachineFunction *MF = MBB->getParent();
22465 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22466 MachineRegisterInfo &MRI = MF->getRegInfo();
22468 // Memory Reference
22469 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22470 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22472 MVT PVT = getPointerTy(MF->getDataLayout());
22473 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22474 "Invalid Pointer Size!");
22476 const TargetRegisterClass *RC =
22477 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22478 unsigned Tmp = MRI.createVirtualRegister(RC);
22479 // Since FP is only updated here but NOT referenced, it's treated as GPR.
22480 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22481 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22482 unsigned SP = RegInfo->getStackRegister();
22484 MachineInstrBuilder MIB;
22486 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22487 const int64_t SPOffset = 2 * PVT.getStoreSize();
22489 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22490 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22493 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22494 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22495 MIB.addOperand(MI->getOperand(i));
22496 MIB.setMemRefs(MMOBegin, MMOEnd);
22498 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22499 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22500 if (i == X86::AddrDisp)
22501 MIB.addDisp(MI->getOperand(i), LabelOffset);
22503 MIB.addOperand(MI->getOperand(i));
22505 MIB.setMemRefs(MMOBegin, MMOEnd);
22507 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22508 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22509 if (i == X86::AddrDisp)
22510 MIB.addDisp(MI->getOperand(i), SPOffset);
22512 MIB.addOperand(MI->getOperand(i));
22514 MIB.setMemRefs(MMOBegin, MMOEnd);
22516 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22518 MI->eraseFromParent();
22522 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22523 // accumulator loops. Writing back to the accumulator allows the coalescer
22524 // to remove extra copies in the loop.
22525 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
22526 MachineBasicBlock *
22527 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22528 MachineBasicBlock *MBB) const {
22529 MachineOperand &AddendOp = MI->getOperand(3);
22531 // Bail out early if the addend isn't a register - we can't switch these.
22532 if (!AddendOp.isReg())
22535 MachineFunction &MF = *MBB->getParent();
22536 MachineRegisterInfo &MRI = MF.getRegInfo();
22538 // Check whether the addend is defined by a PHI:
22539 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22540 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22541 if (!AddendDef.isPHI())
22544 // Look for the following pattern:
22546 // %addend = phi [%entry, 0], [%loop, %result]
22548 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22552 // %addend = phi [%entry, 0], [%loop, %result]
22554 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22556 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22557 assert(AddendDef.getOperand(i).isReg());
22558 MachineOperand PHISrcOp = AddendDef.getOperand(i);
22559 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22560 if (&PHISrcInst == MI) {
22561 // Found a matching instruction.
22562 unsigned NewFMAOpc = 0;
22563 switch (MI->getOpcode()) {
22564 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22565 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22566 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22567 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22568 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22569 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22570 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22571 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22572 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22573 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22574 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22575 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22576 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22577 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22578 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22579 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22580 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22581 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22582 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22583 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22585 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22586 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22587 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22588 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22589 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22590 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22591 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22592 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22593 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22594 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22595 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22596 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22597 default: llvm_unreachable("Unrecognized FMA variant.");
22600 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22601 MachineInstrBuilder MIB =
22602 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22603 .addOperand(MI->getOperand(0))
22604 .addOperand(MI->getOperand(3))
22605 .addOperand(MI->getOperand(2))
22606 .addOperand(MI->getOperand(1));
22607 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22608 MI->eraseFromParent();
22615 MachineBasicBlock *
22616 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22617 MachineBasicBlock *BB) const {
22618 switch (MI->getOpcode()) {
22619 default: llvm_unreachable("Unexpected instr type to insert");
22620 case X86::TAILJMPd64:
22621 case X86::TAILJMPr64:
22622 case X86::TAILJMPm64:
22623 case X86::TAILJMPd64_REX:
22624 case X86::TAILJMPr64_REX:
22625 case X86::TAILJMPm64_REX:
22626 llvm_unreachable("TAILJMP64 would not be touched here.");
22627 case X86::TCRETURNdi64:
22628 case X86::TCRETURNri64:
22629 case X86::TCRETURNmi64:
22631 case X86::WIN_ALLOCA:
22632 return EmitLoweredWinAlloca(MI, BB);
22633 case X86::CATCHRET:
22634 return EmitLoweredCatchRet(MI, BB);
22635 case X86::CATCHPAD:
22636 return EmitLoweredCatchPad(MI, BB);
22637 case X86::SEG_ALLOCA_32:
22638 case X86::SEG_ALLOCA_64:
22639 return EmitLoweredSegAlloca(MI, BB);
22640 case X86::TLSCall_32:
22641 case X86::TLSCall_64:
22642 return EmitLoweredTLSCall(MI, BB);
22643 case X86::CMOV_FR32:
22644 case X86::CMOV_FR64:
22645 case X86::CMOV_FR128:
22646 case X86::CMOV_GR8:
22647 case X86::CMOV_GR16:
22648 case X86::CMOV_GR32:
22649 case X86::CMOV_RFP32:
22650 case X86::CMOV_RFP64:
22651 case X86::CMOV_RFP80:
22652 case X86::CMOV_V2F64:
22653 case X86::CMOV_V2I64:
22654 case X86::CMOV_V4F32:
22655 case X86::CMOV_V4F64:
22656 case X86::CMOV_V4I64:
22657 case X86::CMOV_V16F32:
22658 case X86::CMOV_V8F32:
22659 case X86::CMOV_V8F64:
22660 case X86::CMOV_V8I64:
22661 case X86::CMOV_V8I1:
22662 case X86::CMOV_V16I1:
22663 case X86::CMOV_V32I1:
22664 case X86::CMOV_V64I1:
22665 return EmitLoweredSelect(MI, BB);
22667 case X86::RDFLAGS32:
22668 case X86::RDFLAGS64: {
22669 DebugLoc DL = MI->getDebugLoc();
22670 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22672 MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22674 MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22675 BuildMI(*BB, MI, DL, TII->get(PushF));
22676 BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22678 MI->eraseFromParent(); // The pseudo is gone now.
22682 case X86::WRFLAGS32:
22683 case X86::WRFLAGS64: {
22684 DebugLoc DL = MI->getDebugLoc();
22685 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22687 MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22689 MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22690 BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22691 BuildMI(*BB, MI, DL, TII->get(PopF));
22693 MI->eraseFromParent(); // The pseudo is gone now.
22697 case X86::RELEASE_FADD32mr:
22698 case X86::RELEASE_FADD64mr:
22699 return EmitLoweredAtomicFP(MI, BB);
22701 case X86::FP32_TO_INT16_IN_MEM:
22702 case X86::FP32_TO_INT32_IN_MEM:
22703 case X86::FP32_TO_INT64_IN_MEM:
22704 case X86::FP64_TO_INT16_IN_MEM:
22705 case X86::FP64_TO_INT32_IN_MEM:
22706 case X86::FP64_TO_INT64_IN_MEM:
22707 case X86::FP80_TO_INT16_IN_MEM:
22708 case X86::FP80_TO_INT32_IN_MEM:
22709 case X86::FP80_TO_INT64_IN_MEM: {
22710 MachineFunction *F = BB->getParent();
22711 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22712 DebugLoc DL = MI->getDebugLoc();
22714 // Change the floating point control register to use "round towards zero"
22715 // mode when truncating to an integer value.
22716 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22717 addFrameReference(BuildMI(*BB, MI, DL,
22718 TII->get(X86::FNSTCW16m)), CWFrameIdx);
22720 // Load the old value of the high byte of the control word...
22722 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22723 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22726 // Set the high part to be round to zero...
22727 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22730 // Reload the modified control word now...
22731 addFrameReference(BuildMI(*BB, MI, DL,
22732 TII->get(X86::FLDCW16m)), CWFrameIdx);
22734 // Restore the memory image of control word to original value
22735 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22738 // Get the X86 opcode to use.
22740 switch (MI->getOpcode()) {
22741 default: llvm_unreachable("illegal opcode!");
22742 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22743 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22744 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22745 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22746 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22747 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22748 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22749 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22750 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22754 MachineOperand &Op = MI->getOperand(0);
22756 AM.BaseType = X86AddressMode::RegBase;
22757 AM.Base.Reg = Op.getReg();
22759 AM.BaseType = X86AddressMode::FrameIndexBase;
22760 AM.Base.FrameIndex = Op.getIndex();
22762 Op = MI->getOperand(1);
22764 AM.Scale = Op.getImm();
22765 Op = MI->getOperand(2);
22767 AM.IndexReg = Op.getImm();
22768 Op = MI->getOperand(3);
22769 if (Op.isGlobal()) {
22770 AM.GV = Op.getGlobal();
22772 AM.Disp = Op.getImm();
22774 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22775 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22777 // Reload the original control word now.
22778 addFrameReference(BuildMI(*BB, MI, DL,
22779 TII->get(X86::FLDCW16m)), CWFrameIdx);
22781 MI->eraseFromParent(); // The pseudo instruction is gone now.
22784 // String/text processing lowering.
22785 case X86::PCMPISTRM128REG:
22786 case X86::VPCMPISTRM128REG:
22787 case X86::PCMPISTRM128MEM:
22788 case X86::VPCMPISTRM128MEM:
22789 case X86::PCMPESTRM128REG:
22790 case X86::VPCMPESTRM128REG:
22791 case X86::PCMPESTRM128MEM:
22792 case X86::VPCMPESTRM128MEM:
22793 assert(Subtarget->hasSSE42() &&
22794 "Target must have SSE4.2 or AVX features enabled");
22795 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22797 // String/text processing lowering.
22798 case X86::PCMPISTRIREG:
22799 case X86::VPCMPISTRIREG:
22800 case X86::PCMPISTRIMEM:
22801 case X86::VPCMPISTRIMEM:
22802 case X86::PCMPESTRIREG:
22803 case X86::VPCMPESTRIREG:
22804 case X86::PCMPESTRIMEM:
22805 case X86::VPCMPESTRIMEM:
22806 assert(Subtarget->hasSSE42() &&
22807 "Target must have SSE4.2 or AVX features enabled");
22808 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22810 // Thread synchronization.
22812 return EmitMonitor(MI, BB, Subtarget);
22815 return EmitWRPKRU(MI, BB, Subtarget);
22817 return EmitRDPKRU(MI, BB, Subtarget);
22820 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22822 case X86::VASTART_SAVE_XMM_REGS:
22823 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22825 case X86::VAARG_64:
22826 return EmitVAARG64WithCustomInserter(MI, BB);
22828 case X86::EH_SjLj_SetJmp32:
22829 case X86::EH_SjLj_SetJmp64:
22830 return emitEHSjLjSetJmp(MI, BB);
22832 case X86::EH_SjLj_LongJmp32:
22833 case X86::EH_SjLj_LongJmp64:
22834 return emitEHSjLjLongJmp(MI, BB);
22836 case TargetOpcode::STATEPOINT:
22837 // As an implementation detail, STATEPOINT shares the STACKMAP format at
22838 // this point in the process. We diverge later.
22839 return emitPatchPoint(MI, BB);
22841 case TargetOpcode::STACKMAP:
22842 case TargetOpcode::PATCHPOINT:
22843 return emitPatchPoint(MI, BB);
22845 case X86::VFMADDPDr213r:
22846 case X86::VFMADDPSr213r:
22847 case X86::VFMADDSDr213r:
22848 case X86::VFMADDSSr213r:
22849 case X86::VFMSUBPDr213r:
22850 case X86::VFMSUBPSr213r:
22851 case X86::VFMSUBSDr213r:
22852 case X86::VFMSUBSSr213r:
22853 case X86::VFNMADDPDr213r:
22854 case X86::VFNMADDPSr213r:
22855 case X86::VFNMADDSDr213r:
22856 case X86::VFNMADDSSr213r:
22857 case X86::VFNMSUBPDr213r:
22858 case X86::VFNMSUBPSr213r:
22859 case X86::VFNMSUBSDr213r:
22860 case X86::VFNMSUBSSr213r:
22861 case X86::VFMADDSUBPDr213r:
22862 case X86::VFMADDSUBPSr213r:
22863 case X86::VFMSUBADDPDr213r:
22864 case X86::VFMSUBADDPSr213r:
22865 case X86::VFMADDPDr213rY:
22866 case X86::VFMADDPSr213rY:
22867 case X86::VFMSUBPDr213rY:
22868 case X86::VFMSUBPSr213rY:
22869 case X86::VFNMADDPDr213rY:
22870 case X86::VFNMADDPSr213rY:
22871 case X86::VFNMSUBPDr213rY:
22872 case X86::VFNMSUBPSr213rY:
22873 case X86::VFMADDSUBPDr213rY:
22874 case X86::VFMADDSUBPSr213rY:
22875 case X86::VFMSUBADDPDr213rY:
22876 case X86::VFMSUBADDPSr213rY:
22877 return emitFMA3Instr(MI, BB);
22881 //===----------------------------------------------------------------------===//
22882 // X86 Optimization Hooks
22883 //===----------------------------------------------------------------------===//
22885 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22888 const SelectionDAG &DAG,
22889 unsigned Depth) const {
22890 unsigned BitWidth = KnownZero.getBitWidth();
22891 unsigned Opc = Op.getOpcode();
22892 assert((Opc >= ISD::BUILTIN_OP_END ||
22893 Opc == ISD::INTRINSIC_WO_CHAIN ||
22894 Opc == ISD::INTRINSIC_W_CHAIN ||
22895 Opc == ISD::INTRINSIC_VOID) &&
22896 "Should use MaskedValueIsZero if you don't know whether Op"
22897 " is a target node!");
22899 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
22913 // These nodes' second result is a boolean.
22914 if (Op.getResNo() == 0)
22917 case X86ISD::SETCC:
22918 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22920 case ISD::INTRINSIC_WO_CHAIN: {
22921 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22922 unsigned NumLoBits = 0;
22925 case Intrinsic::x86_sse_movmsk_ps:
22926 case Intrinsic::x86_avx_movmsk_ps_256:
22927 case Intrinsic::x86_sse2_movmsk_pd:
22928 case Intrinsic::x86_avx_movmsk_pd_256:
22929 case Intrinsic::x86_mmx_pmovmskb:
22930 case Intrinsic::x86_sse2_pmovmskb_128:
22931 case Intrinsic::x86_avx2_pmovmskb: {
22932 // High bits of movmskp{s|d}, pmovmskb are known zero.
22934 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
22935 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
22936 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
22937 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
22938 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
22939 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
22940 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
22941 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
22943 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22952 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22954 const SelectionDAG &,
22955 unsigned Depth) const {
22956 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22957 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22958 return Op.getValueType().getScalarSizeInBits();
22964 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22965 /// node is a GlobalAddress + offset.
22966 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22967 const GlobalValue* &GA,
22968 int64_t &Offset) const {
22969 if (N->getOpcode() == X86ISD::Wrapper) {
22970 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22971 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22972 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22976 return TargetLowering::isGAPlusOffset(N, GA, Offset);
22979 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22980 /// FIXME: This could be expanded to support 512 bit vectors as well.
22981 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22982 TargetLowering::DAGCombinerInfo &DCI,
22983 const X86Subtarget* Subtarget) {
22985 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22986 SDValue V1 = SVOp->getOperand(0);
22987 SDValue V2 = SVOp->getOperand(1);
22988 MVT VT = SVOp->getSimpleValueType(0);
22989 unsigned NumElems = VT.getVectorNumElements();
22991 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22992 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22996 // V UNDEF BUILD_VECTOR UNDEF
22998 // CONCAT_VECTOR CONCAT_VECTOR
23001 // RESULT: V + zero extended
23003 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
23004 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
23005 V1.getOperand(1).getOpcode() != ISD::UNDEF)
23008 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
23011 // To match the shuffle mask, the first half of the mask should
23012 // be exactly the first vector, and all the rest a splat with the
23013 // first element of the second one.
23014 for (unsigned i = 0; i != NumElems/2; ++i)
23015 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
23016 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
23019 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
23020 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
23021 if (Ld->hasNUsesOfValue(1, 0)) {
23022 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
23023 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
23025 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
23027 Ld->getPointerInfo(),
23028 Ld->getAlignment(),
23029 false/*isVolatile*/, true/*ReadMem*/,
23030 false/*WriteMem*/);
23032 // Make sure the newly-created LOAD is in the same position as Ld in
23033 // terms of dependency. We create a TokenFactor for Ld and ResNode,
23034 // and update uses of Ld's output chain to use the TokenFactor.
23035 if (Ld->hasAnyUseOfValue(1)) {
23036 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23037 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
23038 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
23039 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
23040 SDValue(ResNode.getNode(), 1));
23043 return DAG.getBitcast(VT, ResNode);
23047 // Emit a zeroed vector and insert the desired subvector on its
23049 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
23050 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
23051 return DCI.CombineTo(N, InsV);
23057 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
23060 /// This is the leaf of the recursive combinine below. When we have found some
23061 /// chain of single-use x86 shuffle instructions and accumulated the combined
23062 /// shuffle mask represented by them, this will try to pattern match that mask
23063 /// into either a single instruction if there is a special purpose instruction
23064 /// for this operation, or into a PSHUFB instruction which is a fully general
23065 /// instruction but should only be used to replace chains over a certain depth.
23066 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
23067 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
23068 TargetLowering::DAGCombinerInfo &DCI,
23069 const X86Subtarget *Subtarget) {
23070 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
23072 // Find the operand that enters the chain. Note that multiple uses are OK
23073 // here, we're not going to remove the operand we find.
23074 SDValue Input = Op.getOperand(0);
23075 while (Input.getOpcode() == ISD::BITCAST)
23076 Input = Input.getOperand(0);
23078 MVT VT = Input.getSimpleValueType();
23079 MVT RootVT = Root.getSimpleValueType();
23082 if (Mask.size() == 1) {
23083 int Index = Mask[0];
23084 assert((Index >= 0 || Index == SM_SentinelUndef ||
23085 Index == SM_SentinelZero) &&
23086 "Invalid shuffle index found!");
23088 // We may end up with an accumulated mask of size 1 as a result of
23089 // widening of shuffle operands (see function canWidenShuffleElements).
23090 // If the only shuffle index is equal to SM_SentinelZero then propagate
23091 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
23092 // mask, and therefore the entire chain of shuffles can be folded away.
23093 if (Index == SM_SentinelZero)
23094 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23096 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23101 // Use the float domain if the operand type is a floating point type.
23102 bool FloatDomain = VT.isFloatingPoint();
23104 // For floating point shuffles, we don't have free copies in the shuffle
23105 // instructions or the ability to load as part of the instruction, so
23106 // canonicalize their shuffles to UNPCK or MOV variants.
23108 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23109 // vectors because it can have a load folded into it that UNPCK cannot. This
23110 // doesn't preclude something switching to the shorter encoding post-RA.
23112 // FIXME: Should teach these routines about AVX vector widths.
23113 if (FloatDomain && VT.is128BitVector()) {
23114 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23115 bool Lo = Mask.equals({0, 0});
23118 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23119 // is no slower than UNPCKLPD but has the option to fold the input operand
23120 // into even an unaligned memory load.
23121 if (Lo && Subtarget->hasSSE3()) {
23122 Shuffle = X86ISD::MOVDDUP;
23123 ShuffleVT = MVT::v2f64;
23125 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23126 // than the UNPCK variants.
23127 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23128 ShuffleVT = MVT::v4f32;
23130 if (Depth == 1 && Root->getOpcode() == Shuffle)
23131 return false; // Nothing to do!
23132 Op = DAG.getBitcast(ShuffleVT, Input);
23133 DCI.AddToWorklist(Op.getNode());
23134 if (Shuffle == X86ISD::MOVDDUP)
23135 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23137 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23138 DCI.AddToWorklist(Op.getNode());
23139 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23143 if (Subtarget->hasSSE3() &&
23144 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23145 bool Lo = Mask.equals({0, 0, 2, 2});
23146 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23147 MVT ShuffleVT = MVT::v4f32;
23148 if (Depth == 1 && Root->getOpcode() == Shuffle)
23149 return false; // Nothing to do!
23150 Op = DAG.getBitcast(ShuffleVT, Input);
23151 DCI.AddToWorklist(Op.getNode());
23152 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23153 DCI.AddToWorklist(Op.getNode());
23154 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23158 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23159 bool Lo = Mask.equals({0, 0, 1, 1});
23160 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23161 MVT ShuffleVT = MVT::v4f32;
23162 if (Depth == 1 && Root->getOpcode() == Shuffle)
23163 return false; // Nothing to do!
23164 Op = DAG.getBitcast(ShuffleVT, Input);
23165 DCI.AddToWorklist(Op.getNode());
23166 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23167 DCI.AddToWorklist(Op.getNode());
23168 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23174 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23175 // variants as none of these have single-instruction variants that are
23176 // superior to the UNPCK formulation.
23177 if (!FloatDomain && VT.is128BitVector() &&
23178 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23179 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23180 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23182 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23183 bool Lo = Mask[0] == 0;
23184 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23185 if (Depth == 1 && Root->getOpcode() == Shuffle)
23186 return false; // Nothing to do!
23188 switch (Mask.size()) {
23190 ShuffleVT = MVT::v8i16;
23193 ShuffleVT = MVT::v16i8;
23196 llvm_unreachable("Impossible mask size!");
23198 Op = DAG.getBitcast(ShuffleVT, Input);
23199 DCI.AddToWorklist(Op.getNode());
23200 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23201 DCI.AddToWorklist(Op.getNode());
23202 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23207 // Don't try to re-form single instruction chains under any circumstances now
23208 // that we've done encoding canonicalization for them.
23212 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23213 // can replace them with a single PSHUFB instruction profitably. Intel's
23214 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23215 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23216 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23217 SmallVector<SDValue, 16> PSHUFBMask;
23218 int NumBytes = VT.getSizeInBits() / 8;
23219 int Ratio = NumBytes / Mask.size();
23220 for (int i = 0; i < NumBytes; ++i) {
23221 if (Mask[i / Ratio] == SM_SentinelUndef) {
23222 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23225 int M = Mask[i / Ratio] != SM_SentinelZero
23226 ? Ratio * Mask[i / Ratio] + i % Ratio
23228 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23230 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23231 Op = DAG.getBitcast(ByteVT, Input);
23232 DCI.AddToWorklist(Op.getNode());
23233 SDValue PSHUFBMaskOp =
23234 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23235 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23236 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23237 DCI.AddToWorklist(Op.getNode());
23238 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23243 // Failed to find any combines.
23247 /// \brief Fully generic combining of x86 shuffle instructions.
23249 /// This should be the last combine run over the x86 shuffle instructions. Once
23250 /// they have been fully optimized, this will recursively consider all chains
23251 /// of single-use shuffle instructions, build a generic model of the cumulative
23252 /// shuffle operation, and check for simpler instructions which implement this
23253 /// operation. We use this primarily for two purposes:
23255 /// 1) Collapse generic shuffles to specialized single instructions when
23256 /// equivalent. In most cases, this is just an encoding size win, but
23257 /// sometimes we will collapse multiple generic shuffles into a single
23258 /// special-purpose shuffle.
23259 /// 2) Look for sequences of shuffle instructions with 3 or more total
23260 /// instructions, and replace them with the slightly more expensive SSSE3
23261 /// PSHUFB instruction if available. We do this as the last combining step
23262 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
23263 /// a suitable short sequence of other instructions. The PHUFB will either
23264 /// use a register or have to read from memory and so is slightly (but only
23265 /// slightly) more expensive than the other shuffle instructions.
23267 /// Because this is inherently a quadratic operation (for each shuffle in
23268 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23269 /// This should never be an issue in practice as the shuffle lowering doesn't
23270 /// produce sequences of more than 8 instructions.
23272 /// FIXME: We will currently miss some cases where the redundant shuffling
23273 /// would simplify under the threshold for PSHUFB formation because of
23274 /// combine-ordering. To fix this, we should do the redundant instruction
23275 /// combining in this recursive walk.
23276 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23277 ArrayRef<int> RootMask,
23278 int Depth, bool HasPSHUFB,
23280 TargetLowering::DAGCombinerInfo &DCI,
23281 const X86Subtarget *Subtarget) {
23282 // Bound the depth of our recursive combine because this is ultimately
23283 // quadratic in nature.
23287 // Directly rip through bitcasts to find the underlying operand.
23288 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23289 Op = Op.getOperand(0);
23291 MVT VT = Op.getSimpleValueType();
23292 if (!VT.isVector())
23293 return false; // Bail if we hit a non-vector.
23295 assert(Root.getSimpleValueType().isVector() &&
23296 "Shuffles operate on vector types!");
23297 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23298 "Can only combine shuffles of the same vector register size.");
23300 if (!isTargetShuffle(Op.getOpcode()))
23302 SmallVector<int, 16> OpMask;
23304 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23305 // We only can combine unary shuffles which we can decode the mask for.
23306 if (!HaveMask || !IsUnary)
23309 assert(VT.getVectorNumElements() == OpMask.size() &&
23310 "Different mask size from vector size!");
23311 assert(((RootMask.size() > OpMask.size() &&
23312 RootMask.size() % OpMask.size() == 0) ||
23313 (OpMask.size() > RootMask.size() &&
23314 OpMask.size() % RootMask.size() == 0) ||
23315 OpMask.size() == RootMask.size()) &&
23316 "The smaller number of elements must divide the larger.");
23317 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23318 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23319 assert(((RootRatio == 1 && OpRatio == 1) ||
23320 (RootRatio == 1) != (OpRatio == 1)) &&
23321 "Must not have a ratio for both incoming and op masks!");
23323 SmallVector<int, 16> Mask;
23324 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23326 // Merge this shuffle operation's mask into our accumulated mask. Note that
23327 // this shuffle's mask will be the first applied to the input, followed by the
23328 // root mask to get us all the way to the root value arrangement. The reason
23329 // for this order is that we are recursing up the operation chain.
23330 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23331 int RootIdx = i / RootRatio;
23332 if (RootMask[RootIdx] < 0) {
23333 // This is a zero or undef lane, we're done.
23334 Mask.push_back(RootMask[RootIdx]);
23338 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23339 int OpIdx = RootMaskedIdx / OpRatio;
23340 if (OpMask[OpIdx] < 0) {
23341 // The incoming lanes are zero or undef, it doesn't matter which ones we
23343 Mask.push_back(OpMask[OpIdx]);
23347 // Ok, we have non-zero lanes, map them through.
23348 Mask.push_back(OpMask[OpIdx] * OpRatio +
23349 RootMaskedIdx % OpRatio);
23352 // See if we can recurse into the operand to combine more things.
23353 switch (Op.getOpcode()) {
23354 case X86ISD::PSHUFB:
23356 case X86ISD::PSHUFD:
23357 case X86ISD::PSHUFHW:
23358 case X86ISD::PSHUFLW:
23359 if (Op.getOperand(0).hasOneUse() &&
23360 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23361 HasPSHUFB, DAG, DCI, Subtarget))
23365 case X86ISD::UNPCKL:
23366 case X86ISD::UNPCKH:
23367 assert(Op.getOperand(0) == Op.getOperand(1) &&
23368 "We only combine unary shuffles!");
23369 // We can't check for single use, we have to check that this shuffle is the
23371 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23372 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23373 HasPSHUFB, DAG, DCI, Subtarget))
23378 // Minor canonicalization of the accumulated shuffle mask to make it easier
23379 // to match below. All this does is detect masks with squential pairs of
23380 // elements, and shrink them to the half-width mask. It does this in a loop
23381 // so it will reduce the size of the mask to the minimal width mask which
23382 // performs an equivalent shuffle.
23383 SmallVector<int, 16> WidenedMask;
23384 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23385 Mask = std::move(WidenedMask);
23386 WidenedMask.clear();
23389 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23393 /// \brief Get the PSHUF-style mask from PSHUF node.
23395 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23396 /// PSHUF-style masks that can be reused with such instructions.
23397 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23398 MVT VT = N.getSimpleValueType();
23399 SmallVector<int, 4> Mask;
23401 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23405 // If we have more than 128-bits, only the low 128-bits of shuffle mask
23406 // matter. Check that the upper masks are repeats and remove them.
23407 if (VT.getSizeInBits() > 128) {
23408 int LaneElts = 128 / VT.getScalarSizeInBits();
23410 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23411 for (int j = 0; j < LaneElts; ++j)
23412 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23413 "Mask doesn't repeat in high 128-bit lanes!");
23415 Mask.resize(LaneElts);
23418 switch (N.getOpcode()) {
23419 case X86ISD::PSHUFD:
23421 case X86ISD::PSHUFLW:
23424 case X86ISD::PSHUFHW:
23425 Mask.erase(Mask.begin(), Mask.begin() + 4);
23426 for (int &M : Mask)
23430 llvm_unreachable("No valid shuffle instruction found!");
23434 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23436 /// We walk up the chain and look for a combinable shuffle, skipping over
23437 /// shuffles that we could hoist this shuffle's transformation past without
23438 /// altering anything.
23440 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23442 TargetLowering::DAGCombinerInfo &DCI) {
23443 assert(N.getOpcode() == X86ISD::PSHUFD &&
23444 "Called with something other than an x86 128-bit half shuffle!");
23447 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23448 // of the shuffles in the chain so that we can form a fresh chain to replace
23450 SmallVector<SDValue, 8> Chain;
23451 SDValue V = N.getOperand(0);
23452 for (; V.hasOneUse(); V = V.getOperand(0)) {
23453 switch (V.getOpcode()) {
23455 return SDValue(); // Nothing combined!
23458 // Skip bitcasts as we always know the type for the target specific
23462 case X86ISD::PSHUFD:
23463 // Found another dword shuffle.
23466 case X86ISD::PSHUFLW:
23467 // Check that the low words (being shuffled) are the identity in the
23468 // dword shuffle, and the high words are self-contained.
23469 if (Mask[0] != 0 || Mask[1] != 1 ||
23470 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23473 Chain.push_back(V);
23476 case X86ISD::PSHUFHW:
23477 // Check that the high words (being shuffled) are the identity in the
23478 // dword shuffle, and the low words are self-contained.
23479 if (Mask[2] != 2 || Mask[3] != 3 ||
23480 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23483 Chain.push_back(V);
23486 case X86ISD::UNPCKL:
23487 case X86ISD::UNPCKH:
23488 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23489 // shuffle into a preceding word shuffle.
23490 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23491 V.getSimpleValueType().getVectorElementType() != MVT::i16)
23494 // Search for a half-shuffle which we can combine with.
23495 unsigned CombineOp =
23496 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23497 if (V.getOperand(0) != V.getOperand(1) ||
23498 !V->isOnlyUserOf(V.getOperand(0).getNode()))
23500 Chain.push_back(V);
23501 V = V.getOperand(0);
23503 switch (V.getOpcode()) {
23505 return SDValue(); // Nothing to combine.
23507 case X86ISD::PSHUFLW:
23508 case X86ISD::PSHUFHW:
23509 if (V.getOpcode() == CombineOp)
23512 Chain.push_back(V);
23516 V = V.getOperand(0);
23520 } while (V.hasOneUse());
23523 // Break out of the loop if we break out of the switch.
23527 if (!V.hasOneUse())
23528 // We fell out of the loop without finding a viable combining instruction.
23531 // Merge this node's mask and our incoming mask.
23532 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23533 for (int &M : Mask)
23535 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23536 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23538 // Rebuild the chain around this new shuffle.
23539 while (!Chain.empty()) {
23540 SDValue W = Chain.pop_back_val();
23542 if (V.getValueType() != W.getOperand(0).getValueType())
23543 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23545 switch (W.getOpcode()) {
23547 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23549 case X86ISD::UNPCKL:
23550 case X86ISD::UNPCKH:
23551 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23554 case X86ISD::PSHUFD:
23555 case X86ISD::PSHUFLW:
23556 case X86ISD::PSHUFHW:
23557 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23561 if (V.getValueType() != N.getValueType())
23562 V = DAG.getBitcast(N.getValueType(), V);
23564 // Return the new chain to replace N.
23568 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23571 /// We walk up the chain, skipping shuffles of the other half and looking
23572 /// through shuffles which switch halves trying to find a shuffle of the same
23573 /// pair of dwords.
23574 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23576 TargetLowering::DAGCombinerInfo &DCI) {
23578 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23579 "Called with something other than an x86 128-bit half shuffle!");
23581 unsigned CombineOpcode = N.getOpcode();
23583 // Walk up a single-use chain looking for a combinable shuffle.
23584 SDValue V = N.getOperand(0);
23585 for (; V.hasOneUse(); V = V.getOperand(0)) {
23586 switch (V.getOpcode()) {
23588 return false; // Nothing combined!
23591 // Skip bitcasts as we always know the type for the target specific
23595 case X86ISD::PSHUFLW:
23596 case X86ISD::PSHUFHW:
23597 if (V.getOpcode() == CombineOpcode)
23600 // Other-half shuffles are no-ops.
23603 // Break out of the loop if we break out of the switch.
23607 if (!V.hasOneUse())
23608 // We fell out of the loop without finding a viable combining instruction.
23611 // Combine away the bottom node as its shuffle will be accumulated into
23612 // a preceding shuffle.
23613 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23615 // Record the old value.
23618 // Merge this node's mask and our incoming mask (adjusted to account for all
23619 // the pshufd instructions encountered).
23620 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23621 for (int &M : Mask)
23623 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23624 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23626 // Check that the shuffles didn't cancel each other out. If not, we need to
23627 // combine to the new one.
23629 // Replace the combinable shuffle with the combined one, updating all users
23630 // so that we re-evaluate the chain here.
23631 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23636 /// \brief Try to combine x86 target specific shuffles.
23637 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23638 TargetLowering::DAGCombinerInfo &DCI,
23639 const X86Subtarget *Subtarget) {
23641 MVT VT = N.getSimpleValueType();
23642 SmallVector<int, 4> Mask;
23644 switch (N.getOpcode()) {
23645 case X86ISD::PSHUFD:
23646 case X86ISD::PSHUFLW:
23647 case X86ISD::PSHUFHW:
23648 Mask = getPSHUFShuffleMask(N);
23649 assert(Mask.size() == 4);
23651 case X86ISD::UNPCKL: {
23652 // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23653 // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23654 // moves upper half elements into the lower half part. For example:
23656 // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23658 // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23660 // will be combined to:
23662 // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23664 // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23665 // happen due to advanced instructions.
23666 if (!VT.is128BitVector())
23669 auto Op0 = N.getOperand(0);
23670 auto Op1 = N.getOperand(1);
23671 if (Op0.getOpcode() == ISD::UNDEF &&
23672 Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23673 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23675 unsigned NumElts = VT.getVectorNumElements();
23676 SmallVector<int, 8> ExpectedMask(NumElts, -1);
23677 std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23680 auto ShufOp = Op1.getOperand(0);
23681 if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23682 return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23686 case X86ISD::BLENDI: {
23687 SDValue V0 = N->getOperand(0);
23688 SDValue V1 = N->getOperand(1);
23689 assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23690 "Unexpected input vector types");
23692 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23693 // operands and changing the mask to 1. This saves us a bunch of
23694 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23695 // x86InstrInfo knows how to commute this back after instruction selection
23696 // if it would help register allocation.
23698 // TODO: If optimizing for size or a processor that doesn't suffer from
23699 // partial register update stalls, this should be transformed into a MOVSD
23700 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23702 if (VT == MVT::v2f64)
23703 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23704 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23705 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23706 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23715 // Nuke no-op shuffles that show up after combining.
23716 if (isNoopShuffleMask(Mask))
23717 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23719 // Look for simplifications involving one or two shuffle instructions.
23720 SDValue V = N.getOperand(0);
23721 switch (N.getOpcode()) {
23724 case X86ISD::PSHUFLW:
23725 case X86ISD::PSHUFHW:
23726 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23728 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23729 return SDValue(); // We combined away this shuffle, so we're done.
23731 // See if this reduces to a PSHUFD which is no more expensive and can
23732 // combine with more operations. Note that it has to at least flip the
23733 // dwords as otherwise it would have been removed as a no-op.
23734 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23735 int DMask[] = {0, 1, 2, 3};
23736 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23737 DMask[DOffset + 0] = DOffset + 1;
23738 DMask[DOffset + 1] = DOffset + 0;
23739 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23740 V = DAG.getBitcast(DVT, V);
23741 DCI.AddToWorklist(V.getNode());
23742 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23743 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23744 DCI.AddToWorklist(V.getNode());
23745 return DAG.getBitcast(VT, V);
23748 // Look for shuffle patterns which can be implemented as a single unpack.
23749 // FIXME: This doesn't handle the location of the PSHUFD generically, and
23750 // only works when we have a PSHUFD followed by two half-shuffles.
23751 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23752 (V.getOpcode() == X86ISD::PSHUFLW ||
23753 V.getOpcode() == X86ISD::PSHUFHW) &&
23754 V.getOpcode() != N.getOpcode() &&
23756 SDValue D = V.getOperand(0);
23757 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23758 D = D.getOperand(0);
23759 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23760 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23761 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23762 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23763 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23765 for (int i = 0; i < 4; ++i) {
23766 WordMask[i + NOffset] = Mask[i] + NOffset;
23767 WordMask[i + VOffset] = VMask[i] + VOffset;
23769 // Map the word mask through the DWord mask.
23771 for (int i = 0; i < 8; ++i)
23772 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23773 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23774 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23775 // We can replace all three shuffles with an unpack.
23776 V = DAG.getBitcast(VT, D.getOperand(0));
23777 DCI.AddToWorklist(V.getNode());
23778 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23787 case X86ISD::PSHUFD:
23788 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23797 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23799 /// We combine this directly on the abstract vector shuffle nodes so it is
23800 /// easier to generically match. We also insert dummy vector shuffle nodes for
23801 /// the operands which explicitly discard the lanes which are unused by this
23802 /// operation to try to flow through the rest of the combiner the fact that
23803 /// they're unused.
23804 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23805 SelectionDAG &DAG) {
23807 EVT VT = N->getValueType(0);
23808 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23809 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23812 // We only handle target-independent shuffles.
23813 // FIXME: It would be easy and harmless to use the target shuffle mask
23814 // extraction tool to support more.
23815 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23818 auto *SVN = cast<ShuffleVectorSDNode>(N);
23819 SmallVector<int, 8> Mask;
23820 for (int M : SVN->getMask())
23823 SDValue V1 = N->getOperand(0);
23824 SDValue V2 = N->getOperand(1);
23826 // We require the first shuffle operand to be the FSUB node, and the second to
23827 // be the FADD node.
23828 if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23829 ShuffleVectorSDNode::commuteMask(Mask);
23831 } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23834 // If there are other uses of these operations we can't fold them.
23835 if (!V1->hasOneUse() || !V2->hasOneUse())
23838 // Ensure that both operations have the same operands. Note that we can
23839 // commute the FADD operands.
23840 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23841 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23842 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23845 // We're looking for blends between FADD and FSUB nodes. We insist on these
23846 // nodes being lined up in a specific expected pattern.
23847 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23848 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23849 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23852 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23855 /// PerformShuffleCombine - Performs several different shuffle combines.
23856 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23857 TargetLowering::DAGCombinerInfo &DCI,
23858 const X86Subtarget *Subtarget) {
23860 SDValue N0 = N->getOperand(0);
23861 SDValue N1 = N->getOperand(1);
23862 EVT VT = N->getValueType(0);
23864 // Don't create instructions with illegal types after legalize types has run.
23865 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23866 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23869 // If we have legalized the vector types, look for blends of FADD and FSUB
23870 // nodes that we can fuse into an ADDSUB node.
23871 if (TLI.isTypeLegal(VT))
23872 if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23875 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23876 if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23877 N->getOpcode() == ISD::VECTOR_SHUFFLE)
23878 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23880 // During Type Legalization, when promoting illegal vector types,
23881 // the backend might introduce new shuffle dag nodes and bitcasts.
23883 // This code performs the following transformation:
23884 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23885 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23887 // We do this only if both the bitcast and the BINOP dag nodes have
23888 // one use. Also, perform this transformation only if the new binary
23889 // operation is legal. This is to avoid introducing dag nodes that
23890 // potentially need to be further expanded (or custom lowered) into a
23891 // less optimal sequence of dag nodes.
23892 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23893 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23894 N0.getOpcode() == ISD::BITCAST) {
23895 SDValue BC0 = N0.getOperand(0);
23896 EVT SVT = BC0.getValueType();
23897 unsigned Opcode = BC0.getOpcode();
23898 unsigned NumElts = VT.getVectorNumElements();
23900 if (BC0.hasOneUse() && SVT.isVector() &&
23901 SVT.getVectorNumElements() * 2 == NumElts &&
23902 TLI.isOperationLegal(Opcode, VT)) {
23903 bool CanFold = false;
23915 unsigned SVTNumElts = SVT.getVectorNumElements();
23916 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23917 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23918 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23919 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23920 CanFold = SVOp->getMaskElt(i) < 0;
23923 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23924 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23925 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23926 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23931 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23932 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23933 // consecutive, non-overlapping, and in the right order.
23934 SmallVector<SDValue, 16> Elts;
23935 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23936 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23938 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23941 if (isTargetShuffle(N->getOpcode())) {
23943 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23944 if (Shuffle.getNode())
23947 // Try recursively combining arbitrary sequences of x86 shuffle
23948 // instructions into higher-order shuffles. We do this after combining
23949 // specific PSHUF instruction sequences into their minimal form so that we
23950 // can evaluate how many specialized shuffle instructions are involved in
23951 // a particular chain.
23952 SmallVector<int, 1> NonceMask; // Just a placeholder.
23953 NonceMask.push_back(0);
23954 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23955 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23957 return SDValue(); // This routine will use CombineTo to replace N.
23963 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23964 /// specific shuffle of a load can be folded into a single element load.
23965 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23966 /// shuffles have been custom lowered so we need to handle those here.
23967 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23968 TargetLowering::DAGCombinerInfo &DCI) {
23969 if (DCI.isBeforeLegalizeOps())
23972 SDValue InVec = N->getOperand(0);
23973 SDValue EltNo = N->getOperand(1);
23974 EVT EltVT = N->getValueType(0);
23976 if (!isa<ConstantSDNode>(EltNo))
23979 EVT OriginalVT = InVec.getValueType();
23981 if (InVec.getOpcode() == ISD::BITCAST) {
23982 // Don't duplicate a load with other uses.
23983 if (!InVec.hasOneUse())
23985 EVT BCVT = InVec.getOperand(0).getValueType();
23986 if (!BCVT.isVector() ||
23987 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23989 InVec = InVec.getOperand(0);
23992 EVT CurrentVT = InVec.getValueType();
23994 if (!isTargetShuffle(InVec.getOpcode()))
23997 // Don't duplicate a load with other uses.
23998 if (!InVec.hasOneUse())
24001 SmallVector<int, 16> ShuffleMask;
24003 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
24004 ShuffleMask, UnaryShuffle))
24007 // Select the input vector, guarding against out of range extract vector.
24008 unsigned NumElems = CurrentVT.getVectorNumElements();
24009 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
24010 int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
24012 if (Idx == SM_SentinelZero)
24013 return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
24014 : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
24015 if (Idx == SM_SentinelUndef)
24016 return DAG.getUNDEF(EltVT);
24018 assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
24019 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
24020 : InVec.getOperand(1);
24022 // If inputs to shuffle are the same for both ops, then allow 2 uses
24023 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
24024 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
24026 if (LdNode.getOpcode() == ISD::BITCAST) {
24027 // Don't duplicate a load with other uses.
24028 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
24031 AllowedUses = 1; // only allow 1 load use if we have a bitcast
24032 LdNode = LdNode.getOperand(0);
24035 if (!ISD::isNormalLoad(LdNode.getNode()))
24038 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
24040 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
24043 // If there's a bitcast before the shuffle, check if the load type and
24044 // alignment is valid.
24045 unsigned Align = LN0->getAlignment();
24046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24047 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
24048 EltVT.getTypeForEVT(*DAG.getContext()));
24050 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
24053 // All checks match so transform back to vector_shuffle so that DAG combiner
24054 // can finish the job
24057 // Create shuffle node taking into account the case that its a unary shuffle
24058 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
24059 : InVec.getOperand(1);
24060 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
24061 InVec.getOperand(0), Shuffle,
24063 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
24064 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
24068 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
24069 const X86Subtarget *Subtarget) {
24070 SDValue N0 = N->getOperand(0);
24071 EVT VT = N->getValueType(0);
24073 // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
24074 // special and don't usually play with other vector types, it's better to
24075 // handle them early to be sure we emit efficient code by avoiding
24076 // store-load conversions.
24077 if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
24078 N0.getValueType() == MVT::v2i32 &&
24079 isNullConstant(N0.getOperand(1))) {
24080 SDValue N00 = N0->getOperand(0);
24081 if (N00.getValueType() == MVT::i32)
24082 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
24085 // Convert a bitcasted integer logic operation that has one bitcasted
24086 // floating-point operand and one constant operand into a floating-point
24087 // logic operation. This may create a load of the constant, but that is
24088 // cheaper than materializing the constant in an integer register and
24089 // transferring it to an SSE register or transferring the SSE operand to
24090 // integer register and back.
24092 switch (N0.getOpcode()) {
24093 case ISD::AND: FPOpcode = X86ISD::FAND; break;
24094 case ISD::OR: FPOpcode = X86ISD::FOR; break;
24095 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24096 default: return SDValue();
24098 if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24099 (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24100 isa<ConstantSDNode>(N0.getOperand(1)) &&
24101 N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24102 N0.getOperand(0).getOperand(0).getValueType() == VT) {
24103 SDValue N000 = N0.getOperand(0).getOperand(0);
24104 SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24105 return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24111 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24112 /// generation and convert it from being a bunch of shuffles and extracts
24113 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24114 /// storing the value and loading scalars back, while for x64 we should
24115 /// use 64-bit extracts and shifts.
24116 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24117 TargetLowering::DAGCombinerInfo &DCI) {
24118 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24121 SDValue InputVector = N->getOperand(0);
24122 SDLoc dl(InputVector);
24123 // Detect mmx to i32 conversion through a v2i32 elt extract.
24124 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24125 N->getValueType(0) == MVT::i32 &&
24126 InputVector.getValueType() == MVT::v2i32) {
24128 // The bitcast source is a direct mmx result.
24129 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24130 if (MMXSrc.getValueType() == MVT::x86mmx)
24131 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24132 N->getValueType(0),
24133 InputVector.getNode()->getOperand(0));
24135 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24136 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24137 MMXSrc.getValueType() == MVT::i64) {
24138 SDValue MMXSrcOp = MMXSrc.getOperand(0);
24139 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24140 MMXSrcOp.getValueType() == MVT::v1i64 &&
24141 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24142 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24143 N->getValueType(0), MMXSrcOp.getOperand(0));
24147 EVT VT = N->getValueType(0);
24149 if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24150 InputVector.getOpcode() == ISD::BITCAST &&
24151 isa<ConstantSDNode>(InputVector.getOperand(0))) {
24152 uint64_t ExtractedElt =
24153 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24154 uint64_t InputValue =
24155 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24156 uint64_t Res = (InputValue >> ExtractedElt) & 1;
24157 return DAG.getConstant(Res, dl, MVT::i1);
24159 // Only operate on vectors of 4 elements, where the alternative shuffling
24160 // gets to be more expensive.
24161 if (InputVector.getValueType() != MVT::v4i32)
24164 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24165 // single use which is a sign-extend or zero-extend, and all elements are
24167 SmallVector<SDNode *, 4> Uses;
24168 unsigned ExtractedElements = 0;
24169 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24170 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24171 if (UI.getUse().getResNo() != InputVector.getResNo())
24174 SDNode *Extract = *UI;
24175 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24178 if (Extract->getValueType(0) != MVT::i32)
24180 if (!Extract->hasOneUse())
24182 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24183 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24185 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24188 // Record which element was extracted.
24189 ExtractedElements |=
24190 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24192 Uses.push_back(Extract);
24195 // If not all the elements were used, this may not be worthwhile.
24196 if (ExtractedElements != 15)
24199 // Ok, we've now decided to do the transformation.
24200 // If 64-bit shifts are legal, use the extract-shift sequence,
24201 // otherwise bounce the vector off the cache.
24202 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24205 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24206 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24207 auto &DL = DAG.getDataLayout();
24208 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24209 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24210 DAG.getConstant(0, dl, VecIdxTy));
24211 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24212 DAG.getConstant(1, dl, VecIdxTy));
24214 SDValue ShAmt = DAG.getConstant(
24215 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24216 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24217 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24218 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24219 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24220 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24221 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24223 // Store the value to a temporary stack slot.
24224 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24225 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24226 MachinePointerInfo(), false, false, 0);
24228 EVT ElementType = InputVector.getValueType().getVectorElementType();
24229 unsigned EltSize = ElementType.getSizeInBits() / 8;
24231 // Replace each use (extract) with a load of the appropriate element.
24232 for (unsigned i = 0; i < 4; ++i) {
24233 uint64_t Offset = EltSize * i;
24234 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24235 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24237 SDValue ScalarAddr =
24238 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24240 // Load the scalar.
24241 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24242 ScalarAddr, MachinePointerInfo(),
24243 false, false, false, 0);
24248 // Replace the extracts
24249 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24250 UE = Uses.end(); UI != UE; ++UI) {
24251 SDNode *Extract = *UI;
24253 SDValue Idx = Extract->getOperand(1);
24254 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24255 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24258 // The replacement was made in place; don't return anything.
24263 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24264 const X86Subtarget *Subtarget) {
24266 SDValue Cond = N->getOperand(0);
24267 SDValue LHS = N->getOperand(1);
24268 SDValue RHS = N->getOperand(2);
24270 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24271 SDValue CondSrc = Cond->getOperand(0);
24272 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24273 Cond = CondSrc->getOperand(0);
24276 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24279 // A vselect where all conditions and data are constants can be optimized into
24280 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24281 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24282 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24285 unsigned MaskValue = 0;
24286 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24289 MVT VT = N->getSimpleValueType(0);
24290 unsigned NumElems = VT.getVectorNumElements();
24291 SmallVector<int, 8> ShuffleMask(NumElems, -1);
24292 for (unsigned i = 0; i < NumElems; ++i) {
24293 // Be sure we emit undef where we can.
24294 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24295 ShuffleMask[i] = -1;
24297 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24300 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24301 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24303 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24306 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24308 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24309 TargetLowering::DAGCombinerInfo &DCI,
24310 const X86Subtarget *Subtarget) {
24312 SDValue Cond = N->getOperand(0);
24313 // Get the LHS/RHS of the select.
24314 SDValue LHS = N->getOperand(1);
24315 SDValue RHS = N->getOperand(2);
24316 EVT VT = LHS.getValueType();
24317 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24319 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24320 // instructions match the semantics of the common C idiom x<y?x:y but not
24321 // x<=y?x:y, because of how they handle negative zero (which can be
24322 // ignored in unsafe-math mode).
24323 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24324 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24325 VT != MVT::f80 && VT != MVT::f128 &&
24326 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24327 (Subtarget->hasSSE2() ||
24328 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24329 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24331 unsigned Opcode = 0;
24332 // Check for x CC y ? x : y.
24333 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24334 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24338 // Converting this to a min would handle NaNs incorrectly, and swapping
24339 // the operands would cause it to handle comparisons between positive
24340 // and negative zero incorrectly.
24341 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24342 if (!DAG.getTarget().Options.UnsafeFPMath &&
24343 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24345 std::swap(LHS, RHS);
24347 Opcode = X86ISD::FMIN;
24350 // Converting this to a min would handle comparisons between positive
24351 // and negative zero incorrectly.
24352 if (!DAG.getTarget().Options.UnsafeFPMath &&
24353 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24355 Opcode = X86ISD::FMIN;
24358 // Converting this to a min would handle both negative zeros and NaNs
24359 // incorrectly, but we can swap the operands to fix both.
24360 std::swap(LHS, RHS);
24364 Opcode = X86ISD::FMIN;
24368 // Converting this to a max would handle comparisons between positive
24369 // and negative zero incorrectly.
24370 if (!DAG.getTarget().Options.UnsafeFPMath &&
24371 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24373 Opcode = X86ISD::FMAX;
24376 // Converting this to a max would handle NaNs incorrectly, and swapping
24377 // the operands would cause it to handle comparisons between positive
24378 // and negative zero incorrectly.
24379 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24380 if (!DAG.getTarget().Options.UnsafeFPMath &&
24381 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24383 std::swap(LHS, RHS);
24385 Opcode = X86ISD::FMAX;
24388 // Converting this to a max would handle both negative zeros and NaNs
24389 // incorrectly, but we can swap the operands to fix both.
24390 std::swap(LHS, RHS);
24394 Opcode = X86ISD::FMAX;
24397 // Check for x CC y ? y : x -- a min/max with reversed arms.
24398 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24399 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24403 // Converting this to a min would handle comparisons between positive
24404 // and negative zero incorrectly, and swapping the operands would
24405 // cause it to handle NaNs incorrectly.
24406 if (!DAG.getTarget().Options.UnsafeFPMath &&
24407 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24408 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24410 std::swap(LHS, RHS);
24412 Opcode = X86ISD::FMIN;
24415 // Converting this to a min would handle NaNs incorrectly.
24416 if (!DAG.getTarget().Options.UnsafeFPMath &&
24417 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24419 Opcode = X86ISD::FMIN;
24422 // Converting this to a min would handle both negative zeros and NaNs
24423 // incorrectly, but we can swap the operands to fix both.
24424 std::swap(LHS, RHS);
24428 Opcode = X86ISD::FMIN;
24432 // Converting this to a max would handle NaNs incorrectly.
24433 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24435 Opcode = X86ISD::FMAX;
24438 // Converting this to a max would handle comparisons between positive
24439 // and negative zero incorrectly, and swapping the operands would
24440 // cause it to handle NaNs incorrectly.
24441 if (!DAG.getTarget().Options.UnsafeFPMath &&
24442 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24443 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24445 std::swap(LHS, RHS);
24447 Opcode = X86ISD::FMAX;
24450 // Converting this to a max would handle both negative zeros and NaNs
24451 // incorrectly, but we can swap the operands to fix both.
24452 std::swap(LHS, RHS);
24456 Opcode = X86ISD::FMAX;
24462 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24465 EVT CondVT = Cond.getValueType();
24466 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24467 CondVT.getVectorElementType() == MVT::i1) {
24468 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24469 // lowering on KNL. In this case we convert it to
24470 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24471 // The same situation for all 128 and 256-bit vectors of i8 and i16.
24472 // Since SKX these selects have a proper lowering.
24473 EVT OpVT = LHS.getValueType();
24474 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24475 (OpVT.getVectorElementType() == MVT::i8 ||
24476 OpVT.getVectorElementType() == MVT::i16) &&
24477 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24478 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24479 DCI.AddToWorklist(Cond.getNode());
24480 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24483 // If this is a select between two integer constants, try to do some
24485 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24486 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24487 // Don't do this for crazy integer types.
24488 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24489 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24490 // so that TrueC (the true value) is larger than FalseC.
24491 bool NeedsCondInvert = false;
24493 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24494 // Efficiently invertible.
24495 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
24496 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
24497 isa<ConstantSDNode>(Cond.getOperand(1))))) {
24498 NeedsCondInvert = true;
24499 std::swap(TrueC, FalseC);
24502 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
24503 if (FalseC->getAPIntValue() == 0 &&
24504 TrueC->getAPIntValue().isPowerOf2()) {
24505 if (NeedsCondInvert) // Invert the condition if needed.
24506 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24507 DAG.getConstant(1, DL, Cond.getValueType()));
24509 // Zero extend the condition if needed.
24510 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24512 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24513 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24514 DAG.getConstant(ShAmt, DL, MVT::i8));
24517 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24518 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24519 if (NeedsCondInvert) // Invert the condition if needed.
24520 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24521 DAG.getConstant(1, DL, Cond.getValueType()));
24523 // Zero extend the condition if needed.
24524 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24525 FalseC->getValueType(0), Cond);
24526 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24527 SDValue(FalseC, 0));
24530 // Optimize cases that will turn into an LEA instruction. This requires
24531 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24532 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24533 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24534 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24536 bool isFastMultiplier = false;
24538 switch ((unsigned char)Diff) {
24540 case 1: // result = add base, cond
24541 case 2: // result = lea base( , cond*2)
24542 case 3: // result = lea base(cond, cond*2)
24543 case 4: // result = lea base( , cond*4)
24544 case 5: // result = lea base(cond, cond*4)
24545 case 8: // result = lea base( , cond*8)
24546 case 9: // result = lea base(cond, cond*8)
24547 isFastMultiplier = true;
24552 if (isFastMultiplier) {
24553 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24554 if (NeedsCondInvert) // Invert the condition if needed.
24555 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24556 DAG.getConstant(1, DL, Cond.getValueType()));
24558 // Zero extend the condition if needed.
24559 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24561 // Scale the condition by the difference.
24563 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24564 DAG.getConstant(Diff, DL,
24565 Cond.getValueType()));
24567 // Add the base if non-zero.
24568 if (FalseC->getAPIntValue() != 0)
24569 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24570 SDValue(FalseC, 0));
24577 // Canonicalize max and min:
24578 // (x > y) ? x : y -> (x >= y) ? x : y
24579 // (x < y) ? x : y -> (x <= y) ? x : y
24580 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24581 // the need for an extra compare
24582 // against zero. e.g.
24583 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24585 // testl %edi, %edi
24587 // cmovgl %edi, %eax
24591 // cmovsl %eax, %edi
24592 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24593 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24594 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24595 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24600 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24601 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24602 Cond.getOperand(0), Cond.getOperand(1), NewCC);
24603 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24608 // Early exit check
24609 if (!TLI.isTypeLegal(VT))
24612 // Match VSELECTs into subs with unsigned saturation.
24613 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24614 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24615 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24616 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24617 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24619 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24620 // left side invert the predicate to simplify logic below.
24622 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24624 CC = ISD::getSetCCInverse(CC, true);
24625 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24629 if (Other.getNode() && Other->getNumOperands() == 2 &&
24630 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24631 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24632 SDValue CondRHS = Cond->getOperand(1);
24634 // Look for a general sub with unsigned saturation first.
24635 // x >= y ? x-y : 0 --> subus x, y
24636 // x > y ? x-y : 0 --> subus x, y
24637 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24638 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24639 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24641 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24642 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24643 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24644 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24645 // If the RHS is a constant we have to reverse the const
24646 // canonicalization.
24647 // x > C-1 ? x+-C : 0 --> subus x, C
24648 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24649 CondRHSConst->getAPIntValue() ==
24650 (-OpRHSConst->getAPIntValue() - 1))
24651 return DAG.getNode(
24652 X86ISD::SUBUS, DL, VT, OpLHS,
24653 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24655 // Another special case: If C was a sign bit, the sub has been
24656 // canonicalized into a xor.
24657 // FIXME: Would it be better to use computeKnownBits to determine
24658 // whether it's safe to decanonicalize the xor?
24659 // x s< 0 ? x^C : 0 --> subus x, C
24660 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24661 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24662 OpRHSConst->getAPIntValue().isSignBit())
24663 // Note that we have to rebuild the RHS constant here to ensure we
24664 // don't rely on particular values of undef lanes.
24665 return DAG.getNode(
24666 X86ISD::SUBUS, DL, VT, OpLHS,
24667 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24672 // Simplify vector selection if condition value type matches vselect
24674 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24675 assert(Cond.getValueType().isVector() &&
24676 "vector select expects a vector selector!");
24678 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24679 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24681 // Try invert the condition if true value is not all 1s and false value
24683 if (!TValIsAllOnes && !FValIsAllZeros &&
24684 // Check if the selector will be produced by CMPP*/PCMP*
24685 Cond.getOpcode() == ISD::SETCC &&
24686 // Check if SETCC has already been promoted
24687 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24689 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24690 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24692 if (TValIsAllZeros || FValIsAllOnes) {
24693 SDValue CC = Cond.getOperand(2);
24694 ISD::CondCode NewCC =
24695 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24696 Cond.getOperand(0).getValueType().isInteger());
24697 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24698 std::swap(LHS, RHS);
24699 TValIsAllOnes = FValIsAllOnes;
24700 FValIsAllZeros = TValIsAllZeros;
24704 if (TValIsAllOnes || FValIsAllZeros) {
24707 if (TValIsAllOnes && FValIsAllZeros)
24709 else if (TValIsAllOnes)
24711 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24712 else if (FValIsAllZeros)
24713 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24714 DAG.getBitcast(CondVT, LHS));
24716 return DAG.getBitcast(VT, Ret);
24720 // We should generate an X86ISD::BLENDI from a vselect if its argument
24721 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24722 // constants. This specific pattern gets generated when we split a
24723 // selector for a 512 bit vector in a machine without AVX512 (but with
24724 // 256-bit vectors), during legalization:
24726 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24728 // Iff we find this pattern and the build_vectors are built from
24729 // constants, we translate the vselect into a shuffle_vector that we
24730 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24731 if ((N->getOpcode() == ISD::VSELECT ||
24732 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24733 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24734 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24735 if (Shuffle.getNode())
24739 // If this is a *dynamic* select (non-constant condition) and we can match
24740 // this node with one of the variable blend instructions, restructure the
24741 // condition so that the blends can use the high bit of each element and use
24742 // SimplifyDemandedBits to simplify the condition operand.
24743 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24744 !DCI.isBeforeLegalize() &&
24745 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24746 unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24748 // Don't optimize vector selects that map to mask-registers.
24752 // We can only handle the cases where VSELECT is directly legal on the
24753 // subtarget. We custom lower VSELECT nodes with constant conditions and
24754 // this makes it hard to see whether a dynamic VSELECT will correctly
24755 // lower, so we both check the operation's status and explicitly handle the
24756 // cases where a *dynamic* blend will fail even though a constant-condition
24757 // blend could be custom lowered.
24758 // FIXME: We should find a better way to handle this class of problems.
24759 // Potentially, we should combine constant-condition vselect nodes
24760 // pre-legalization into shuffles and not mark as many types as custom
24762 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24764 // FIXME: We don't support i16-element blends currently. We could and
24765 // should support them by making *all* the bits in the condition be set
24766 // rather than just the high bit and using an i8-element blend.
24767 if (VT.getVectorElementType() == MVT::i16)
24769 // Dynamic blending was only available from SSE4.1 onward.
24770 if (VT.is128BitVector() && !Subtarget->hasSSE41())
24772 // Byte blends are only available in AVX2
24773 if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24776 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24777 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24779 APInt KnownZero, KnownOne;
24780 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24781 DCI.isBeforeLegalizeOps());
24782 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24783 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24785 // If we changed the computation somewhere in the DAG, this change
24786 // will affect all users of Cond.
24787 // Make sure it is fine and update all the nodes so that we do not
24788 // use the generic VSELECT anymore. Otherwise, we may perform
24789 // wrong optimizations as we messed up with the actual expectation
24790 // for the vector boolean values.
24791 if (Cond != TLO.Old) {
24792 // Check all uses of that condition operand to check whether it will be
24793 // consumed by non-BLEND instructions, which may depend on all bits are
24795 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24797 if (I->getOpcode() != ISD::VSELECT)
24798 // TODO: Add other opcodes eventually lowered into BLEND.
24801 // Update all the users of the condition, before committing the change,
24802 // so that the VSELECT optimizations that expect the correct vector
24803 // boolean value will not be triggered.
24804 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24806 DAG.ReplaceAllUsesOfValueWith(
24808 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24809 Cond, I->getOperand(1), I->getOperand(2)));
24810 DCI.CommitTargetLoweringOpt(TLO);
24813 // At this point, only Cond is changed. Change the condition
24814 // just for N to keep the opportunity to optimize all other
24815 // users their own way.
24816 DAG.ReplaceAllUsesOfValueWith(
24818 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24819 TLO.New, N->getOperand(1), N->getOperand(2)));
24827 // Check whether a boolean test is testing a boolean value generated by
24828 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24831 // Simplify the following patterns:
24832 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24833 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24834 // to (Op EFLAGS Cond)
24836 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24837 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24838 // to (Op EFLAGS !Cond)
24840 // where Op could be BRCOND or CMOV.
24842 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24843 // Quit if not CMP and SUB with its value result used.
24844 if (Cmp.getOpcode() != X86ISD::CMP &&
24845 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24848 // Quit if not used as a boolean value.
24849 if (CC != X86::COND_E && CC != X86::COND_NE)
24852 // Check CMP operands. One of them should be 0 or 1 and the other should be
24853 // an SetCC or extended from it.
24854 SDValue Op1 = Cmp.getOperand(0);
24855 SDValue Op2 = Cmp.getOperand(1);
24858 const ConstantSDNode* C = nullptr;
24859 bool needOppositeCond = (CC == X86::COND_E);
24860 bool checkAgainstTrue = false; // Is it a comparison against 1?
24862 if ((C = dyn_cast<ConstantSDNode>(Op1)))
24864 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24866 else // Quit if all operands are not constants.
24869 if (C->getZExtValue() == 1) {
24870 needOppositeCond = !needOppositeCond;
24871 checkAgainstTrue = true;
24872 } else if (C->getZExtValue() != 0)
24873 // Quit if the constant is neither 0 or 1.
24876 bool truncatedToBoolWithAnd = false;
24877 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24878 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24879 SetCC.getOpcode() == ISD::TRUNCATE ||
24880 SetCC.getOpcode() == ISD::AND) {
24881 if (SetCC.getOpcode() == ISD::AND) {
24883 if (isOneConstant(SetCC.getOperand(0)))
24885 if (isOneConstant(SetCC.getOperand(1)))
24889 SetCC = SetCC.getOperand(OpIdx);
24890 truncatedToBoolWithAnd = true;
24892 SetCC = SetCC.getOperand(0);
24895 switch (SetCC.getOpcode()) {
24896 case X86ISD::SETCC_CARRY:
24897 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24898 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24899 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24900 // truncated to i1 using 'and'.
24901 if (checkAgainstTrue && !truncatedToBoolWithAnd)
24903 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24904 "Invalid use of SETCC_CARRY!");
24906 case X86ISD::SETCC:
24907 // Set the condition code or opposite one if necessary.
24908 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24909 if (needOppositeCond)
24910 CC = X86::GetOppositeBranchCondition(CC);
24911 return SetCC.getOperand(1);
24912 case X86ISD::CMOV: {
24913 // Check whether false/true value has canonical one, i.e. 0 or 1.
24914 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24915 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24916 // Quit if true value is not a constant.
24919 // Quit if false value is not a constant.
24921 SDValue Op = SetCC.getOperand(0);
24922 // Skip 'zext' or 'trunc' node.
24923 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24924 Op.getOpcode() == ISD::TRUNCATE)
24925 Op = Op.getOperand(0);
24926 // A special case for rdrand/rdseed, where 0 is set if false cond is
24928 if ((Op.getOpcode() != X86ISD::RDRAND &&
24929 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24932 // Quit if false value is not the constant 0 or 1.
24933 bool FValIsFalse = true;
24934 if (FVal && FVal->getZExtValue() != 0) {
24935 if (FVal->getZExtValue() != 1)
24937 // If FVal is 1, opposite cond is needed.
24938 needOppositeCond = !needOppositeCond;
24939 FValIsFalse = false;
24941 // Quit if TVal is not the constant opposite of FVal.
24942 if (FValIsFalse && TVal->getZExtValue() != 1)
24944 if (!FValIsFalse && TVal->getZExtValue() != 0)
24946 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24947 if (needOppositeCond)
24948 CC = X86::GetOppositeBranchCondition(CC);
24949 return SetCC.getOperand(3);
24956 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24958 /// (X86or (X86setcc) (X86setcc))
24959 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
24960 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24961 X86::CondCode &CC1, SDValue &Flags,
24963 if (Cond->getOpcode() == X86ISD::CMP) {
24964 if (!isNullConstant(Cond->getOperand(1)))
24967 Cond = Cond->getOperand(0);
24972 SDValue SetCC0, SetCC1;
24973 switch (Cond->getOpcode()) {
24974 default: return false;
24981 SetCC0 = Cond->getOperand(0);
24982 SetCC1 = Cond->getOperand(1);
24986 // Make sure we have SETCC nodes, using the same flags value.
24987 if (SetCC0.getOpcode() != X86ISD::SETCC ||
24988 SetCC1.getOpcode() != X86ISD::SETCC ||
24989 SetCC0->getOperand(1) != SetCC1->getOperand(1))
24992 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24993 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24994 Flags = SetCC0->getOperand(1);
24998 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24999 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
25000 TargetLowering::DAGCombinerInfo &DCI,
25001 const X86Subtarget *Subtarget) {
25004 // If the flag operand isn't dead, don't touch this CMOV.
25005 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
25008 SDValue FalseOp = N->getOperand(0);
25009 SDValue TrueOp = N->getOperand(1);
25010 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
25011 SDValue Cond = N->getOperand(3);
25013 if (CC == X86::COND_E || CC == X86::COND_NE) {
25014 switch (Cond.getOpcode()) {
25018 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
25019 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
25020 return (CC == X86::COND_E) ? FalseOp : TrueOp;
25026 Flags = checkBoolTestSetCCCombine(Cond, CC);
25027 if (Flags.getNode() &&
25028 // Extra check as FCMOV only supports a subset of X86 cond.
25029 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
25030 SDValue Ops[] = { FalseOp, TrueOp,
25031 DAG.getConstant(CC, DL, MVT::i8), Flags };
25032 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25035 // If this is a select between two integer constants, try to do some
25036 // optimizations. Note that the operands are ordered the opposite of SELECT
25038 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
25039 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
25040 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
25041 // larger than FalseC (the false value).
25042 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
25043 CC = X86::GetOppositeBranchCondition(CC);
25044 std::swap(TrueC, FalseC);
25045 std::swap(TrueOp, FalseOp);
25048 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
25049 // This is efficient for any integer data type (including i8/i16) and
25051 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
25052 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25053 DAG.getConstant(CC, DL, MVT::i8), Cond);
25055 // Zero extend the condition if needed.
25056 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
25058 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
25059 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
25060 DAG.getConstant(ShAmt, DL, MVT::i8));
25061 if (N->getNumValues() == 2) // Dead flag value?
25062 return DCI.CombineTo(N, Cond, SDValue());
25066 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
25067 // for any integer data type, including i8/i16.
25068 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
25069 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25070 DAG.getConstant(CC, DL, MVT::i8), Cond);
25072 // Zero extend the condition if needed.
25073 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
25074 FalseC->getValueType(0), Cond);
25075 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25076 SDValue(FalseC, 0));
25078 if (N->getNumValues() == 2) // Dead flag value?
25079 return DCI.CombineTo(N, Cond, SDValue());
25083 // Optimize cases that will turn into an LEA instruction. This requires
25084 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
25085 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
25086 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
25087 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
25089 bool isFastMultiplier = false;
25091 switch ((unsigned char)Diff) {
25093 case 1: // result = add base, cond
25094 case 2: // result = lea base( , cond*2)
25095 case 3: // result = lea base(cond, cond*2)
25096 case 4: // result = lea base( , cond*4)
25097 case 5: // result = lea base(cond, cond*4)
25098 case 8: // result = lea base( , cond*8)
25099 case 9: // result = lea base(cond, cond*8)
25100 isFastMultiplier = true;
25105 if (isFastMultiplier) {
25106 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25107 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25108 DAG.getConstant(CC, DL, MVT::i8), Cond);
25109 // Zero extend the condition if needed.
25110 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25112 // Scale the condition by the difference.
25114 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25115 DAG.getConstant(Diff, DL, Cond.getValueType()));
25117 // Add the base if non-zero.
25118 if (FalseC->getAPIntValue() != 0)
25119 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25120 SDValue(FalseC, 0));
25121 if (N->getNumValues() == 2) // Dead flag value?
25122 return DCI.CombineTo(N, Cond, SDValue());
25129 // Handle these cases:
25130 // (select (x != c), e, c) -> select (x != c), e, x),
25131 // (select (x == c), c, e) -> select (x == c), x, e)
25132 // where the c is an integer constant, and the "select" is the combination
25133 // of CMOV and CMP.
25135 // The rationale for this change is that the conditional-move from a constant
25136 // needs two instructions, however, conditional-move from a register needs
25137 // only one instruction.
25139 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25140 // some instruction-combining opportunities. This opt needs to be
25141 // postponed as late as possible.
25143 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25144 // the DCI.xxxx conditions are provided to postpone the optimization as
25145 // late as possible.
25147 ConstantSDNode *CmpAgainst = nullptr;
25148 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25149 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25150 !isa<ConstantSDNode>(Cond.getOperand(0))) {
25152 if (CC == X86::COND_NE &&
25153 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25154 CC = X86::GetOppositeBranchCondition(CC);
25155 std::swap(TrueOp, FalseOp);
25158 if (CC == X86::COND_E &&
25159 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25160 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25161 DAG.getConstant(CC, DL, MVT::i8), Cond };
25162 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25167 // Fold and/or of setcc's to double CMOV:
25168 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25169 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25171 // This combine lets us generate:
25172 // cmovcc1 (jcc1 if we don't have CMOV)
25178 // cmovne (jne if we don't have CMOV)
25179 // When we can't use the CMOV instruction, it might increase branch
25181 // When we can use CMOV, or when there is no mispredict, this improves
25182 // throughput and reduces register pressure.
25184 if (CC == X86::COND_NE) {
25186 X86::CondCode CC0, CC1;
25188 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25190 std::swap(FalseOp, TrueOp);
25191 CC0 = X86::GetOppositeBranchCondition(CC0);
25192 CC1 = X86::GetOppositeBranchCondition(CC1);
25195 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25197 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25198 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25199 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25200 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25208 /// PerformMulCombine - Optimize a single multiply with constant into two
25209 /// in order to implement it with two cheaper instructions, e.g.
25210 /// LEA + SHL, LEA + LEA.
25211 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25212 TargetLowering::DAGCombinerInfo &DCI) {
25213 // An imul is usually smaller than the alternative sequence.
25214 if (DAG.getMachineFunction().getFunction()->optForMinSize())
25217 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25220 EVT VT = N->getValueType(0);
25221 if (VT != MVT::i64 && VT != MVT::i32)
25224 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25227 uint64_t MulAmt = C->getZExtValue();
25228 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25231 uint64_t MulAmt1 = 0;
25232 uint64_t MulAmt2 = 0;
25233 if ((MulAmt % 9) == 0) {
25235 MulAmt2 = MulAmt / 9;
25236 } else if ((MulAmt % 5) == 0) {
25238 MulAmt2 = MulAmt / 5;
25239 } else if ((MulAmt % 3) == 0) {
25241 MulAmt2 = MulAmt / 3;
25247 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25249 if (isPowerOf2_64(MulAmt2) &&
25250 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25251 // If second multiplifer is pow2, issue it first. We want the multiply by
25252 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25254 std::swap(MulAmt1, MulAmt2);
25256 if (isPowerOf2_64(MulAmt1))
25257 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25258 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25260 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25261 DAG.getConstant(MulAmt1, DL, VT));
25263 if (isPowerOf2_64(MulAmt2))
25264 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25265 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25267 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25268 DAG.getConstant(MulAmt2, DL, VT));
25272 assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25273 && "Both cases that could cause potential overflows should have "
25274 "already been handled.");
25275 if (isPowerOf2_64(MulAmt - 1))
25276 // (mul x, 2^N + 1) => (add (shl x, N), x)
25277 NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25278 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25279 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25282 else if (isPowerOf2_64(MulAmt + 1))
25283 // (mul x, 2^N - 1) => (sub (shl x, N), x)
25284 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25286 DAG.getConstant(Log2_64(MulAmt + 1),
25287 DL, MVT::i8)), N->getOperand(0));
25291 // Do not add new nodes to DAG combiner worklist.
25292 DCI.CombineTo(N, NewMul, false);
25297 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25298 SDValue N0 = N->getOperand(0);
25299 SDValue N1 = N->getOperand(1);
25300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25301 EVT VT = N0.getValueType();
25303 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25304 // since the result of setcc_c is all zero's or all ones.
25305 if (VT.isInteger() && !VT.isVector() &&
25306 N1C && N0.getOpcode() == ISD::AND &&
25307 N0.getOperand(1).getOpcode() == ISD::Constant) {
25308 SDValue N00 = N0.getOperand(0);
25309 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25310 APInt ShAmt = N1C->getAPIntValue();
25311 Mask = Mask.shl(ShAmt);
25312 bool MaskOK = false;
25313 // We can handle cases concerning bit-widening nodes containing setcc_c if
25314 // we carefully interrogate the mask to make sure we are semantics
25316 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25317 // of the underlying setcc_c operation if the setcc_c was zero extended.
25318 // Consider the following example:
25319 // zext(setcc_c) -> i32 0x0000FFFF
25320 // c1 -> i32 0x0000FFFF
25321 // c2 -> i32 0x00000001
25322 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25323 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
25324 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25326 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25327 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25329 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25330 N00.getOpcode() == ISD::ANY_EXTEND) &&
25331 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25332 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25334 if (MaskOK && Mask != 0) {
25336 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25340 // Hardware support for vector shifts is sparse which makes us scalarize the
25341 // vector operations in many cases. Also, on sandybridge ADD is faster than
25343 // (shl V, 1) -> add V,V
25344 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25345 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25346 assert(N0.getValueType().isVector() && "Invalid vector shift type");
25347 // We shift all of the values by one. In many cases we do not have
25348 // hardware support for this operation. This is better expressed as an ADD
25350 if (N1SplatC->getAPIntValue() == 1)
25351 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25357 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25358 SDValue N0 = N->getOperand(0);
25359 SDValue N1 = N->getOperand(1);
25360 EVT VT = N0.getValueType();
25361 unsigned Size = VT.getSizeInBits();
25363 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25364 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25365 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25366 // depending on sign of (SarConst - [56,48,32,24,16])
25368 // sexts in X86 are MOVs. The MOVs have the same code size
25369 // as above SHIFTs (only SHIFT on 1 has lower code size).
25370 // However the MOVs have 2 advantages to a SHIFT:
25371 // 1. MOVs can write to a register that differs from source
25372 // 2. MOVs accept memory operands
25374 if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25375 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25376 N0.getOperand(1).getOpcode() != ISD::Constant)
25379 SDValue N00 = N0.getOperand(0);
25380 SDValue N01 = N0.getOperand(1);
25381 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25382 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25383 EVT CVT = N1.getValueType();
25385 if (SarConst.isNegative())
25388 for (MVT SVT : MVT::integer_valuetypes()) {
25389 unsigned ShiftSize = SVT.getSizeInBits();
25390 // skipping types without corresponding sext/zext and
25391 // ShlConst that is not one of [56,48,32,24,16]
25392 if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25396 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25397 SarConst = SarConst - (Size - ShiftSize);
25400 else if (SarConst.isNegative())
25401 return DAG.getNode(ISD::SHL, DL, VT, NN,
25402 DAG.getConstant(-SarConst, DL, CVT));
25404 return DAG.getNode(ISD::SRA, DL, VT, NN,
25405 DAG.getConstant(SarConst, DL, CVT));
25410 /// \brief Returns a vector of 0s if the node in input is a vector logical
25411 /// shift by a constant amount which is known to be bigger than or equal
25412 /// to the vector element size in bits.
25413 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25414 const X86Subtarget *Subtarget) {
25415 EVT VT = N->getValueType(0);
25417 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25418 (!Subtarget->hasInt256() ||
25419 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25422 SDValue Amt = N->getOperand(1);
25424 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25425 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25426 APInt ShiftAmt = AmtSplat->getAPIntValue();
25427 unsigned MaxAmount =
25428 VT.getSimpleVT().getVectorElementType().getSizeInBits();
25430 // SSE2/AVX2 logical shifts always return a vector of 0s
25431 // if the shift amount is bigger than or equal to
25432 // the element size. The constant shift amount will be
25433 // encoded as a 8-bit immediate.
25434 if (ShiftAmt.trunc(8).uge(MaxAmount))
25435 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25441 /// PerformShiftCombine - Combine shifts.
25442 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25443 TargetLowering::DAGCombinerInfo &DCI,
25444 const X86Subtarget *Subtarget) {
25445 if (N->getOpcode() == ISD::SHL)
25446 if (SDValue V = PerformSHLCombine(N, DAG))
25449 if (N->getOpcode() == ISD::SRA)
25450 if (SDValue V = PerformSRACombine(N, DAG))
25453 // Try to fold this logical shift into a zero vector.
25454 if (N->getOpcode() != ISD::SRA)
25455 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25461 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
25462 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25463 // and friends. Likewise for OR -> CMPNEQSS.
25464 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25465 TargetLowering::DAGCombinerInfo &DCI,
25466 const X86Subtarget *Subtarget) {
25469 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25470 // we're requiring SSE2 for both.
25471 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25472 SDValue N0 = N->getOperand(0);
25473 SDValue N1 = N->getOperand(1);
25474 SDValue CMP0 = N0->getOperand(1);
25475 SDValue CMP1 = N1->getOperand(1);
25478 // The SETCCs should both refer to the same CMP.
25479 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25482 SDValue CMP00 = CMP0->getOperand(0);
25483 SDValue CMP01 = CMP0->getOperand(1);
25484 EVT VT = CMP00.getValueType();
25486 if (VT == MVT::f32 || VT == MVT::f64) {
25487 bool ExpectingFlags = false;
25488 // Check for any users that want flags:
25489 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25490 !ExpectingFlags && UI != UE; ++UI)
25491 switch (UI->getOpcode()) {
25496 ExpectingFlags = true;
25498 case ISD::CopyToReg:
25499 case ISD::SIGN_EXTEND:
25500 case ISD::ZERO_EXTEND:
25501 case ISD::ANY_EXTEND:
25505 if (!ExpectingFlags) {
25506 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25507 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25509 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25510 X86::CondCode tmp = cc0;
25515 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
25516 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25517 // FIXME: need symbolic constants for these magic numbers.
25518 // See X86ATTInstPrinter.cpp:printSSECC().
25519 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25520 if (Subtarget->hasAVX512()) {
25521 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25523 DAG.getConstant(x86cc, DL, MVT::i8));
25524 if (N->getValueType(0) != MVT::i1)
25525 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25529 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25530 CMP00.getValueType(), CMP00, CMP01,
25531 DAG.getConstant(x86cc, DL,
25534 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25535 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25537 if (is64BitFP && !Subtarget->is64Bit()) {
25538 // On a 32-bit target, we cannot bitcast the 64-bit float to a
25539 // 64-bit integer, since that's not a legal type. Since
25540 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25541 // bits, but can do this little dance to extract the lowest 32 bits
25542 // and work with those going forward.
25543 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25545 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25546 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25547 Vector32, DAG.getIntPtrConstant(0, DL));
25551 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25552 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25553 DAG.getConstant(1, DL, IntVT));
25554 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25556 return OneBitOfTruth;
25564 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25565 /// so it can be folded inside ANDNP.
25566 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25567 EVT VT = N->getValueType(0);
25569 // Match direct AllOnes for 128 and 256-bit vectors
25570 if (ISD::isBuildVectorAllOnes(N))
25573 // Look through a bit convert.
25574 if (N->getOpcode() == ISD::BITCAST)
25575 N = N->getOperand(0).getNode();
25577 // Sometimes the operand may come from a insert_subvector building a 256-bit
25579 if (VT.is256BitVector() &&
25580 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25581 SDValue V1 = N->getOperand(0);
25582 SDValue V2 = N->getOperand(1);
25584 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25585 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25586 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25587 ISD::isBuildVectorAllOnes(V2.getNode()))
25594 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25595 // register. In most cases we actually compare or select YMM-sized registers
25596 // and mixing the two types creates horrible code. This method optimizes
25597 // some of the transition sequences.
25598 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25599 TargetLowering::DAGCombinerInfo &DCI,
25600 const X86Subtarget *Subtarget) {
25601 EVT VT = N->getValueType(0);
25602 if (!VT.is256BitVector())
25605 assert((N->getOpcode() == ISD::ANY_EXTEND ||
25606 N->getOpcode() == ISD::ZERO_EXTEND ||
25607 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25609 SDValue Narrow = N->getOperand(0);
25610 EVT NarrowVT = Narrow->getValueType(0);
25611 if (!NarrowVT.is128BitVector())
25614 if (Narrow->getOpcode() != ISD::XOR &&
25615 Narrow->getOpcode() != ISD::AND &&
25616 Narrow->getOpcode() != ISD::OR)
25619 SDValue N0 = Narrow->getOperand(0);
25620 SDValue N1 = Narrow->getOperand(1);
25623 // The Left side has to be a trunc.
25624 if (N0.getOpcode() != ISD::TRUNCATE)
25627 // The type of the truncated inputs.
25628 EVT WideVT = N0->getOperand(0)->getValueType(0);
25632 // The right side has to be a 'trunc' or a constant vector.
25633 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25634 ConstantSDNode *RHSConstSplat = nullptr;
25635 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25636 RHSConstSplat = RHSBV->getConstantSplatNode();
25637 if (!RHSTrunc && !RHSConstSplat)
25640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25642 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25645 // Set N0 and N1 to hold the inputs to the new wide operation.
25646 N0 = N0->getOperand(0);
25647 if (RHSConstSplat) {
25648 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25649 SDValue(RHSConstSplat, 0));
25650 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25651 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25652 } else if (RHSTrunc) {
25653 N1 = N1->getOperand(0);
25656 // Generate the wide operation.
25657 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25658 unsigned Opcode = N->getOpcode();
25660 case ISD::ANY_EXTEND:
25662 case ISD::ZERO_EXTEND: {
25663 unsigned InBits = NarrowVT.getScalarSizeInBits();
25664 APInt Mask = APInt::getAllOnesValue(InBits);
25665 Mask = Mask.zext(VT.getScalarSizeInBits());
25666 return DAG.getNode(ISD::AND, DL, VT,
25667 Op, DAG.getConstant(Mask, DL, VT));
25669 case ISD::SIGN_EXTEND:
25670 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25671 Op, DAG.getValueType(NarrowVT));
25673 llvm_unreachable("Unexpected opcode");
25677 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25678 TargetLowering::DAGCombinerInfo &DCI,
25679 const X86Subtarget *Subtarget) {
25680 SDValue N0 = N->getOperand(0);
25681 SDValue N1 = N->getOperand(1);
25684 // A vector zext_in_reg may be represented as a shuffle,
25685 // feeding into a bitcast (this represents anyext) feeding into
25686 // an and with a mask.
25687 // We'd like to try to combine that into a shuffle with zero
25688 // plus a bitcast, removing the and.
25689 if (N0.getOpcode() != ISD::BITCAST ||
25690 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25693 // The other side of the AND should be a splat of 2^C, where C
25694 // is the number of bits in the source type.
25695 if (N1.getOpcode() == ISD::BITCAST)
25696 N1 = N1.getOperand(0);
25697 if (N1.getOpcode() != ISD::BUILD_VECTOR)
25699 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25701 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25702 EVT SrcType = Shuffle->getValueType(0);
25704 // We expect a single-source shuffle
25705 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25708 unsigned SrcSize = SrcType.getScalarSizeInBits();
25710 APInt SplatValue, SplatUndef;
25711 unsigned SplatBitSize;
25713 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25714 SplatBitSize, HasAnyUndefs))
25717 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25718 // Make sure the splat matches the mask we expect
25719 if (SplatBitSize > ResSize ||
25720 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25723 // Make sure the input and output size make sense
25724 if (SrcSize >= ResSize || ResSize % SrcSize)
25727 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25728 // The number of u's between each two values depends on the ratio between
25729 // the source and dest type.
25730 unsigned ZextRatio = ResSize / SrcSize;
25731 bool IsZext = true;
25732 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25733 if (i % ZextRatio) {
25734 if (Shuffle->getMaskElt(i) > 0) {
25740 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25741 // Expected element number
25751 // Ok, perform the transformation - replace the shuffle with
25752 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25753 // (instead of undef) where the k elements come from the zero vector.
25754 SmallVector<int, 8> Mask;
25755 unsigned NumElems = SrcType.getVectorNumElements();
25756 for (unsigned i = 0; i < NumElems; ++i)
25758 Mask.push_back(NumElems);
25760 Mask.push_back(i / ZextRatio);
25762 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25763 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25764 return DAG.getBitcast(N0.getValueType(), NewShuffle);
25767 /// If both input operands of a logic op are being cast from floating point
25768 /// types, try to convert this into a floating point logic node to avoid
25769 /// unnecessary moves from SSE to integer registers.
25770 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25771 const X86Subtarget *Subtarget) {
25772 unsigned FPOpcode = ISD::DELETED_NODE;
25773 if (N->getOpcode() == ISD::AND)
25774 FPOpcode = X86ISD::FAND;
25775 else if (N->getOpcode() == ISD::OR)
25776 FPOpcode = X86ISD::FOR;
25777 else if (N->getOpcode() == ISD::XOR)
25778 FPOpcode = X86ISD::FXOR;
25780 assert(FPOpcode != ISD::DELETED_NODE &&
25781 "Unexpected input node for FP logic conversion");
25783 EVT VT = N->getValueType(0);
25784 SDValue N0 = N->getOperand(0);
25785 SDValue N1 = N->getOperand(1);
25787 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25788 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25789 (Subtarget->hasSSE2() && VT == MVT::i64))) {
25790 SDValue N00 = N0.getOperand(0);
25791 SDValue N10 = N1.getOperand(0);
25792 EVT N00Type = N00.getValueType();
25793 EVT N10Type = N10.getValueType();
25794 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25795 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25796 return DAG.getBitcast(VT, FPLogic);
25802 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25803 TargetLowering::DAGCombinerInfo &DCI,
25804 const X86Subtarget *Subtarget) {
25805 if (DCI.isBeforeLegalizeOps())
25808 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25811 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25814 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25817 EVT VT = N->getValueType(0);
25818 SDValue N0 = N->getOperand(0);
25819 SDValue N1 = N->getOperand(1);
25822 // Create BEXTR instructions
25823 // BEXTR is ((X >> imm) & (2**size-1))
25824 if (VT == MVT::i32 || VT == MVT::i64) {
25825 // Check for BEXTR.
25826 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25827 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25828 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25829 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25830 if (MaskNode && ShiftNode) {
25831 uint64_t Mask = MaskNode->getZExtValue();
25832 uint64_t Shift = ShiftNode->getZExtValue();
25833 if (isMask_64(Mask)) {
25834 uint64_t MaskSize = countPopulation(Mask);
25835 if (Shift + MaskSize <= VT.getSizeInBits())
25836 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25837 DAG.getConstant(Shift | (MaskSize << 8), DL,
25846 // Want to form ANDNP nodes:
25847 // 1) In the hopes of then easily combining them with OR and AND nodes
25848 // to form PBLEND/PSIGN.
25849 // 2) To match ANDN packed intrinsics
25850 if (VT != MVT::v2i64 && VT != MVT::v4i64)
25853 // Check LHS for vnot
25854 if (N0.getOpcode() == ISD::XOR &&
25855 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25856 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25857 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25859 // Check RHS for vnot
25860 if (N1.getOpcode() == ISD::XOR &&
25861 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25862 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25863 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25868 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25869 TargetLowering::DAGCombinerInfo &DCI,
25870 const X86Subtarget *Subtarget) {
25871 if (DCI.isBeforeLegalizeOps())
25874 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25877 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25880 SDValue N0 = N->getOperand(0);
25881 SDValue N1 = N->getOperand(1);
25882 EVT VT = N->getValueType(0);
25884 // look for psign/blend
25885 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25886 if (!Subtarget->hasSSSE3() ||
25887 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25890 // Canonicalize pandn to RHS
25891 if (N0.getOpcode() == X86ISD::ANDNP)
25893 // or (and (m, y), (pandn m, x))
25894 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25895 SDValue Mask = N1.getOperand(0);
25896 SDValue X = N1.getOperand(1);
25898 if (N0.getOperand(0) == Mask)
25899 Y = N0.getOperand(1);
25900 if (N0.getOperand(1) == Mask)
25901 Y = N0.getOperand(0);
25903 // Check to see if the mask appeared in both the AND and ANDNP and
25907 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25908 // Look through mask bitcast.
25909 if (Mask.getOpcode() == ISD::BITCAST)
25910 Mask = Mask.getOperand(0);
25911 if (X.getOpcode() == ISD::BITCAST)
25912 X = X.getOperand(0);
25913 if (Y.getOpcode() == ISD::BITCAST)
25914 Y = Y.getOperand(0);
25916 EVT MaskVT = Mask.getValueType();
25918 // Validate that the Mask operand is a vector sra node.
25919 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25920 // there is no psrai.b
25921 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25922 unsigned SraAmt = ~0;
25923 if (Mask.getOpcode() == ISD::SRA) {
25924 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25925 if (auto *AmtConst = AmtBV->getConstantSplatNode())
25926 SraAmt = AmtConst->getZExtValue();
25927 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25928 SDValue SraC = Mask.getOperand(1);
25929 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
25931 if ((SraAmt + 1) != EltBits)
25936 // Now we know we at least have a plendvb with the mask val. See if
25937 // we can form a psignb/w/d.
25938 // psign = x.type == y.type == mask.type && y = sub(0, x);
25939 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25940 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25941 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25942 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25943 "Unsupported VT for PSIGN");
25944 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25945 return DAG.getBitcast(VT, Mask);
25947 // PBLENDVB only available on SSE 4.1
25948 if (!Subtarget->hasSSE41())
25951 MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25953 X = DAG.getBitcast(BlendVT, X);
25954 Y = DAG.getBitcast(BlendVT, Y);
25955 Mask = DAG.getBitcast(BlendVT, Mask);
25956 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25957 return DAG.getBitcast(VT, Mask);
25961 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25964 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25965 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25967 // SHLD/SHRD instructions have lower register pressure, but on some
25968 // platforms they have higher latency than the equivalent
25969 // series of shifts/or that would otherwise be generated.
25970 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25971 // have higher latencies and we are not optimizing for size.
25972 if (!OptForSize && Subtarget->isSHLDSlow())
25975 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25977 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25979 if (!N0.hasOneUse() || !N1.hasOneUse())
25982 SDValue ShAmt0 = N0.getOperand(1);
25983 if (ShAmt0.getValueType() != MVT::i8)
25985 SDValue ShAmt1 = N1.getOperand(1);
25986 if (ShAmt1.getValueType() != MVT::i8)
25988 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25989 ShAmt0 = ShAmt0.getOperand(0);
25990 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25991 ShAmt1 = ShAmt1.getOperand(0);
25994 unsigned Opc = X86ISD::SHLD;
25995 SDValue Op0 = N0.getOperand(0);
25996 SDValue Op1 = N1.getOperand(0);
25997 if (ShAmt0.getOpcode() == ISD::SUB) {
25998 Opc = X86ISD::SHRD;
25999 std::swap(Op0, Op1);
26000 std::swap(ShAmt0, ShAmt1);
26003 unsigned Bits = VT.getSizeInBits();
26004 if (ShAmt1.getOpcode() == ISD::SUB) {
26005 SDValue Sum = ShAmt1.getOperand(0);
26006 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
26007 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
26008 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
26009 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
26010 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
26011 return DAG.getNode(Opc, DL, VT,
26013 DAG.getNode(ISD::TRUNCATE, DL,
26016 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
26017 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
26019 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
26020 return DAG.getNode(Opc, DL, VT,
26021 N0.getOperand(0), N1.getOperand(0),
26022 DAG.getNode(ISD::TRUNCATE, DL,
26029 // Generate NEG and CMOV for integer abs.
26030 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
26031 EVT VT = N->getValueType(0);
26033 // Since X86 does not have CMOV for 8-bit integer, we don't convert
26034 // 8-bit integer abs to NEG and CMOV.
26035 if (VT.isInteger() && VT.getSizeInBits() == 8)
26038 SDValue N0 = N->getOperand(0);
26039 SDValue N1 = N->getOperand(1);
26042 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
26043 // and change it to SUB and CMOV.
26044 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
26045 N0.getOpcode() == ISD::ADD &&
26046 N0.getOperand(1) == N1 &&
26047 N1.getOpcode() == ISD::SRA &&
26048 N1.getOperand(0) == N0.getOperand(0))
26049 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
26050 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
26051 // Generate SUB & CMOV.
26052 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
26053 DAG.getConstant(0, DL, VT), N0.getOperand(0));
26055 SDValue Ops[] = { N0.getOperand(0), Neg,
26056 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
26057 SDValue(Neg.getNode(), 1) };
26058 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
26063 // Try to turn tests against the signbit in the form of:
26064 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
26067 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
26068 // This is only worth doing if the output type is i8.
26069 if (N->getValueType(0) != MVT::i8)
26072 SDValue N0 = N->getOperand(0);
26073 SDValue N1 = N->getOperand(1);
26075 // We should be performing an xor against a truncated shift.
26076 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
26079 // Make sure we are performing an xor against one.
26080 if (!isOneConstant(N1))
26083 // SetCC on x86 zero extends so only act on this if it's a logical shift.
26084 SDValue Shift = N0.getOperand(0);
26085 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
26088 // Make sure we are truncating from one of i16, i32 or i64.
26089 EVT ShiftTy = Shift.getValueType();
26090 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26093 // Make sure the shift amount extracts the sign bit.
26094 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26095 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26098 // Create a greater-than comparison against -1.
26099 // N.B. Using SETGE against 0 works but we want a canonical looking
26100 // comparison, using SETGT matches up with what TranslateX86CC.
26102 SDValue ShiftOp = Shift.getOperand(0);
26103 EVT ShiftOpTy = ShiftOp.getValueType();
26104 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26105 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26109 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26110 TargetLowering::DAGCombinerInfo &DCI,
26111 const X86Subtarget *Subtarget) {
26112 if (DCI.isBeforeLegalizeOps())
26115 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26118 if (Subtarget->hasCMov())
26119 if (SDValue RV = performIntegerAbsCombine(N, DAG))
26122 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26128 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26129 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26130 /// X86ISD::AVG instruction.
26131 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26132 const X86Subtarget *Subtarget, SDLoc DL) {
26133 if (!VT.isVector() || !VT.isSimple())
26135 EVT InVT = In.getValueType();
26136 unsigned NumElems = VT.getVectorNumElements();
26138 EVT ScalarVT = VT.getVectorElementType();
26139 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26140 isPowerOf2_32(NumElems)))
26143 // InScalarVT is the intermediate type in AVG pattern and it should be greater
26144 // than the original input type (i8/i16).
26145 EVT InScalarVT = InVT.getVectorElementType();
26146 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26149 if (Subtarget->hasAVX512()) {
26150 if (VT.getSizeInBits() > 512)
26152 } else if (Subtarget->hasAVX2()) {
26153 if (VT.getSizeInBits() > 256)
26156 if (VT.getSizeInBits() > 128)
26160 // Detect the following pattern:
26162 // %1 = zext <N x i8> %a to <N x i32>
26163 // %2 = zext <N x i8> %b to <N x i32>
26164 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26165 // %4 = add nuw nsw <N x i32> %3, %2
26166 // %5 = lshr <N x i32> %N, <i32 1 x N>
26167 // %6 = trunc <N x i32> %5 to <N x i8>
26169 // In AVX512, the last instruction can also be a trunc store.
26171 if (In.getOpcode() != ISD::SRL)
26174 // A lambda checking the given SDValue is a constant vector and each element
26175 // is in the range [Min, Max].
26176 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26177 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26178 if (!BV || !BV->isConstant())
26180 for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26181 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26184 uint64_t Val = C->getZExtValue();
26185 if (Val < Min || Val > Max)
26191 // Check if each element of the vector is left-shifted by one.
26192 auto LHS = In.getOperand(0);
26193 auto RHS = In.getOperand(1);
26194 if (!IsConstVectorInRange(RHS, 1, 1))
26196 if (LHS.getOpcode() != ISD::ADD)
26199 // Detect a pattern of a + b + 1 where the order doesn't matter.
26200 SDValue Operands[3];
26201 Operands[0] = LHS.getOperand(0);
26202 Operands[1] = LHS.getOperand(1);
26204 // Take care of the case when one of the operands is a constant vector whose
26205 // element is in the range [1, 256].
26206 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26207 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26208 Operands[0].getOperand(0).getValueType() == VT) {
26209 // The pattern is detected. Subtract one from the constant vector, then
26210 // demote it and emit X86ISD::AVG instruction.
26211 SDValue One = DAG.getConstant(1, DL, InScalarVT);
26212 SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26213 SmallVector<SDValue, 8>(NumElems, One));
26214 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26215 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26216 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26220 if (Operands[0].getOpcode() == ISD::ADD)
26221 std::swap(Operands[0], Operands[1]);
26222 else if (Operands[1].getOpcode() != ISD::ADD)
26224 Operands[2] = Operands[1].getOperand(0);
26225 Operands[1] = Operands[1].getOperand(1);
26227 // Now we have three operands of two additions. Check that one of them is a
26228 // constant vector with ones, and the other two are promoted from i8/i16.
26229 for (int i = 0; i < 3; ++i) {
26230 if (!IsConstVectorInRange(Operands[i], 1, 1))
26232 std::swap(Operands[i], Operands[2]);
26234 // Check if Operands[0] and Operands[1] are results of type promotion.
26235 for (int j = 0; j < 2; ++j)
26236 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26237 Operands[j].getOperand(0).getValueType() != VT)
26240 // The pattern is detected, emit X86ISD::AVG instruction.
26241 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26242 Operands[1].getOperand(0));
26248 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26249 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26250 TargetLowering::DAGCombinerInfo &DCI,
26251 const X86Subtarget *Subtarget) {
26252 LoadSDNode *Ld = cast<LoadSDNode>(N);
26253 EVT RegVT = Ld->getValueType(0);
26254 EVT MemVT = Ld->getMemoryVT();
26256 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26258 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26259 // into two 16-byte operations.
26260 ISD::LoadExtType Ext = Ld->getExtensionType();
26262 unsigned AddressSpace = Ld->getAddressSpace();
26263 unsigned Alignment = Ld->getAlignment();
26264 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26265 Ext == ISD::NON_EXTLOAD &&
26266 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26267 AddressSpace, Alignment, &Fast) && !Fast) {
26268 unsigned NumElems = RegVT.getVectorNumElements();
26272 SDValue Ptr = Ld->getBasePtr();
26273 SDValue Increment =
26274 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26276 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26278 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26279 Ld->getPointerInfo(), Ld->isVolatile(),
26280 Ld->isNonTemporal(), Ld->isInvariant(),
26282 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26283 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26284 Ld->getPointerInfo(), Ld->isVolatile(),
26285 Ld->isNonTemporal(), Ld->isInvariant(),
26286 std::min(16U, Alignment));
26287 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26289 Load2.getValue(1));
26291 SDValue NewVec = DAG.getUNDEF(RegVT);
26292 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26293 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26294 return DCI.CombineTo(N, NewVec, TF, true);
26300 /// PerformMLOADCombine - Resolve extending loads
26301 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26302 TargetLowering::DAGCombinerInfo &DCI,
26303 const X86Subtarget *Subtarget) {
26304 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26305 if (Mld->getExtensionType() != ISD::SEXTLOAD)
26308 EVT VT = Mld->getValueType(0);
26309 unsigned NumElems = VT.getVectorNumElements();
26310 EVT LdVT = Mld->getMemoryVT();
26313 assert(LdVT != VT && "Cannot extend to the same type");
26314 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26315 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26316 // From, To sizes and ElemCount must be pow of two
26317 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26318 "Unexpected size for extending masked load");
26320 unsigned SizeRatio = ToSz / FromSz;
26321 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26323 // Create a type on which we perform the shuffle
26324 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26325 LdVT.getScalarType(), NumElems*SizeRatio);
26326 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26328 // Convert Src0 value
26329 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26330 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26331 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26332 for (unsigned i = 0; i != NumElems; ++i)
26333 ShuffleVec[i] = i * SizeRatio;
26335 // Can't shuffle using an illegal type.
26336 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26337 "WideVecVT should be legal");
26338 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26339 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26341 // Prepare the new mask
26343 SDValue Mask = Mld->getMask();
26344 if (Mask.getValueType() == VT) {
26345 // Mask and original value have the same type
26346 NewMask = DAG.getBitcast(WideVecVT, Mask);
26347 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26348 for (unsigned i = 0; i != NumElems; ++i)
26349 ShuffleVec[i] = i * SizeRatio;
26350 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26351 ShuffleVec[i] = NumElems * SizeRatio;
26352 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26353 DAG.getConstant(0, dl, WideVecVT),
26357 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26358 unsigned WidenNumElts = NumElems*SizeRatio;
26359 unsigned MaskNumElts = VT.getVectorNumElements();
26360 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26363 unsigned NumConcat = WidenNumElts / MaskNumElts;
26364 SmallVector<SDValue, 16> Ops(NumConcat);
26365 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26367 for (unsigned i = 1; i != NumConcat; ++i)
26370 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26373 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26374 Mld->getBasePtr(), NewMask, WideSrc0,
26375 Mld->getMemoryVT(), Mld->getMemOperand(),
26377 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26378 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26380 /// PerformMSTORECombine - Resolve truncating stores
26381 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26382 const X86Subtarget *Subtarget) {
26383 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26384 if (!Mst->isTruncatingStore())
26387 EVT VT = Mst->getValue().getValueType();
26388 unsigned NumElems = VT.getVectorNumElements();
26389 EVT StVT = Mst->getMemoryVT();
26392 assert(StVT != VT && "Cannot truncate to the same type");
26393 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26394 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26396 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26398 // The truncating store is legal in some cases. For example
26399 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26400 // are designated for truncate store.
26401 // In this case we don't need any further transformations.
26402 if (TLI.isTruncStoreLegal(VT, StVT))
26405 // From, To sizes and ElemCount must be pow of two
26406 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26407 "Unexpected size for truncating masked store");
26408 // We are going to use the original vector elt for storing.
26409 // Accumulated smaller vector elements must be a multiple of the store size.
26410 assert (((NumElems * FromSz) % ToSz) == 0 &&
26411 "Unexpected ratio for truncating masked store");
26413 unsigned SizeRatio = FromSz / ToSz;
26414 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26416 // Create a type on which we perform the shuffle
26417 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26418 StVT.getScalarType(), NumElems*SizeRatio);
26420 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26422 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26423 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26424 for (unsigned i = 0; i != NumElems; ++i)
26425 ShuffleVec[i] = i * SizeRatio;
26427 // Can't shuffle using an illegal type.
26428 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26429 "WideVecVT should be legal");
26431 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26432 DAG.getUNDEF(WideVecVT),
26436 SDValue Mask = Mst->getMask();
26437 if (Mask.getValueType() == VT) {
26438 // Mask and original value have the same type
26439 NewMask = DAG.getBitcast(WideVecVT, Mask);
26440 for (unsigned i = 0; i != NumElems; ++i)
26441 ShuffleVec[i] = i * SizeRatio;
26442 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26443 ShuffleVec[i] = NumElems*SizeRatio;
26444 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26445 DAG.getConstant(0, dl, WideVecVT),
26449 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26450 unsigned WidenNumElts = NumElems*SizeRatio;
26451 unsigned MaskNumElts = VT.getVectorNumElements();
26452 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26455 unsigned NumConcat = WidenNumElts / MaskNumElts;
26456 SmallVector<SDValue, 16> Ops(NumConcat);
26457 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26459 for (unsigned i = 1; i != NumConcat; ++i)
26462 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26465 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26466 Mst->getBasePtr(), NewMask, StVT,
26467 Mst->getMemOperand(), false);
26469 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26470 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26471 const X86Subtarget *Subtarget) {
26472 StoreSDNode *St = cast<StoreSDNode>(N);
26473 EVT VT = St->getValue().getValueType();
26474 EVT StVT = St->getMemoryVT();
26476 SDValue StoredVal = St->getOperand(1);
26477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26479 // If we are saving a concatenation of two XMM registers and 32-byte stores
26480 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26482 unsigned AddressSpace = St->getAddressSpace();
26483 unsigned Alignment = St->getAlignment();
26484 if (VT.is256BitVector() && StVT == VT &&
26485 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26486 AddressSpace, Alignment, &Fast) && !Fast) {
26487 unsigned NumElems = VT.getVectorNumElements();
26491 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26492 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26495 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26496 SDValue Ptr0 = St->getBasePtr();
26497 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26499 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26500 St->getPointerInfo(), St->isVolatile(),
26501 St->isNonTemporal(), Alignment);
26502 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26503 St->getPointerInfo(), St->isVolatile(),
26504 St->isNonTemporal(),
26505 std::min(16U, Alignment));
26506 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26509 // Optimize trunc store (of multiple scalars) to shuffle and store.
26510 // First, pack all of the elements in one place. Next, store to memory
26511 // in fewer chunks.
26512 if (St->isTruncatingStore() && VT.isVector()) {
26513 // Check if we can detect an AVG pattern from the truncation. If yes,
26514 // replace the trunc store by a normal store with the result of X86ISD::AVG
26517 detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26519 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26520 St->getPointerInfo(), St->isVolatile(),
26521 St->isNonTemporal(), St->getAlignment());
26523 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26524 unsigned NumElems = VT.getVectorNumElements();
26525 assert(StVT != VT && "Cannot truncate to the same type");
26526 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26527 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26529 // The truncating store is legal in some cases. For example
26530 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26531 // are designated for truncate store.
26532 // In this case we don't need any further transformations.
26533 if (TLI.isTruncStoreLegal(VT, StVT))
26536 // From, To sizes and ElemCount must be pow of two
26537 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26538 // We are going to use the original vector elt for storing.
26539 // Accumulated smaller vector elements must be a multiple of the store size.
26540 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26542 unsigned SizeRatio = FromSz / ToSz;
26544 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26546 // Create a type on which we perform the shuffle
26547 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26548 StVT.getScalarType(), NumElems*SizeRatio);
26550 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26552 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26553 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26554 for (unsigned i = 0; i != NumElems; ++i)
26555 ShuffleVec[i] = i * SizeRatio;
26557 // Can't shuffle using an illegal type.
26558 if (!TLI.isTypeLegal(WideVecVT))
26561 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26562 DAG.getUNDEF(WideVecVT),
26564 // At this point all of the data is stored at the bottom of the
26565 // register. We now need to save it to mem.
26567 // Find the largest store unit
26568 MVT StoreType = MVT::i8;
26569 for (MVT Tp : MVT::integer_valuetypes()) {
26570 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26574 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26575 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26576 (64 <= NumElems * ToSz))
26577 StoreType = MVT::f64;
26579 // Bitcast the original vector into a vector of store-size units
26580 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26581 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26582 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26583 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26584 SmallVector<SDValue, 8> Chains;
26585 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26586 TLI.getPointerTy(DAG.getDataLayout()));
26587 SDValue Ptr = St->getBasePtr();
26589 // Perform one or more big stores into memory.
26590 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26591 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26592 StoreType, ShuffWide,
26593 DAG.getIntPtrConstant(i, dl));
26594 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26595 St->getPointerInfo(), St->isVolatile(),
26596 St->isNonTemporal(), St->getAlignment());
26597 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26598 Chains.push_back(Ch);
26601 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26604 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
26605 // the FP state in cases where an emms may be missing.
26606 // A preferable solution to the general problem is to figure out the right
26607 // places to insert EMMS. This qualifies as a quick hack.
26609 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26610 if (VT.getSizeInBits() != 64)
26613 const Function *F = DAG.getMachineFunction().getFunction();
26614 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26616 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26617 if ((VT.isVector() ||
26618 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26619 isa<LoadSDNode>(St->getValue()) &&
26620 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26621 St->getChain().hasOneUse() && !St->isVolatile()) {
26622 SDNode* LdVal = St->getValue().getNode();
26623 LoadSDNode *Ld = nullptr;
26624 int TokenFactorIndex = -1;
26625 SmallVector<SDValue, 8> Ops;
26626 SDNode* ChainVal = St->getChain().getNode();
26627 // Must be a store of a load. We currently handle two cases: the load
26628 // is a direct child, and it's under an intervening TokenFactor. It is
26629 // possible to dig deeper under nested TokenFactors.
26630 if (ChainVal == LdVal)
26631 Ld = cast<LoadSDNode>(St->getChain());
26632 else if (St->getValue().hasOneUse() &&
26633 ChainVal->getOpcode() == ISD::TokenFactor) {
26634 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26635 if (ChainVal->getOperand(i).getNode() == LdVal) {
26636 TokenFactorIndex = i;
26637 Ld = cast<LoadSDNode>(St->getValue());
26639 Ops.push_back(ChainVal->getOperand(i));
26643 if (!Ld || !ISD::isNormalLoad(Ld))
26646 // If this is not the MMX case, i.e. we are just turning i64 load/store
26647 // into f64 load/store, avoid the transformation if there are multiple
26648 // uses of the loaded value.
26649 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26654 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26655 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26657 if (Subtarget->is64Bit() || F64IsLegal) {
26658 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26659 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26660 Ld->getPointerInfo(), Ld->isVolatile(),
26661 Ld->isNonTemporal(), Ld->isInvariant(),
26662 Ld->getAlignment());
26663 SDValue NewChain = NewLd.getValue(1);
26664 if (TokenFactorIndex != -1) {
26665 Ops.push_back(NewChain);
26666 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26668 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26669 St->getPointerInfo(),
26670 St->isVolatile(), St->isNonTemporal(),
26671 St->getAlignment());
26674 // Otherwise, lower to two pairs of 32-bit loads / stores.
26675 SDValue LoAddr = Ld->getBasePtr();
26676 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26677 DAG.getConstant(4, LdDL, MVT::i32));
26679 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26680 Ld->getPointerInfo(),
26681 Ld->isVolatile(), Ld->isNonTemporal(),
26682 Ld->isInvariant(), Ld->getAlignment());
26683 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26684 Ld->getPointerInfo().getWithOffset(4),
26685 Ld->isVolatile(), Ld->isNonTemporal(),
26687 MinAlign(Ld->getAlignment(), 4));
26689 SDValue NewChain = LoLd.getValue(1);
26690 if (TokenFactorIndex != -1) {
26691 Ops.push_back(LoLd);
26692 Ops.push_back(HiLd);
26693 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26696 LoAddr = St->getBasePtr();
26697 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26698 DAG.getConstant(4, StDL, MVT::i32));
26700 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26701 St->getPointerInfo(),
26702 St->isVolatile(), St->isNonTemporal(),
26703 St->getAlignment());
26704 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26705 St->getPointerInfo().getWithOffset(4),
26707 St->isNonTemporal(),
26708 MinAlign(St->getAlignment(), 4));
26709 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26712 // This is similar to the above case, but here we handle a scalar 64-bit
26713 // integer store that is extracted from a vector on a 32-bit target.
26714 // If we have SSE2, then we can treat it like a floating-point double
26715 // to get past legalization. The execution dependencies fixup pass will
26716 // choose the optimal machine instruction for the store if this really is
26717 // an integer or v2f32 rather than an f64.
26718 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26719 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26720 SDValue OldExtract = St->getOperand(1);
26721 SDValue ExtOp0 = OldExtract.getOperand(0);
26722 unsigned VecSize = ExtOp0.getValueSizeInBits();
26723 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26724 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26725 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26726 BitCast, OldExtract.getOperand(1));
26727 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26728 St->getPointerInfo(), St->isVolatile(),
26729 St->isNonTemporal(), St->getAlignment());
26735 /// Return 'true' if this vector operation is "horizontal"
26736 /// and return the operands for the horizontal operation in LHS and RHS. A
26737 /// horizontal operation performs the binary operation on successive elements
26738 /// of its first operand, then on successive elements of its second operand,
26739 /// returning the resulting values in a vector. For example, if
26740 /// A = < float a0, float a1, float a2, float a3 >
26742 /// B = < float b0, float b1, float b2, float b3 >
26743 /// then the result of doing a horizontal operation on A and B is
26744 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26745 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26746 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26747 /// set to A, RHS to B, and the routine returns 'true'.
26748 /// Note that the binary operation should have the property that if one of the
26749 /// operands is UNDEF then the result is UNDEF.
26750 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26751 // Look for the following pattern: if
26752 // A = < float a0, float a1, float a2, float a3 >
26753 // B = < float b0, float b1, float b2, float b3 >
26755 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26756 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26757 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26758 // which is A horizontal-op B.
26760 // At least one of the operands should be a vector shuffle.
26761 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26762 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26765 MVT VT = LHS.getSimpleValueType();
26767 assert((VT.is128BitVector() || VT.is256BitVector()) &&
26768 "Unsupported vector type for horizontal add/sub");
26770 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26771 // operate independently on 128-bit lanes.
26772 unsigned NumElts = VT.getVectorNumElements();
26773 unsigned NumLanes = VT.getSizeInBits()/128;
26774 unsigned NumLaneElts = NumElts / NumLanes;
26775 assert((NumLaneElts % 2 == 0) &&
26776 "Vector type should have an even number of elements in each lane");
26777 unsigned HalfLaneElts = NumLaneElts/2;
26779 // View LHS in the form
26780 // LHS = VECTOR_SHUFFLE A, B, LMask
26781 // If LHS is not a shuffle then pretend it is the shuffle
26782 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26783 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26786 SmallVector<int, 16> LMask(NumElts);
26787 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26788 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26789 A = LHS.getOperand(0);
26790 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26791 B = LHS.getOperand(1);
26792 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26793 std::copy(Mask.begin(), Mask.end(), LMask.begin());
26795 if (LHS.getOpcode() != ISD::UNDEF)
26797 for (unsigned i = 0; i != NumElts; ++i)
26801 // Likewise, view RHS in the form
26802 // RHS = VECTOR_SHUFFLE C, D, RMask
26804 SmallVector<int, 16> RMask(NumElts);
26805 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26806 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26807 C = RHS.getOperand(0);
26808 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26809 D = RHS.getOperand(1);
26810 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26811 std::copy(Mask.begin(), Mask.end(), RMask.begin());
26813 if (RHS.getOpcode() != ISD::UNDEF)
26815 for (unsigned i = 0; i != NumElts; ++i)
26819 // Check that the shuffles are both shuffling the same vectors.
26820 if (!(A == C && B == D) && !(A == D && B == C))
26823 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26824 if (!A.getNode() && !B.getNode())
26827 // If A and B occur in reverse order in RHS, then "swap" them (which means
26828 // rewriting the mask).
26830 ShuffleVectorSDNode::commuteMask(RMask);
26832 // At this point LHS and RHS are equivalent to
26833 // LHS = VECTOR_SHUFFLE A, B, LMask
26834 // RHS = VECTOR_SHUFFLE A, B, RMask
26835 // Check that the masks correspond to performing a horizontal operation.
26836 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26837 for (unsigned i = 0; i != NumLaneElts; ++i) {
26838 int LIdx = LMask[i+l], RIdx = RMask[i+l];
26840 // Ignore any UNDEF components.
26841 if (LIdx < 0 || RIdx < 0 ||
26842 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26843 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26846 // Check that successive elements are being operated on. If not, this is
26847 // not a horizontal operation.
26848 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26849 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26850 if (!(LIdx == Index && RIdx == Index + 1) &&
26851 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26856 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26857 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26861 /// Do target-specific dag combines on floating point adds.
26862 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26863 const X86Subtarget *Subtarget) {
26864 EVT VT = N->getValueType(0);
26865 SDValue LHS = N->getOperand(0);
26866 SDValue RHS = N->getOperand(1);
26868 // Try to synthesize horizontal adds from adds of shuffles.
26869 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26870 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26871 isHorizontalBinOp(LHS, RHS, true))
26872 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26876 /// Do target-specific dag combines on floating point subs.
26877 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26878 const X86Subtarget *Subtarget) {
26879 EVT VT = N->getValueType(0);
26880 SDValue LHS = N->getOperand(0);
26881 SDValue RHS = N->getOperand(1);
26883 // Try to synthesize horizontal subs from subs of shuffles.
26884 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26885 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26886 isHorizontalBinOp(LHS, RHS, false))
26887 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26891 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26893 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26894 SmallVector<SDValue, 8> &Regs) {
26895 assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26896 Regs[0].getValueType() == MVT::v2i64));
26897 EVT OutVT = N->getValueType(0);
26898 EVT OutSVT = OutVT.getVectorElementType();
26899 EVT InVT = Regs[0].getValueType();
26900 EVT InSVT = InVT.getVectorElementType();
26903 // First, use mask to unset all bits that won't appear in the result.
26904 assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26905 "OutSVT can only be either i8 or i16.");
26907 DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26908 SDValue MaskVec = DAG.getNode(
26909 ISD::BUILD_VECTOR, DL, InVT,
26910 SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26911 for (auto &Reg : Regs)
26912 Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26914 MVT UnpackedVT, PackedVT;
26915 if (OutSVT == MVT::i8) {
26916 UnpackedVT = MVT::v8i16;
26917 PackedVT = MVT::v16i8;
26919 UnpackedVT = MVT::v4i32;
26920 PackedVT = MVT::v8i16;
26923 // In each iteration, truncate the type by a half size.
26924 auto RegNum = Regs.size();
26925 for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26926 j < e; j *= 2, RegNum /= 2) {
26927 for (unsigned i = 0; i < RegNum; i++)
26928 Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26929 for (unsigned i = 0; i < RegNum / 2; i++)
26930 Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26934 // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26935 // then extract a subvector as the result since v8i8 is not a legal type.
26936 if (OutVT == MVT::v8i8) {
26937 Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26938 Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26939 DAG.getIntPtrConstant(0, DL));
26941 } else if (RegNum > 1) {
26942 Regs.resize(RegNum);
26943 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26948 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26950 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26951 SmallVector<SDValue, 8> &Regs) {
26952 assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26953 EVT OutVT = N->getValueType(0);
26956 // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26957 SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26958 for (auto &Reg : Regs) {
26959 Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26960 Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26963 for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26964 Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26967 if (Regs.size() > 2) {
26968 Regs.resize(Regs.size() / 2);
26969 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26974 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26975 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26976 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26977 /// element that is extracted from a vector and then truncated, and it is
26978 /// diffcult to do this optimization based on them.
26979 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26980 const X86Subtarget *Subtarget) {
26981 EVT OutVT = N->getValueType(0);
26982 if (!OutVT.isVector())
26985 SDValue In = N->getOperand(0);
26986 if (!In.getValueType().isSimple())
26989 EVT InVT = In.getValueType();
26990 unsigned NumElems = OutVT.getVectorNumElements();
26992 // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26993 // SSE2, and we need to take care of it specially.
26994 // AVX512 provides vpmovdb.
26995 if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26998 EVT OutSVT = OutVT.getVectorElementType();
26999 EVT InSVT = InVT.getVectorElementType();
27000 if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
27001 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
27005 // SSSE3's pshufb results in less instructions in the cases below.
27006 if (Subtarget->hasSSSE3() && NumElems == 8 &&
27007 ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
27008 (InSVT == MVT::i32 && OutSVT == MVT::i16)))
27013 // Split a long vector into vectors of legal type.
27014 unsigned RegNum = InVT.getSizeInBits() / 128;
27015 SmallVector<SDValue, 8> SubVec(RegNum);
27016 if (InSVT == MVT::i32) {
27017 for (unsigned i = 0; i < RegNum; i++)
27018 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
27019 DAG.getIntPtrConstant(i * 4, DL));
27021 for (unsigned i = 0; i < RegNum; i++)
27022 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
27023 DAG.getIntPtrConstant(i * 2, DL));
27026 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
27027 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
27028 // truncate 2 x v4i32 to v8i16.
27029 if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
27030 return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
27031 else if (InSVT == MVT::i32)
27032 return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
27037 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
27038 const X86Subtarget *Subtarget) {
27039 // Try to detect AVG pattern first.
27040 SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
27041 Subtarget, SDLoc(N));
27045 return combineVectorTruncation(N, DAG, Subtarget);
27048 /// Do target-specific dag combines on floating point negations.
27049 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
27050 const X86Subtarget *Subtarget) {
27051 EVT VT = N->getValueType(0);
27052 EVT SVT = VT.getScalarType();
27053 SDValue Arg = N->getOperand(0);
27056 // Let legalize expand this if it isn't a legal type yet.
27057 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27060 // If we're negating a FMUL node on a target with FMA, then we can avoid the
27061 // use of a constant by performing (-0 - A*B) instead.
27062 // FIXME: Check rounding control flags as well once it becomes available.
27063 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
27064 Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
27065 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
27066 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27067 Arg.getOperand(1), Zero);
27070 // If we're negating a FMA node, then we can adjust the
27071 // instruction to include the extra negation.
27072 if (Arg.hasOneUse()) {
27073 switch (Arg.getOpcode()) {
27074 case X86ISD::FMADD:
27075 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27076 Arg.getOperand(1), Arg.getOperand(2));
27077 case X86ISD::FMSUB:
27078 return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
27079 Arg.getOperand(1), Arg.getOperand(2));
27080 case X86ISD::FNMADD:
27081 return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
27082 Arg.getOperand(1), Arg.getOperand(2));
27083 case X86ISD::FNMSUB:
27084 return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
27085 Arg.getOperand(1), Arg.getOperand(2));
27091 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
27092 const X86Subtarget *Subtarget) {
27093 EVT VT = N->getValueType(0);
27094 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27095 // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27096 // These logic operations may be executed in the integer domain.
27098 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27099 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27101 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27102 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27103 unsigned IntOpcode = 0;
27104 switch (N->getOpcode()) {
27105 default: llvm_unreachable("Unexpected FP logic op");
27106 case X86ISD::FOR: IntOpcode = ISD::OR; break;
27107 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27108 case X86ISD::FAND: IntOpcode = ISD::AND; break;
27109 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27111 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27112 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27116 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27117 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27118 const X86Subtarget *Subtarget) {
27119 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27121 // F[X]OR(0.0, x) -> x
27122 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27123 if (C->getValueAPF().isPosZero())
27124 return N->getOperand(1);
27126 // F[X]OR(x, 0.0) -> x
27127 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27128 if (C->getValueAPF().isPosZero())
27129 return N->getOperand(0);
27131 return lowerX86FPLogicOp(N, DAG, Subtarget);
27134 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27135 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27136 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27138 // Only perform optimizations if UnsafeMath is used.
27139 if (!DAG.getTarget().Options.UnsafeFPMath)
27142 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27143 // into FMINC and FMAXC, which are Commutative operations.
27144 unsigned NewOp = 0;
27145 switch (N->getOpcode()) {
27146 default: llvm_unreachable("unknown opcode");
27147 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
27148 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
27151 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27152 N->getOperand(0), N->getOperand(1));
27155 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27156 const X86Subtarget *Subtarget) {
27157 if (Subtarget->useSoftFloat())
27160 // TODO: Check for global or instruction-level "nnan". In that case, we
27161 // should be able to lower to FMAX/FMIN alone.
27162 // TODO: If an operand is already known to be a NaN or not a NaN, this
27163 // should be an optional swap and FMAX/FMIN.
27165 EVT VT = N->getValueType(0);
27166 if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27167 (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27168 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27171 // This takes at least 3 instructions, so favor a library call when operating
27172 // on a scalar and minimizing code size.
27173 if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27176 SDValue Op0 = N->getOperand(0);
27177 SDValue Op1 = N->getOperand(1);
27179 EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27180 DAG.getDataLayout(), *DAG.getContext(), VT);
27182 // There are 4 possibilities involving NaN inputs, and these are the required
27186 // ----------------
27187 // Num | Max | Op0 |
27188 // Op0 ----------------
27189 // NaN | Op1 | NaN |
27190 // ----------------
27192 // The SSE FP max/min instructions were not designed for this case, but rather
27194 // Min = Op1 < Op0 ? Op1 : Op0
27195 // Max = Op1 > Op0 ? Op1 : Op0
27197 // So they always return Op0 if either input is a NaN. However, we can still
27198 // use those instructions for fmaxnum by selecting away a NaN input.
27200 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27201 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27202 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27203 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27205 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27206 // are NaN, the NaN value of Op1 is the result.
27207 auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27208 return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27211 /// Do target-specific dag combines on X86ISD::FAND nodes.
27212 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27213 const X86Subtarget *Subtarget) {
27214 // FAND(0.0, x) -> 0.0
27215 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27216 if (C->getValueAPF().isPosZero())
27217 return N->getOperand(0);
27219 // FAND(x, 0.0) -> 0.0
27220 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27221 if (C->getValueAPF().isPosZero())
27222 return N->getOperand(1);
27224 return lowerX86FPLogicOp(N, DAG, Subtarget);
27227 /// Do target-specific dag combines on X86ISD::FANDN nodes
27228 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27229 const X86Subtarget *Subtarget) {
27230 // FANDN(0.0, x) -> x
27231 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27232 if (C->getValueAPF().isPosZero())
27233 return N->getOperand(1);
27235 // FANDN(x, 0.0) -> 0.0
27236 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27237 if (C->getValueAPF().isPosZero())
27238 return N->getOperand(1);
27240 return lowerX86FPLogicOp(N, DAG, Subtarget);
27243 static SDValue PerformBTCombine(SDNode *N,
27245 TargetLowering::DAGCombinerInfo &DCI) {
27246 // BT ignores high bits in the bit index operand.
27247 SDValue Op1 = N->getOperand(1);
27248 if (Op1.hasOneUse()) {
27249 unsigned BitWidth = Op1.getValueSizeInBits();
27250 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27251 APInt KnownZero, KnownOne;
27252 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27253 !DCI.isBeforeLegalizeOps());
27254 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27255 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27256 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27257 DCI.CommitTargetLoweringOpt(TLO);
27262 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27263 SDValue Op = N->getOperand(0);
27264 if (Op.getOpcode() == ISD::BITCAST)
27265 Op = Op.getOperand(0);
27266 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27267 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27268 VT.getVectorElementType().getSizeInBits() ==
27269 OpVT.getVectorElementType().getSizeInBits()) {
27270 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27275 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27276 const X86Subtarget *Subtarget) {
27277 EVT VT = N->getValueType(0);
27278 if (!VT.isVector())
27281 SDValue N0 = N->getOperand(0);
27282 SDValue N1 = N->getOperand(1);
27283 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27286 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27287 // both SSE and AVX2 since there is no sign-extended shift right
27288 // operation on a vector with 64-bit elements.
27289 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27290 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27291 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27292 N0.getOpcode() == ISD::SIGN_EXTEND)) {
27293 SDValue N00 = N0.getOperand(0);
27295 // EXTLOAD has a better solution on AVX2,
27296 // it may be replaced with X86ISD::VSEXT node.
27297 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27298 if (!ISD::isNormalLoad(N00.getNode()))
27301 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27302 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27304 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27310 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27311 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27312 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27313 /// eliminate extend, add, and shift instructions.
27314 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27315 const X86Subtarget *Subtarget) {
27316 // TODO: This should be valid for other integer types.
27317 EVT VT = Sext->getValueType(0);
27318 if (VT != MVT::i64)
27321 // We need an 'add nsw' feeding into the 'sext'.
27322 SDValue Add = Sext->getOperand(0);
27323 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27326 // Having a constant operand to the 'add' ensures that we are not increasing
27327 // the instruction count because the constant is extended for free below.
27328 // A constant operand can also become the displacement field of an LEA.
27329 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27333 // Don't make the 'add' bigger if there's no hope of combining it with some
27334 // other 'add' or 'shl' instruction.
27335 // TODO: It may be profitable to generate simpler LEA instructions in place
27336 // of single 'add' instructions, but the cost model for selecting an LEA
27337 // currently has a high threshold.
27338 bool HasLEAPotential = false;
27339 for (auto *User : Sext->uses()) {
27340 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27341 HasLEAPotential = true;
27345 if (!HasLEAPotential)
27348 // Everything looks good, so pull the 'sext' ahead of the 'add'.
27349 int64_t AddConstant = AddOp1->getSExtValue();
27350 SDValue AddOp0 = Add.getOperand(0);
27351 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27352 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27354 // The wider add is guaranteed to not wrap because both operands are
27357 Flags.setNoSignedWrap(true);
27358 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27361 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27362 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27363 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27364 /// extends from AH (which we otherwise need to do contortions to access).
27365 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27366 SDValue N0 = N->getOperand(0);
27367 auto OpcodeN = N->getOpcode();
27368 auto OpcodeN0 = N0.getOpcode();
27369 if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27370 (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27373 EVT VT = N->getValueType(0);
27374 EVT InVT = N0.getValueType();
27375 if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27378 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27379 auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27380 : X86ISD::UDIVREM8_ZEXT_HREG;
27381 SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27383 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27384 return R.getValue(1);
27387 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27388 TargetLowering::DAGCombinerInfo &DCI,
27389 const X86Subtarget *Subtarget) {
27390 SDValue N0 = N->getOperand(0);
27391 EVT VT = N->getValueType(0);
27392 EVT SVT = VT.getScalarType();
27393 EVT InVT = N0.getValueType();
27394 EVT InSVT = InVT.getScalarType();
27397 if (SDValue DivRem8 = getDivRem8(N, DAG))
27400 if (!DCI.isBeforeLegalizeOps()) {
27401 if (InVT == MVT::i1) {
27402 SDValue Zero = DAG.getConstant(0, DL, VT);
27404 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27405 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27410 if (VT.isVector() && Subtarget->hasSSE2()) {
27411 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27412 EVT InVT = N.getValueType();
27413 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27414 Size / InVT.getScalarSizeInBits());
27415 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27416 DAG.getUNDEF(InVT));
27418 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27421 // If target-size is less than 128-bits, extend to a type that would extend
27422 // to 128 bits, extend that and extract the original target vector.
27423 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27424 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27425 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27426 unsigned Scale = 128 / VT.getSizeInBits();
27428 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27429 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27430 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27431 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27432 DAG.getIntPtrConstant(0, DL));
27435 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27436 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27437 if (VT.getSizeInBits() == 128 &&
27438 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27439 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27440 SDValue ExOp = ExtendVecSize(DL, N0, 128);
27441 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27444 // On pre-AVX2 targets, split into 128-bit nodes of
27445 // ISD::SIGN_EXTEND_VECTOR_INREG.
27446 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27447 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27448 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27449 unsigned NumVecs = VT.getSizeInBits() / 128;
27450 unsigned NumSubElts = 128 / SVT.getSizeInBits();
27451 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27452 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27454 SmallVector<SDValue, 8> Opnds;
27455 for (unsigned i = 0, Offset = 0; i != NumVecs;
27456 ++i, Offset += NumSubElts) {
27457 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27458 DAG.getIntPtrConstant(Offset, DL));
27459 SrcVec = ExtendVecSize(DL, SrcVec, 128);
27460 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27461 Opnds.push_back(SrcVec);
27463 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27467 if (Subtarget->hasAVX() && VT.is256BitVector())
27468 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27471 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27477 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27478 const X86Subtarget* Subtarget) {
27480 EVT VT = N->getValueType(0);
27482 // Let legalize expand this if it isn't a legal type yet.
27483 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27486 EVT ScalarVT = VT.getScalarType();
27487 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27490 SDValue A = N->getOperand(0);
27491 SDValue B = N->getOperand(1);
27492 SDValue C = N->getOperand(2);
27494 bool NegA = (A.getOpcode() == ISD::FNEG);
27495 bool NegB = (B.getOpcode() == ISD::FNEG);
27496 bool NegC = (C.getOpcode() == ISD::FNEG);
27498 // Negative multiplication when NegA xor NegB
27499 bool NegMul = (NegA != NegB);
27501 A = A.getOperand(0);
27503 B = B.getOperand(0);
27505 C = C.getOperand(0);
27509 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27511 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27513 return DAG.getNode(Opcode, dl, VT, A, B, C);
27516 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27517 TargetLowering::DAGCombinerInfo &DCI,
27518 const X86Subtarget *Subtarget) {
27519 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
27520 // (and (i32 x86isd::setcc_carry), 1)
27521 // This eliminates the zext. This transformation is necessary because
27522 // ISD::SETCC is always legalized to i8.
27524 SDValue N0 = N->getOperand(0);
27525 EVT VT = N->getValueType(0);
27527 if (N0.getOpcode() == ISD::AND &&
27529 N0.getOperand(0).hasOneUse()) {
27530 SDValue N00 = N0.getOperand(0);
27531 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27532 if (!isOneConstant(N0.getOperand(1)))
27534 return DAG.getNode(ISD::AND, dl, VT,
27535 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27536 N00.getOperand(0), N00.getOperand(1)),
27537 DAG.getConstant(1, dl, VT));
27541 if (N0.getOpcode() == ISD::TRUNCATE &&
27543 N0.getOperand(0).hasOneUse()) {
27544 SDValue N00 = N0.getOperand(0);
27545 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27546 return DAG.getNode(ISD::AND, dl, VT,
27547 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27548 N00.getOperand(0), N00.getOperand(1)),
27549 DAG.getConstant(1, dl, VT));
27553 if (VT.is256BitVector())
27554 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27557 if (SDValue DivRem8 = getDivRem8(N, DAG))
27563 // Optimize x == -y --> x+y == 0
27564 // x != -y --> x+y != 0
27565 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27566 const X86Subtarget* Subtarget) {
27567 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27568 SDValue LHS = N->getOperand(0);
27569 SDValue RHS = N->getOperand(1);
27570 EVT VT = N->getValueType(0);
27573 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27574 if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27575 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27576 LHS.getOperand(1));
27577 return DAG.getSetCC(DL, N->getValueType(0), addV,
27578 DAG.getConstant(0, DL, addV.getValueType()), CC);
27580 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27581 if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27582 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27583 RHS.getOperand(1));
27584 return DAG.getSetCC(DL, N->getValueType(0), addV,
27585 DAG.getConstant(0, DL, addV.getValueType()), CC);
27588 if (VT.getScalarType() == MVT::i1 &&
27589 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27591 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27592 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27593 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27595 if (!IsSEXT0 || !IsVZero1) {
27596 // Swap the operands and update the condition code.
27597 std::swap(LHS, RHS);
27598 CC = ISD::getSetCCSwappedOperands(CC);
27600 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27601 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27602 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27605 if (IsSEXT0 && IsVZero1) {
27606 assert(VT == LHS.getOperand(0).getValueType() &&
27607 "Uexpected operand type");
27608 if (CC == ISD::SETGT)
27609 return DAG.getConstant(0, DL, VT);
27610 if (CC == ISD::SETLE)
27611 return DAG.getConstant(1, DL, VT);
27612 if (CC == ISD::SETEQ || CC == ISD::SETGE)
27613 return DAG.getNOT(DL, LHS.getOperand(0), VT);
27615 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27616 "Unexpected condition code!");
27617 return LHS.getOperand(0);
27624 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27626 // Gather and Scatter instructions use k-registers for masks. The type of
27627 // the masks is v*i1. So the mask will be truncated anyway.
27628 // The SIGN_EXTEND_INREG my be dropped.
27629 SDValue Mask = N->getOperand(2);
27630 if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27631 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27632 NewOps[2] = Mask.getOperand(0);
27633 DAG.UpdateNodeOperands(N, NewOps);
27638 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27639 // as "sbb reg,reg", since it can be extended without zext and produces
27640 // an all-ones bit which is more useful than 0/1 in some cases.
27641 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27644 return DAG.getNode(ISD::AND, DL, VT,
27645 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27646 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27648 DAG.getConstant(1, DL, VT));
27649 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27650 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27651 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27652 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27656 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27657 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27658 TargetLowering::DAGCombinerInfo &DCI,
27659 const X86Subtarget *Subtarget) {
27661 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27662 SDValue EFLAGS = N->getOperand(1);
27664 if (CC == X86::COND_A) {
27665 // Try to convert COND_A into COND_B in an attempt to facilitate
27666 // materializing "setb reg".
27668 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27669 // cannot take an immediate as its first operand.
27671 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27672 EFLAGS.getValueType().isInteger() &&
27673 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27674 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27675 EFLAGS.getNode()->getVTList(),
27676 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27677 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27678 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27682 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27683 // a zext and produces an all-ones bit which is more useful than 0/1 in some
27685 if (CC == X86::COND_B)
27686 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27688 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27689 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27690 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27696 // Optimize branch condition evaluation.
27698 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27699 TargetLowering::DAGCombinerInfo &DCI,
27700 const X86Subtarget *Subtarget) {
27702 SDValue Chain = N->getOperand(0);
27703 SDValue Dest = N->getOperand(1);
27704 SDValue EFLAGS = N->getOperand(3);
27705 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27707 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27708 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27709 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27716 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27717 SelectionDAG &DAG) {
27718 // Take advantage of vector comparisons producing 0 or -1 in each lane to
27719 // optimize away operation when it's from a constant.
27721 // The general transformation is:
27722 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27723 // AND(VECTOR_CMP(x,y), constant2)
27724 // constant2 = UNARYOP(constant)
27726 // Early exit if this isn't a vector operation, the operand of the
27727 // unary operation isn't a bitwise AND, or if the sizes of the operations
27728 // aren't the same.
27729 EVT VT = N->getValueType(0);
27730 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27731 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27732 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27735 // Now check that the other operand of the AND is a constant. We could
27736 // make the transformation for non-constant splats as well, but it's unclear
27737 // that would be a benefit as it would not eliminate any operations, just
27738 // perform one more step in scalar code before moving to the vector unit.
27739 if (BuildVectorSDNode *BV =
27740 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27741 // Bail out if the vector isn't a constant.
27742 if (!BV->isConstant())
27745 // Everything checks out. Build up the new and improved node.
27747 EVT IntVT = BV->getValueType(0);
27748 // Create a new constant of the appropriate type for the transformed
27750 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27751 // The AND node needs bitcasts to/from an integer vector type around it.
27752 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27753 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27754 N->getOperand(0)->getOperand(0), MaskConst);
27755 SDValue Res = DAG.getBitcast(VT, NewAnd);
27762 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27763 const X86Subtarget *Subtarget) {
27764 SDValue Op0 = N->getOperand(0);
27765 EVT VT = N->getValueType(0);
27766 EVT InVT = Op0.getValueType();
27767 EVT InSVT = InVT.getScalarType();
27768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27770 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27771 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27772 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27774 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27775 InVT.getVectorNumElements());
27776 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27778 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27779 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27781 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27787 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27788 const X86Subtarget *Subtarget) {
27789 // First try to optimize away the conversion entirely when it's
27790 // conditionally from a constant. Vectors only.
27791 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27794 // Now move on to more general possibilities.
27795 SDValue Op0 = N->getOperand(0);
27796 EVT VT = N->getValueType(0);
27797 EVT InVT = Op0.getValueType();
27798 EVT InSVT = InVT.getScalarType();
27800 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27801 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27802 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27804 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27805 InVT.getVectorNumElements());
27806 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27807 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27810 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27811 // a 32-bit target where SSE doesn't support i64->FP operations.
27812 if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27813 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27814 EVT LdVT = Ld->getValueType(0);
27816 // This transformation is not supported if the result type is f16
27817 if (VT == MVT::f16)
27820 if (!Ld->isVolatile() && !VT.isVector() &&
27821 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27822 !Subtarget->is64Bit() && LdVT == MVT::i64) {
27823 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27824 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27825 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27832 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27833 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27834 X86TargetLowering::DAGCombinerInfo &DCI) {
27835 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27836 // the result is either zero or one (depending on the input carry bit).
27837 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27838 if (X86::isZeroNode(N->getOperand(0)) &&
27839 X86::isZeroNode(N->getOperand(1)) &&
27840 // We don't have a good way to replace an EFLAGS use, so only do this when
27842 SDValue(N, 1).use_empty()) {
27844 EVT VT = N->getValueType(0);
27845 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27846 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27847 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27848 DAG.getConstant(X86::COND_B, DL,
27851 DAG.getConstant(1, DL, VT));
27852 return DCI.CombineTo(N, Res1, CarryOut);
27858 // fold (add Y, (sete X, 0)) -> adc 0, Y
27859 // (add Y, (setne X, 0)) -> sbb -1, Y
27860 // (sub (sete X, 0), Y) -> sbb 0, Y
27861 // (sub (setne X, 0), Y) -> adc -1, Y
27862 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27865 // Look through ZExts.
27866 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27867 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27870 SDValue SetCC = Ext.getOperand(0);
27871 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27874 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27875 if (CC != X86::COND_E && CC != X86::COND_NE)
27878 SDValue Cmp = SetCC.getOperand(1);
27879 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27880 !X86::isZeroNode(Cmp.getOperand(1)) ||
27881 !Cmp.getOperand(0).getValueType().isInteger())
27884 SDValue CmpOp0 = Cmp.getOperand(0);
27885 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27886 DAG.getConstant(1, DL, CmpOp0.getValueType()));
27888 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27889 if (CC == X86::COND_NE)
27890 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27891 DL, OtherVal.getValueType(), OtherVal,
27892 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27894 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27895 DL, OtherVal.getValueType(), OtherVal,
27896 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27899 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27900 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27901 const X86Subtarget *Subtarget) {
27902 EVT VT = N->getValueType(0);
27903 SDValue Op0 = N->getOperand(0);
27904 SDValue Op1 = N->getOperand(1);
27906 // Try to synthesize horizontal adds from adds of shuffles.
27907 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27908 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27909 isHorizontalBinOp(Op0, Op1, true))
27910 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27912 return OptimizeConditionalInDecrement(N, DAG);
27915 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27916 const X86Subtarget *Subtarget) {
27917 SDValue Op0 = N->getOperand(0);
27918 SDValue Op1 = N->getOperand(1);
27920 // X86 can't encode an immediate LHS of a sub. See if we can push the
27921 // negation into a preceding instruction.
27922 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27923 // If the RHS of the sub is a XOR with one use and a constant, invert the
27924 // immediate. Then add one to the LHS of the sub so we can turn
27925 // X-Y -> X+~Y+1, saving one register.
27926 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27927 isa<ConstantSDNode>(Op1.getOperand(1))) {
27928 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27929 EVT VT = Op0.getValueType();
27930 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27932 DAG.getConstant(~XorC, SDLoc(Op1), VT));
27933 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27934 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27938 // Try to synthesize horizontal adds from adds of shuffles.
27939 EVT VT = N->getValueType(0);
27940 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27941 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27942 isHorizontalBinOp(Op0, Op1, true))
27943 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27945 return OptimizeConditionalInDecrement(N, DAG);
27948 /// performVZEXTCombine - Performs build vector combines
27949 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27950 TargetLowering::DAGCombinerInfo &DCI,
27951 const X86Subtarget *Subtarget) {
27953 MVT VT = N->getSimpleValueType(0);
27954 SDValue Op = N->getOperand(0);
27955 MVT OpVT = Op.getSimpleValueType();
27956 MVT OpEltVT = OpVT.getVectorElementType();
27957 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27959 // (vzext (bitcast (vzext (x)) -> (vzext x)
27961 while (V.getOpcode() == ISD::BITCAST)
27962 V = V.getOperand(0);
27964 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27965 MVT InnerVT = V.getSimpleValueType();
27966 MVT InnerEltVT = InnerVT.getVectorElementType();
27968 // If the element sizes match exactly, we can just do one larger vzext. This
27969 // is always an exact type match as vzext operates on integer types.
27970 if (OpEltVT == InnerEltVT) {
27971 assert(OpVT == InnerVT && "Types must match for vzext!");
27972 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27975 // The only other way we can combine them is if only a single element of the
27976 // inner vzext is used in the input to the outer vzext.
27977 if (InnerEltVT.getSizeInBits() < InputBits)
27980 // In this case, the inner vzext is completely dead because we're going to
27981 // only look at bits inside of the low element. Just do the outer vzext on
27982 // a bitcast of the input to the inner.
27983 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27986 // Check if we can bypass extracting and re-inserting an element of an input
27987 // vector. Essentially:
27988 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27989 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27990 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27991 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27992 SDValue ExtractedV = V.getOperand(0);
27993 SDValue OrigV = ExtractedV.getOperand(0);
27994 if (isNullConstant(ExtractedV.getOperand(1))) {
27995 MVT OrigVT = OrigV.getSimpleValueType();
27996 // Extract a subvector if necessary...
27997 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27998 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27999 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
28000 OrigVT.getVectorNumElements() / Ratio);
28001 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
28002 DAG.getIntPtrConstant(0, DL));
28004 Op = DAG.getBitcast(OpVT, OrigV);
28005 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
28012 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
28013 DAGCombinerInfo &DCI) const {
28014 SelectionDAG &DAG = DCI.DAG;
28015 switch (N->getOpcode()) {
28017 case ISD::EXTRACT_VECTOR_ELT:
28018 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
28021 case X86ISD::SHRUNKBLEND:
28022 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
28023 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG, Subtarget);
28024 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
28025 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
28026 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
28027 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
28028 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
28031 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
28032 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
28033 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
28034 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
28035 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
28036 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
28037 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
28038 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
28039 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
28040 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
28041 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
28042 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
28043 case ISD::FNEG: return PerformFNEGCombine(N, DAG, Subtarget);
28044 case ISD::TRUNCATE: return PerformTRUNCATECombine(N, DAG, Subtarget);
28046 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
28048 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
28050 case ISD::FMAXNUM: return performFMinNumFMaxNumCombine(N, DAG,
28052 case X86ISD::FAND: return PerformFANDCombine(N, DAG, Subtarget);
28053 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG, Subtarget);
28054 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
28055 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
28056 case ISD::ANY_EXTEND:
28057 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
28058 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
28059 case ISD::SIGN_EXTEND_INREG:
28060 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
28061 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
28062 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
28063 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
28064 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
28065 case X86ISD::SHUFP: // Handle all target specific shuffles
28066 case X86ISD::PALIGNR:
28067 case X86ISD::BLENDI:
28068 case X86ISD::UNPCKH:
28069 case X86ISD::UNPCKL:
28070 case X86ISD::MOVHLPS:
28071 case X86ISD::MOVLHPS:
28072 case X86ISD::PSHUFB:
28073 case X86ISD::PSHUFD:
28074 case X86ISD::PSHUFHW:
28075 case X86ISD::PSHUFLW:
28076 case X86ISD::MOVSS:
28077 case X86ISD::MOVSD:
28078 case X86ISD::VPERMILPI:
28079 case X86ISD::VPERM2X128:
28080 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
28081 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
28083 case ISD::MSCATTER: return PerformGatherScatterCombine(N, DAG);
28089 /// isTypeDesirableForOp - Return true if the target has native support for
28090 /// the specified value type and it is 'desirable' to use the type for the
28091 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
28092 /// instruction encodings are longer and some i16 instructions are slow.
28093 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28094 if (!isTypeLegal(VT))
28096 if (VT != MVT::i16)
28103 case ISD::SIGN_EXTEND:
28104 case ISD::ZERO_EXTEND:
28105 case ISD::ANY_EXTEND:
28118 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28119 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28120 /// we don't adjust the stack we clobber the first frame index.
28121 /// See X86InstrInfo::copyPhysReg.
28122 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28123 MachineFunction *MF) const {
28124 const MachineRegisterInfo &MRI = MF->getRegInfo();
28126 return any_of(MRI.reg_instructions(X86::EFLAGS),
28127 [](const MachineInstr &RI) { return RI.isCopy(); });
28130 /// IsDesirableToPromoteOp - This method query the target whether it is
28131 /// beneficial for dag combiner to promote the specified node. If true, it
28132 /// should return the desired promotion type by reference.
28133 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28134 EVT VT = Op.getValueType();
28135 if (VT != MVT::i16)
28138 bool Promote = false;
28139 bool Commute = false;
28140 switch (Op.getOpcode()) {
28143 LoadSDNode *LD = cast<LoadSDNode>(Op);
28144 // If the non-extending load has a single use and it's not live out, then it
28145 // might be folded.
28146 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28147 Op.hasOneUse()*/) {
28148 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28149 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28150 // The only case where we'd want to promote LOAD (rather then it being
28151 // promoted as an operand is when it's only use is liveout.
28152 if (UI->getOpcode() != ISD::CopyToReg)
28159 case ISD::SIGN_EXTEND:
28160 case ISD::ZERO_EXTEND:
28161 case ISD::ANY_EXTEND:
28166 SDValue N0 = Op.getOperand(0);
28167 // Look out for (store (shl (load), x)).
28168 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28181 SDValue N0 = Op.getOperand(0);
28182 SDValue N1 = Op.getOperand(1);
28183 if (!Commute && MayFoldLoad(N1))
28185 // Avoid disabling potential load folding opportunities.
28186 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28188 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28198 //===----------------------------------------------------------------------===//
28199 // X86 Inline Assembly Support
28200 //===----------------------------------------------------------------------===//
28202 // Helper to match a string separated by whitespace.
28203 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28204 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28206 for (StringRef Piece : Pieces) {
28207 if (!S.startswith(Piece)) // Check if the piece matches.
28210 S = S.substr(Piece.size());
28211 StringRef::size_type Pos = S.find_first_not_of(" \t");
28212 if (Pos == 0) // We matched a prefix.
28221 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28223 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28224 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28225 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28226 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28228 if (AsmPieces.size() == 3)
28230 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28237 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28238 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28240 std::string AsmStr = IA->getAsmString();
28242 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28243 if (!Ty || Ty->getBitWidth() % 16 != 0)
28246 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28247 SmallVector<StringRef, 4> AsmPieces;
28248 SplitString(AsmStr, AsmPieces, ";\n");
28250 switch (AsmPieces.size()) {
28251 default: return false;
28253 // FIXME: this should verify that we are targeting a 486 or better. If not,
28254 // we will turn this bswap into something that will be lowered to logical
28255 // ops instead of emitting the bswap asm. For now, we don't support 486 or
28256 // lower so don't worry about this.
28258 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28259 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28260 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28261 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28262 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28263 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28264 // No need to check constraints, nothing other than the equivalent of
28265 // "=r,0" would be valid here.
28266 return IntrinsicLowering::LowerToByteSwap(CI);
28269 // rorw $$8, ${0:w} --> llvm.bswap.i16
28270 if (CI->getType()->isIntegerTy(16) &&
28271 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28272 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28273 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28275 StringRef ConstraintsStr = IA->getConstraintString();
28276 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28277 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28278 if (clobbersFlagRegisters(AsmPieces))
28279 return IntrinsicLowering::LowerToByteSwap(CI);
28283 if (CI->getType()->isIntegerTy(32) &&
28284 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28285 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28286 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28287 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28289 StringRef ConstraintsStr = IA->getConstraintString();
28290 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28291 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28292 if (clobbersFlagRegisters(AsmPieces))
28293 return IntrinsicLowering::LowerToByteSwap(CI);
28296 if (CI->getType()->isIntegerTy(64)) {
28297 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28298 if (Constraints.size() >= 2 &&
28299 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28300 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28301 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
28302 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28303 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28304 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28305 return IntrinsicLowering::LowerToByteSwap(CI);
28313 /// getConstraintType - Given a constraint letter, return the type of
28314 /// constraint it is for this target.
28315 X86TargetLowering::ConstraintType
28316 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28317 if (Constraint.size() == 1) {
28318 switch (Constraint[0]) {
28329 return C_RegisterClass;
28353 return TargetLowering::getConstraintType(Constraint);
28356 /// Examine constraint type and operand type and determine a weight value.
28357 /// This object must already have been set up with the operand type
28358 /// and the current alternative constraint selected.
28359 TargetLowering::ConstraintWeight
28360 X86TargetLowering::getSingleConstraintMatchWeight(
28361 AsmOperandInfo &info, const char *constraint) const {
28362 ConstraintWeight weight = CW_Invalid;
28363 Value *CallOperandVal = info.CallOperandVal;
28364 // If we don't have a value, we can't do a match,
28365 // but allow it at the lowest weight.
28366 if (!CallOperandVal)
28368 Type *type = CallOperandVal->getType();
28369 // Look at the constraint type.
28370 switch (*constraint) {
28372 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28383 if (CallOperandVal->getType()->isIntegerTy())
28384 weight = CW_SpecificReg;
28389 if (type->isFloatingPointTy())
28390 weight = CW_SpecificReg;
28393 if (type->isX86_MMXTy() && Subtarget->hasMMX())
28394 weight = CW_SpecificReg;
28398 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28399 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28400 weight = CW_Register;
28403 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28404 if (C->getZExtValue() <= 31)
28405 weight = CW_Constant;
28409 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28410 if (C->getZExtValue() <= 63)
28411 weight = CW_Constant;
28415 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28416 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28417 weight = CW_Constant;
28421 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28422 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28423 weight = CW_Constant;
28427 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28428 if (C->getZExtValue() <= 3)
28429 weight = CW_Constant;
28433 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28434 if (C->getZExtValue() <= 0xff)
28435 weight = CW_Constant;
28440 if (isa<ConstantFP>(CallOperandVal)) {
28441 weight = CW_Constant;
28445 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28446 if ((C->getSExtValue() >= -0x80000000LL) &&
28447 (C->getSExtValue() <= 0x7fffffffLL))
28448 weight = CW_Constant;
28452 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28453 if (C->getZExtValue() <= 0xffffffff)
28454 weight = CW_Constant;
28461 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28462 /// with another that has more specific requirements based on the type of the
28463 /// corresponding operand.
28464 const char *X86TargetLowering::
28465 LowerXConstraint(EVT ConstraintVT) const {
28466 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28467 // 'f' like normal targets.
28468 if (ConstraintVT.isFloatingPoint()) {
28469 if (Subtarget->hasSSE2())
28471 if (Subtarget->hasSSE1())
28475 return TargetLowering::LowerXConstraint(ConstraintVT);
28478 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28479 /// vector. If it is invalid, don't add anything to Ops.
28480 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28481 std::string &Constraint,
28482 std::vector<SDValue>&Ops,
28483 SelectionDAG &DAG) const {
28486 // Only support length 1 constraints for now.
28487 if (Constraint.length() > 1) return;
28489 char ConstraintLetter = Constraint[0];
28490 switch (ConstraintLetter) {
28493 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28494 if (C->getZExtValue() <= 31) {
28495 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28496 Op.getValueType());
28502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28503 if (C->getZExtValue() <= 63) {
28504 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28505 Op.getValueType());
28511 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28512 if (isInt<8>(C->getSExtValue())) {
28513 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28514 Op.getValueType());
28520 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28521 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28522 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28523 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28524 Op.getValueType());
28530 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28531 if (C->getZExtValue() <= 3) {
28532 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28533 Op.getValueType());
28539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28540 if (C->getZExtValue() <= 255) {
28541 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28542 Op.getValueType());
28548 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28549 if (C->getZExtValue() <= 127) {
28550 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28551 Op.getValueType());
28557 // 32-bit signed value
28558 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28559 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28560 C->getSExtValue())) {
28561 // Widen to 64 bits here to get it sign extended.
28562 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28565 // FIXME gcc accepts some relocatable values here too, but only in certain
28566 // memory models; it's complicated.
28571 // 32-bit unsigned value
28572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28573 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28574 C->getZExtValue())) {
28575 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28576 Op.getValueType());
28580 // FIXME gcc accepts some relocatable values here too, but only in certain
28581 // memory models; it's complicated.
28585 // Literal immediates are always ok.
28586 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28587 // Widen to 64 bits here to get it sign extended.
28588 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28592 // In any sort of PIC mode addresses need to be computed at runtime by
28593 // adding in a register or some sort of table lookup. These can't
28594 // be used as immediates.
28595 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28598 // If we are in non-pic codegen mode, we allow the address of a global (with
28599 // an optional displacement) to be used with 'i'.
28600 GlobalAddressSDNode *GA = nullptr;
28601 int64_t Offset = 0;
28603 // Match either (GA), (GA+C), (GA+C1+C2), etc.
28605 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28606 Offset += GA->getOffset();
28608 } else if (Op.getOpcode() == ISD::ADD) {
28609 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28610 Offset += C->getZExtValue();
28611 Op = Op.getOperand(0);
28614 } else if (Op.getOpcode() == ISD::SUB) {
28615 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28616 Offset += -C->getZExtValue();
28617 Op = Op.getOperand(0);
28622 // Otherwise, this isn't something we can handle, reject it.
28626 const GlobalValue *GV = GA->getGlobal();
28627 // If we require an extra load to get this address, as in PIC mode, we
28628 // can't accept it.
28629 if (isGlobalStubReference(
28630 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28633 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28634 GA->getValueType(0), Offset);
28639 if (Result.getNode()) {
28640 Ops.push_back(Result);
28643 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28646 std::pair<unsigned, const TargetRegisterClass *>
28647 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28648 StringRef Constraint,
28650 // First, see if this is a constraint that directly corresponds to an LLVM
28652 if (Constraint.size() == 1) {
28653 // GCC Constraint Letters
28654 switch (Constraint[0]) {
28656 // TODO: Slight differences here in allocation order and leaving
28657 // RIP in the class. Do they matter any more here than they do
28658 // in the normal allocation?
28659 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28660 if (Subtarget->is64Bit()) {
28661 if (VT == MVT::i32 || VT == MVT::f32)
28662 return std::make_pair(0U, &X86::GR32RegClass);
28663 if (VT == MVT::i16)
28664 return std::make_pair(0U, &X86::GR16RegClass);
28665 if (VT == MVT::i8 || VT == MVT::i1)
28666 return std::make_pair(0U, &X86::GR8RegClass);
28667 if (VT == MVT::i64 || VT == MVT::f64)
28668 return std::make_pair(0U, &X86::GR64RegClass);
28671 // 32-bit fallthrough
28672 case 'Q': // Q_REGS
28673 if (VT == MVT::i32 || VT == MVT::f32)
28674 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28675 if (VT == MVT::i16)
28676 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28677 if (VT == MVT::i8 || VT == MVT::i1)
28678 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28679 if (VT == MVT::i64)
28680 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28682 case 'r': // GENERAL_REGS
28683 case 'l': // INDEX_REGS
28684 if (VT == MVT::i8 || VT == MVT::i1)
28685 return std::make_pair(0U, &X86::GR8RegClass);
28686 if (VT == MVT::i16)
28687 return std::make_pair(0U, &X86::GR16RegClass);
28688 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28689 return std::make_pair(0U, &X86::GR32RegClass);
28690 return std::make_pair(0U, &X86::GR64RegClass);
28691 case 'R': // LEGACY_REGS
28692 if (VT == MVT::i8 || VT == MVT::i1)
28693 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28694 if (VT == MVT::i16)
28695 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28696 if (VT == MVT::i32 || !Subtarget->is64Bit())
28697 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28698 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28699 case 'f': // FP Stack registers.
28700 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28701 // value to the correct fpstack register class.
28702 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28703 return std::make_pair(0U, &X86::RFP32RegClass);
28704 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28705 return std::make_pair(0U, &X86::RFP64RegClass);
28706 return std::make_pair(0U, &X86::RFP80RegClass);
28707 case 'y': // MMX_REGS if MMX allowed.
28708 if (!Subtarget->hasMMX()) break;
28709 return std::make_pair(0U, &X86::VR64RegClass);
28710 case 'Y': // SSE_REGS if SSE2 allowed
28711 if (!Subtarget->hasSSE2()) break;
28713 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28714 if (!Subtarget->hasSSE1()) break;
28716 switch (VT.SimpleTy) {
28718 // Scalar SSE types.
28721 return std::make_pair(0U, &X86::FR32RegClass);
28724 return std::make_pair(0U, &X86::FR64RegClass);
28725 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28733 return std::make_pair(0U, &X86::VR128RegClass);
28741 return std::make_pair(0U, &X86::VR256RegClass);
28746 return std::make_pair(0U, &X86::VR512RegClass);
28752 // Use the default implementation in TargetLowering to convert the register
28753 // constraint into a member of a register class.
28754 std::pair<unsigned, const TargetRegisterClass*> Res;
28755 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28757 // Not found as a standard register?
28759 // Map st(0) -> st(7) -> ST0
28760 if (Constraint.size() == 7 && Constraint[0] == '{' &&
28761 tolower(Constraint[1]) == 's' &&
28762 tolower(Constraint[2]) == 't' &&
28763 Constraint[3] == '(' &&
28764 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28765 Constraint[5] == ')' &&
28766 Constraint[6] == '}') {
28768 Res.first = X86::FP0+Constraint[4]-'0';
28769 Res.second = &X86::RFP80RegClass;
28773 // GCC allows "st(0)" to be called just plain "st".
28774 if (StringRef("{st}").equals_lower(Constraint)) {
28775 Res.first = X86::FP0;
28776 Res.second = &X86::RFP80RegClass;
28781 if (StringRef("{flags}").equals_lower(Constraint)) {
28782 Res.first = X86::EFLAGS;
28783 Res.second = &X86::CCRRegClass;
28787 // 'A' means EAX + EDX.
28788 if (Constraint == "A") {
28789 Res.first = X86::EAX;
28790 Res.second = &X86::GR32_ADRegClass;
28796 // Otherwise, check to see if this is a register class of the wrong value
28797 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28798 // turn into {ax},{dx}.
28799 // MVT::Other is used to specify clobber names.
28800 if (Res.second->hasType(VT) || VT == MVT::Other)
28801 return Res; // Correct type already, nothing to do.
28803 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28804 // return "eax". This should even work for things like getting 64bit integer
28805 // registers when given an f64 type.
28806 const TargetRegisterClass *Class = Res.second;
28807 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28808 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28809 unsigned Size = VT.getSizeInBits();
28810 if (Size == 1) Size = 8;
28811 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28813 Res.first = DestReg;
28814 Res.second = Size == 8 ? &X86::GR8RegClass
28815 : Size == 16 ? &X86::GR16RegClass
28816 : Size == 32 ? &X86::GR32RegClass
28817 : &X86::GR64RegClass;
28818 assert(Res.second->contains(Res.first) && "Register in register class");
28820 // No register found/type mismatch.
28822 Res.second = nullptr;
28824 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28825 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28826 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28827 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28828 Class == &X86::VR512RegClass) {
28829 // Handle references to XMM physical registers that got mapped into the
28830 // wrong class. This can happen with constraints like {xmm0} where the
28831 // target independent register mapper will just pick the first match it can
28832 // find, ignoring the required type.
28834 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28835 if (VT == MVT::f32 || VT == MVT::i32)
28836 Res.second = &X86::FR32RegClass;
28837 else if (VT == MVT::f64 || VT == MVT::i64)
28838 Res.second = &X86::FR64RegClass;
28839 else if (X86::VR128RegClass.hasType(VT))
28840 Res.second = &X86::VR128RegClass;
28841 else if (X86::VR256RegClass.hasType(VT))
28842 Res.second = &X86::VR256RegClass;
28843 else if (X86::VR512RegClass.hasType(VT))
28844 Res.second = &X86::VR512RegClass;
28846 // Type mismatch and not a clobber: Return an error;
28848 Res.second = nullptr;
28855 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28856 const AddrMode &AM, Type *Ty,
28857 unsigned AS) const {
28858 // Scaling factors are not free at all.
28859 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28860 // will take 2 allocations in the out of order engine instead of 1
28861 // for plain addressing mode, i.e. inst (reg1).
28863 // vaddps (%rsi,%drx), %ymm0, %ymm1
28864 // Requires two allocations (one for the load, one for the computation)
28866 // vaddps (%rsi), %ymm0, %ymm1
28867 // Requires just 1 allocation, i.e., freeing allocations for other operations
28868 // and having less micro operations to execute.
28870 // For some X86 architectures, this is even worse because for instance for
28871 // stores, the complex addressing mode forces the instruction to use the
28872 // "load" ports instead of the dedicated "store" port.
28873 // E.g., on Haswell:
28874 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28875 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28876 if (isLegalAddressingMode(DL, AM, Ty, AS))
28877 // Scale represents reg2 * scale, thus account for 1
28878 // as soon as we use a second register.
28879 return AM.Scale != 0;
28883 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28884 // Integer division on x86 is expensive. However, when aggressively optimizing
28885 // for code size, we prefer to use a div instruction, as it is usually smaller
28886 // than the alternative sequence.
28887 // The exception to this is vector division. Since x86 doesn't have vector
28888 // integer division, leaving the division as-is is a loss even in terms of
28889 // size, because it will have to be scalarized, while the alternative code
28890 // sequence can be performed in vector form.
28891 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28892 Attribute::MinSize);
28893 return OptSize && !VT.isVector();
28896 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
28897 if (!Subtarget->is64Bit())
28900 // Update IsSplitCSR in X86MachineFunctionInfo.
28901 X86MachineFunctionInfo *AFI =
28902 Entry->getParent()->getInfo<X86MachineFunctionInfo>();
28903 AFI->setIsSplitCSR(true);
28906 void X86TargetLowering::insertCopiesSplitCSR(
28907 MachineBasicBlock *Entry,
28908 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
28909 const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
28910 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
28914 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
28915 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
28916 MachineBasicBlock::iterator MBBI = Entry->begin();
28917 for (const MCPhysReg *I = IStart; *I; ++I) {
28918 const TargetRegisterClass *RC = nullptr;
28919 if (X86::GR64RegClass.contains(*I))
28920 RC = &X86::GR64RegClass;
28922 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
28924 unsigned NewVR = MRI->createVirtualRegister(RC);
28925 // Create copy from CSR to a virtual register.
28926 // FIXME: this currently does not emit CFI pseudo-instructions, it works
28927 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
28928 // nounwind. If we want to generalize this later, we may need to emit
28929 // CFI pseudo-instructions.
28930 assert(Entry->getParent()->getFunction()->hasFnAttribute(
28931 Attribute::NoUnwind) &&
28932 "Function should be nounwind in insertCopiesSplitCSR!");
28933 Entry->addLiveIn(*I);
28934 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
28937 // Insert the copy-back instructions right before the terminator.
28938 for (auto *Exit : Exits)
28939 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
28940 TII->get(TargetOpcode::COPY), *I)