1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
59 #define DEBUG_TYPE "x86-isel"
61 STATISTIC(NumTailCalls, "Number of tail calls");
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64 "x86-experimental-vector-widening-legalization", cl::init(false),
65 cl::desc("Enable an experimental vector type legalization through widening "
66 "rather than promotion."),
69 static cl::opt<int> ReciprocalEstimateRefinementSteps(
70 "x86-recip-refinement-steps", cl::init(1),
71 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
72 "result of the hardware reciprocal estimate instruction."),
75 // Forward declarations.
76 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
79 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
80 SelectionDAG &DAG, SDLoc dl,
81 unsigned vectorWidth) {
82 assert((vectorWidth == 128 || vectorWidth == 256) &&
83 "Unsupported vector width");
84 EVT VT = Vec.getValueType();
85 EVT ElVT = VT.getVectorElementType();
86 unsigned Factor = VT.getSizeInBits()/vectorWidth;
87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88 VT.getVectorNumElements()/Factor);
90 // Extract from UNDEF is UNDEF.
91 if (Vec.getOpcode() == ISD::UNDEF)
92 return DAG.getUNDEF(ResultVT);
94 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
95 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
97 // This is the index of the first element of the vectorWidth-bit chunk
99 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
102 // If the input is a buildvector just emit a smaller one.
103 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
104 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
105 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
108 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
109 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit boundary. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
163 SelectionDAG &DAG,SDLoc dl) {
164 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
165 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
169 SelectionDAG &DAG, SDLoc dl) {
170 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
171 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
175 /// instructions. This is used because creating CONCAT_VECTOR nodes of
176 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
177 /// large BUILD_VECTORS.
178 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
179 unsigned NumElems, SelectionDAG &DAG,
181 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
182 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
186 unsigned NumElems, SelectionDAG &DAG,
188 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
189 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
193 const X86Subtarget &STI)
194 : TargetLowering(TM), Subtarget(&STI) {
195 X86ScalarSSEf64 = Subtarget->hasSSE2();
196 X86ScalarSSEf32 = Subtarget->hasSSE1();
197 TD = getDataLayout();
199 // Set up the TargetLowering object.
200 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
202 // X86 is weird. It always uses i8 for shift amounts and setcc results.
203 setBooleanContents(ZeroOrOneBooleanContent);
204 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
205 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
207 // For 64-bit, since we have so many registers, use the ILP scheduler.
208 // For 32-bit, use the register pressure specific scheduling.
209 // For Atom, always use ILP scheduling.
210 if (Subtarget->isAtom())
211 setSchedulingPreference(Sched::ILP);
212 else if (Subtarget->is64Bit())
213 setSchedulingPreference(Sched::ILP);
215 setSchedulingPreference(Sched::RegPressure);
216 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
217 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
219 // Bypass expensive divides on Atom when compiling with O2.
220 if (TM.getOptLevel() >= CodeGenOpt::Default) {
221 if (Subtarget->hasSlowDivide32())
222 addBypassSlowDiv(32, 8);
223 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
224 addBypassSlowDiv(64, 16);
227 if (Subtarget->isTargetKnownWindowsMSVC()) {
228 // Setup Windows compiler runtime calls.
229 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
230 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
231 setLibcallName(RTLIB::SREM_I64, "_allrem");
232 setLibcallName(RTLIB::UREM_I64, "_aullrem");
233 setLibcallName(RTLIB::MUL_I64, "_allmul");
234 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
235 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
236 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
237 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
238 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
240 // The _ftol2 runtime function has an unusual calling conv, which
241 // is modeled by a special pseudo-instruction.
242 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
243 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
244 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
245 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
248 if (Subtarget->isTargetDarwin()) {
249 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
250 setUseUnderscoreSetJmp(false);
251 setUseUnderscoreLongJmp(false);
252 } else if (Subtarget->isTargetWindowsGNU()) {
253 // MS runtime is weird: it exports _setjmp, but longjmp!
254 setUseUnderscoreSetJmp(true);
255 setUseUnderscoreLongJmp(false);
257 setUseUnderscoreSetJmp(true);
258 setUseUnderscoreLongJmp(true);
261 // Set up the register classes.
262 addRegisterClass(MVT::i8, &X86::GR8RegClass);
263 addRegisterClass(MVT::i16, &X86::GR16RegClass);
264 addRegisterClass(MVT::i32, &X86::GR32RegClass);
265 if (Subtarget->is64Bit())
266 addRegisterClass(MVT::i64, &X86::GR64RegClass);
268 for (MVT VT : MVT::integer_valuetypes())
269 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
271 // We don't accept any truncstore of integer registers.
272 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
273 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
274 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
275 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
276 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
277 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
279 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
281 // SETOEQ and SETUNE require checking two conditions.
282 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
283 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
284 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
285 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
286 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
287 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
289 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
291 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
292 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
293 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
295 if (Subtarget->is64Bit()) {
296 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
297 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
298 } else if (!TM.Options.UseSoftFloat) {
299 // We have an algorithm for SSE2->double, and we turn this into a
300 // 64-bit FILD followed by conditional FADD for other targets.
301 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
302 // We have an algorithm for SSE2, and we turn this into a 64-bit
303 // FILD for other targets.
304 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
307 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
309 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
310 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
312 if (!TM.Options.UseSoftFloat) {
313 // SSE has no i16 to fp conversion, only i32
314 if (X86ScalarSSEf32) {
315 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
316 // f32 and f64 cases are Legal, f80 case is not
317 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
319 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
320 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
323 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
324 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
327 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
328 // are Legal, f80 is custom lowered.
329 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
330 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
332 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
334 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
335 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
342 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
343 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
346 // Handle FP_TO_UINT by promoting the destination to a larger signed
348 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
349 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
350 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
352 if (Subtarget->is64Bit()) {
353 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
354 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
355 } else if (!TM.Options.UseSoftFloat) {
356 // Since AVX is a superset of SSE3, only check for SSE here.
357 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
358 // Expand FP_TO_UINT into a select.
359 // FIXME: We would like to use a Custom expander here eventually to do
360 // the optimal thing for SSE vs. the default expansion in the legalizer.
361 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
363 // With SSE3 we can use fisttpll to convert to a signed i64; without
364 // SSE, we're stuck with a fistpll.
365 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
368 if (isTargetFTOL()) {
369 // Use the _ftol2 runtime function, which has a pseudo-instruction
370 // to handle its weird calling convention.
371 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
374 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
375 if (!X86ScalarSSEf64) {
376 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
377 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
380 // Without SSE, i64->f64 goes through memory.
381 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
385 // Scalar integer divide and remainder are lowered to use operations that
386 // produce two results, to match the available instructions. This exposes
387 // the two-result form to trivial CSE, which is able to combine x/y and x%y
388 // into a single instruction.
390 // Scalar integer multiply-high is also lowered to use two-result
391 // operations, to match the available instructions. However, plain multiply
392 // (low) operations are left as Legal, as there are single-result
393 // instructions for this in x86. Using the two-result multiply instructions
394 // when both high and low results are needed must be arranged by dagcombine.
395 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
397 setOperationAction(ISD::MULHS, VT, Expand);
398 setOperationAction(ISD::MULHU, VT, Expand);
399 setOperationAction(ISD::SDIV, VT, Expand);
400 setOperationAction(ISD::UDIV, VT, Expand);
401 setOperationAction(ISD::SREM, VT, Expand);
402 setOperationAction(ISD::UREM, VT, Expand);
404 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
405 setOperationAction(ISD::ADDC, VT, Custom);
406 setOperationAction(ISD::ADDE, VT, Custom);
407 setOperationAction(ISD::SUBC, VT, Custom);
408 setOperationAction(ISD::SUBE, VT, Custom);
411 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
412 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
413 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
414 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
415 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
416 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
417 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
418 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
419 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
420 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
421 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
422 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
423 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
424 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
425 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
426 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
427 if (Subtarget->is64Bit())
428 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
429 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
430 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
431 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
432 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
433 setOperationAction(ISD::FREM , MVT::f32 , Expand);
434 setOperationAction(ISD::FREM , MVT::f64 , Expand);
435 setOperationAction(ISD::FREM , MVT::f80 , Expand);
436 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
438 // Promote the i8 variants and force them on up to i32 which has a shorter
440 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
441 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
442 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
443 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
444 if (Subtarget->hasBMI()) {
445 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
446 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
447 if (Subtarget->is64Bit())
448 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
450 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
451 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
452 if (Subtarget->is64Bit())
453 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
456 if (Subtarget->hasLZCNT()) {
457 // When promoting the i8 variants, force them to i32 for a shorter
459 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
461 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
462 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
463 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
469 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
470 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
471 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
474 if (Subtarget->is64Bit()) {
475 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
480 // Special handling for half-precision floating point conversions.
481 // If we don't have F16C support, then lower half float conversions
482 // into library calls.
483 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
484 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
485 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
488 // There's never any support for operations beyond MVT::f32.
489 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
490 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
491 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
492 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
494 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
495 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
496 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
497 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
498 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
499 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
501 if (Subtarget->hasPOPCNT()) {
502 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
504 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
505 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
506 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
507 if (Subtarget->is64Bit())
508 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
511 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
513 if (!Subtarget->hasMOVBE())
514 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
516 // These should be promoted to a larger select which is supported.
517 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
518 // X86 wants to expand cmov itself.
519 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
520 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
521 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
524 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
527 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
531 if (Subtarget->is64Bit()) {
532 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
533 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
535 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
536 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
537 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
538 // support continuation, user-level threading, and etc.. As a result, no
539 // other SjLj exception interfaces are implemented and please don't build
540 // your own exception handling based on them.
541 // LLVM/Clang supports zero-cost DWARF exception handling.
542 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
543 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
546 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
547 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
548 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
549 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
550 if (Subtarget->is64Bit())
551 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
552 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
553 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
554 if (Subtarget->is64Bit()) {
555 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
556 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
557 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
558 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
559 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
561 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
562 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
567 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
568 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
571 if (Subtarget->hasSSE1())
572 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
574 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
576 // Expand certain atomics
577 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
579 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
580 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
581 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
584 if (Subtarget->hasCmpxchg16b()) {
585 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
588 // FIXME - use subtarget debug flags
589 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
590 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
591 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
594 if (Subtarget->is64Bit()) {
595 setExceptionPointerRegister(X86::RAX);
596 setExceptionSelectorRegister(X86::RDX);
598 setExceptionPointerRegister(X86::EAX);
599 setExceptionSelectorRegister(X86::EDX);
601 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
602 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
604 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
605 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
607 setOperationAction(ISD::TRAP, MVT::Other, Legal);
608 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
610 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
611 setOperationAction(ISD::VASTART , MVT::Other, Custom);
612 setOperationAction(ISD::VAEND , MVT::Other, Expand);
613 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
614 // TargetInfo::X86_64ABIBuiltinVaList
615 setOperationAction(ISD::VAARG , MVT::Other, Custom);
616 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
618 // TargetInfo::CharPtrBuiltinVaList
619 setOperationAction(ISD::VAARG , MVT::Other, Expand);
620 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
623 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
624 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
626 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
628 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
629 // f32 and f64 use SSE.
630 // Set up the FP register classes.
631 addRegisterClass(MVT::f32, &X86::FR32RegClass);
632 addRegisterClass(MVT::f64, &X86::FR64RegClass);
634 // Use ANDPD to simulate FABS.
635 setOperationAction(ISD::FABS , MVT::f64, Custom);
636 setOperationAction(ISD::FABS , MVT::f32, Custom);
638 // Use XORP to simulate FNEG.
639 setOperationAction(ISD::FNEG , MVT::f64, Custom);
640 setOperationAction(ISD::FNEG , MVT::f32, Custom);
642 // Use ANDPD and ORPD to simulate FCOPYSIGN.
643 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
644 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
646 // Lower this to FGETSIGNx86 plus an AND.
647 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
648 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
650 // We don't support sin/cos/fmod
651 setOperationAction(ISD::FSIN , MVT::f64, Expand);
652 setOperationAction(ISD::FCOS , MVT::f64, Expand);
653 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
654 setOperationAction(ISD::FSIN , MVT::f32, Expand);
655 setOperationAction(ISD::FCOS , MVT::f32, Expand);
656 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
658 // Expand FP immediates into loads from the stack, except for the special
660 addLegalFPImmediate(APFloat(+0.0)); // xorpd
661 addLegalFPImmediate(APFloat(+0.0f)); // xorps
662 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
663 // Use SSE for f32, x87 for f64.
664 // Set up the FP register classes.
665 addRegisterClass(MVT::f32, &X86::FR32RegClass);
666 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
668 // Use ANDPS to simulate FABS.
669 setOperationAction(ISD::FABS , MVT::f32, Custom);
671 // Use XORP to simulate FNEG.
672 setOperationAction(ISD::FNEG , MVT::f32, Custom);
674 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
676 // Use ANDPS and ORPS to simulate FCOPYSIGN.
677 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
678 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
680 // We don't support sin/cos/fmod
681 setOperationAction(ISD::FSIN , MVT::f32, Expand);
682 setOperationAction(ISD::FCOS , MVT::f32, Expand);
683 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
685 // Special cases we handle for FP constants.
686 addLegalFPImmediate(APFloat(+0.0f)); // xorps
687 addLegalFPImmediate(APFloat(+0.0)); // FLD0
688 addLegalFPImmediate(APFloat(+1.0)); // FLD1
689 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
690 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
692 if (!TM.Options.UnsafeFPMath) {
693 setOperationAction(ISD::FSIN , MVT::f64, Expand);
694 setOperationAction(ISD::FCOS , MVT::f64, Expand);
695 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
697 } else if (!TM.Options.UseSoftFloat) {
698 // f32 and f64 in x87.
699 // Set up the FP register classes.
700 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
701 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
703 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
704 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
705 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
706 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FSIN , MVT::f32, Expand);
711 setOperationAction(ISD::FCOS , MVT::f64, Expand);
712 setOperationAction(ISD::FCOS , MVT::f32, Expand);
713 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
716 addLegalFPImmediate(APFloat(+0.0)); // FLD0
717 addLegalFPImmediate(APFloat(+1.0)); // FLD1
718 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
719 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
720 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
721 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
722 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
723 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
726 // We don't support FMA.
727 setOperationAction(ISD::FMA, MVT::f64, Expand);
728 setOperationAction(ISD::FMA, MVT::f32, Expand);
730 // Long double always uses X87.
731 if (!TM.Options.UseSoftFloat) {
732 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
733 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
734 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
736 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
737 addLegalFPImmediate(TmpFlt); // FLD0
739 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
742 APFloat TmpFlt2(+1.0);
743 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
745 addLegalFPImmediate(TmpFlt2); // FLD1
746 TmpFlt2.changeSign();
747 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
750 if (!TM.Options.UnsafeFPMath) {
751 setOperationAction(ISD::FSIN , MVT::f80, Expand);
752 setOperationAction(ISD::FCOS , MVT::f80, Expand);
753 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
756 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
757 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
758 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
759 setOperationAction(ISD::FRINT, MVT::f80, Expand);
760 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
761 setOperationAction(ISD::FMA, MVT::f80, Expand);
764 // Always use a library call for pow.
765 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
766 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
767 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
769 setOperationAction(ISD::FLOG, MVT::f80, Expand);
770 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
771 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
772 setOperationAction(ISD::FEXP, MVT::f80, Expand);
773 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
774 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
775 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
777 // First set operation action for all vector types to either promote
778 // (for widening) or expand (for scalarization). Then we will selectively
779 // turn on ones that can be effectively codegen'd.
780 for (MVT VT : MVT::vector_valuetypes()) {
781 setOperationAction(ISD::ADD , VT, Expand);
782 setOperationAction(ISD::SUB , VT, Expand);
783 setOperationAction(ISD::FADD, VT, Expand);
784 setOperationAction(ISD::FNEG, VT, Expand);
785 setOperationAction(ISD::FSUB, VT, Expand);
786 setOperationAction(ISD::MUL , VT, Expand);
787 setOperationAction(ISD::FMUL, VT, Expand);
788 setOperationAction(ISD::SDIV, VT, Expand);
789 setOperationAction(ISD::UDIV, VT, Expand);
790 setOperationAction(ISD::FDIV, VT, Expand);
791 setOperationAction(ISD::SREM, VT, Expand);
792 setOperationAction(ISD::UREM, VT, Expand);
793 setOperationAction(ISD::LOAD, VT, Expand);
794 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
796 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
797 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
798 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
799 setOperationAction(ISD::FABS, VT, Expand);
800 setOperationAction(ISD::FSIN, VT, Expand);
801 setOperationAction(ISD::FSINCOS, VT, Expand);
802 setOperationAction(ISD::FCOS, VT, Expand);
803 setOperationAction(ISD::FSINCOS, VT, Expand);
804 setOperationAction(ISD::FREM, VT, Expand);
805 setOperationAction(ISD::FMA, VT, Expand);
806 setOperationAction(ISD::FPOWI, VT, Expand);
807 setOperationAction(ISD::FSQRT, VT, Expand);
808 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
809 setOperationAction(ISD::FFLOOR, VT, Expand);
810 setOperationAction(ISD::FCEIL, VT, Expand);
811 setOperationAction(ISD::FTRUNC, VT, Expand);
812 setOperationAction(ISD::FRINT, VT, Expand);
813 setOperationAction(ISD::FNEARBYINT, VT, Expand);
814 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
815 setOperationAction(ISD::MULHS, VT, Expand);
816 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
817 setOperationAction(ISD::MULHU, VT, Expand);
818 setOperationAction(ISD::SDIVREM, VT, Expand);
819 setOperationAction(ISD::UDIVREM, VT, Expand);
820 setOperationAction(ISD::FPOW, VT, Expand);
821 setOperationAction(ISD::CTPOP, VT, Expand);
822 setOperationAction(ISD::CTTZ, VT, Expand);
823 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
824 setOperationAction(ISD::CTLZ, VT, Expand);
825 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
826 setOperationAction(ISD::SHL, VT, Expand);
827 setOperationAction(ISD::SRA, VT, Expand);
828 setOperationAction(ISD::SRL, VT, Expand);
829 setOperationAction(ISD::ROTL, VT, Expand);
830 setOperationAction(ISD::ROTR, VT, Expand);
831 setOperationAction(ISD::BSWAP, VT, Expand);
832 setOperationAction(ISD::SETCC, VT, Expand);
833 setOperationAction(ISD::FLOG, VT, Expand);
834 setOperationAction(ISD::FLOG2, VT, Expand);
835 setOperationAction(ISD::FLOG10, VT, Expand);
836 setOperationAction(ISD::FEXP, VT, Expand);
837 setOperationAction(ISD::FEXP2, VT, Expand);
838 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
839 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
840 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
841 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
842 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
843 setOperationAction(ISD::TRUNCATE, VT, Expand);
844 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
845 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
846 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
847 setOperationAction(ISD::VSELECT, VT, Expand);
848 setOperationAction(ISD::SELECT_CC, VT, Expand);
849 for (MVT InnerVT : MVT::vector_valuetypes()) {
850 setTruncStoreAction(InnerVT, VT, Expand);
852 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
853 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
855 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
856 // types, we have to deal with them whether we ask for Expansion or not.
857 // Setting Expand causes its own optimisation problems though, so leave
859 if (VT.getVectorElementType() == MVT::i1)
860 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
864 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
865 // with -msoft-float, disable use of MMX as well.
866 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
867 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
868 // No operations on x86mmx supported, everything uses intrinsics.
871 // MMX-sized vectors (other than x86mmx) are expected to be expanded
872 // into smaller operations.
873 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
874 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
875 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
876 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
877 setOperationAction(ISD::AND, MVT::v8i8, Expand);
878 setOperationAction(ISD::AND, MVT::v4i16, Expand);
879 setOperationAction(ISD::AND, MVT::v2i32, Expand);
880 setOperationAction(ISD::AND, MVT::v1i64, Expand);
881 setOperationAction(ISD::OR, MVT::v8i8, Expand);
882 setOperationAction(ISD::OR, MVT::v4i16, Expand);
883 setOperationAction(ISD::OR, MVT::v2i32, Expand);
884 setOperationAction(ISD::OR, MVT::v1i64, Expand);
885 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
886 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
887 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
888 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
889 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
890 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
891 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
892 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
893 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
894 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
895 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
896 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
897 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
898 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
899 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
900 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
901 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
903 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
904 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
906 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
907 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
908 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
909 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
910 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
911 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
912 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
913 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
916 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
918 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
919 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
922 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
923 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
925 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
926 // registers cannot be used even for integer operations.
927 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
928 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
929 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
930 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
932 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
933 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
934 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
935 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
936 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
937 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
938 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
939 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
940 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
941 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
942 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
943 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
944 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
945 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
946 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
947 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
948 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
949 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
950 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
951 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
952 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
953 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
955 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
956 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
957 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
958 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
960 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
961 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
966 // Only provide customized ctpop vector bit twiddling for vector types we
967 // know to perform better than using the popcnt instructions on each vector
968 // element. If popcnt isn't supported, always provide the custom version.
969 if (!Subtarget->hasPOPCNT()) {
970 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
971 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
974 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
975 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
976 MVT VT = (MVT::SimpleValueType)i;
977 // Do not attempt to custom lower non-power-of-2 vectors
978 if (!isPowerOf2_32(VT.getVectorNumElements()))
980 // Do not attempt to custom lower non-128-bit vectors
981 if (!VT.is128BitVector())
983 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
984 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
985 setOperationAction(ISD::VSELECT, VT, Custom);
986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
989 // We support custom legalizing of sext and anyext loads for specific
990 // memory vector types which we can load as a scalar (or sequence of
991 // scalars) and extend in-register to a legal 128-bit vector type. For sext
992 // loads these must work with a single scalar load.
993 for (MVT VT : MVT::integer_vector_valuetypes()) {
994 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
995 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
996 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
997 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
998 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
999 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1000 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1001 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1002 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1005 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1006 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1007 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1008 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1009 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1010 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1014 if (Subtarget->is64Bit()) {
1015 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1019 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1020 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1021 MVT VT = (MVT::SimpleValueType)i;
1023 // Do not attempt to promote non-128-bit vectors
1024 if (!VT.is128BitVector())
1027 setOperationAction(ISD::AND, VT, Promote);
1028 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1029 setOperationAction(ISD::OR, VT, Promote);
1030 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1031 setOperationAction(ISD::XOR, VT, Promote);
1032 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1033 setOperationAction(ISD::LOAD, VT, Promote);
1034 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1035 setOperationAction(ISD::SELECT, VT, Promote);
1036 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1039 // Custom lower v2i64 and v2f64 selects.
1040 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1042 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1043 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1045 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1046 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1048 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1049 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1050 // As there is no 64-bit GPR available, we need build a special custom
1051 // sequence to convert from v2i32 to v2f32.
1052 if (!Subtarget->is64Bit())
1053 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1055 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1056 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1058 for (MVT VT : MVT::fp_vector_valuetypes())
1059 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1061 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1062 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1063 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1066 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1067 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1068 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1069 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1070 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1071 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1072 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1073 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1074 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1075 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1076 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1078 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1079 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1080 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1081 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1082 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1083 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1084 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1085 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1086 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1087 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1089 // FIXME: Do we need to handle scalar-to-vector here?
1090 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1092 // We directly match byte blends in the backend as they match the VSELECT
1094 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1096 // SSE41 brings specific instructions for doing vector sign extend even in
1097 // cases where we don't have SRA.
1098 for (MVT VT : MVT::integer_vector_valuetypes()) {
1099 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1100 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1101 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1104 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1105 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1106 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1107 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1108 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1109 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1110 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1112 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1113 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1114 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1115 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1116 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1117 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1119 // i8 and i16 vectors are custom because the source register and source
1120 // source memory operand types are not the same width. f32 vectors are
1121 // custom since the immediate controlling the insert encodes additional
1123 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1124 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1125 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1126 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1128 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1129 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1130 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1131 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1133 // FIXME: these should be Legal, but that's only for the case where
1134 // the index is constant. For now custom expand to deal with that.
1135 if (Subtarget->is64Bit()) {
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1137 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1141 if (Subtarget->hasSSE2()) {
1142 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1143 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1145 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1146 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1148 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1149 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1151 // In the customized shift lowering, the legal cases in AVX2 will be
1153 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1154 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1156 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1157 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1159 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1162 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1163 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1164 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1165 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1166 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1167 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1168 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1170 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1171 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1172 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1174 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1175 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1176 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1177 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1178 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1179 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1180 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1181 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1182 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1183 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1184 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1185 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1187 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1188 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1189 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1190 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1191 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1192 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1193 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1194 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1195 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1196 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1197 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1198 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1200 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1201 // even though v8i16 is a legal type.
1202 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1203 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1204 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1206 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1207 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1208 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1210 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1211 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1213 for (MVT VT : MVT::fp_vector_valuetypes())
1214 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1216 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1217 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1219 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1220 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1222 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1223 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1225 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1226 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1227 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1228 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1230 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1231 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1232 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1234 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1235 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1236 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1237 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1238 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1239 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1240 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1241 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1242 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1243 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1244 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1245 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1247 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1248 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1249 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1250 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1251 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1252 setOperationAction(ISD::FMA, MVT::f32, Legal);
1253 setOperationAction(ISD::FMA, MVT::f64, Legal);
1256 if (Subtarget->hasInt256()) {
1257 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1258 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1259 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1260 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1262 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1263 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1264 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1265 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1267 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1268 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1269 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1270 // Don't lower v32i8 because there is no 128-bit byte mul
1272 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1273 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1274 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1275 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1277 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1278 // when we have a 256bit-wide blend with immediate.
1279 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1281 // Only provide customized ctpop vector bit twiddling for vector types we
1282 // know to perform better than using the popcnt instructions on each
1283 // vector element. If popcnt isn't supported, always provide the custom
1285 if (!Subtarget->hasPOPCNT())
1286 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1288 // Custom CTPOP always performs better on natively supported v8i32
1289 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1291 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1292 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1293 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1294 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1295 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1296 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1297 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1299 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1300 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1301 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1302 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1303 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1304 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1306 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1307 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1308 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1309 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1311 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1312 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1313 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1314 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1316 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1317 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1318 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1319 // Don't lower v32i8 because there is no 128-bit byte mul
1322 // In the customized shift lowering, the legal cases in AVX2 will be
1324 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1325 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1327 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1328 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1330 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1332 // Custom lower several nodes for 256-bit types.
1333 for (MVT VT : MVT::vector_valuetypes()) {
1334 if (VT.getScalarSizeInBits() >= 32) {
1335 setOperationAction(ISD::MLOAD, VT, Legal);
1336 setOperationAction(ISD::MSTORE, VT, Legal);
1338 // Extract subvector is special because the value type
1339 // (result) is 128-bit but the source is 256-bit wide.
1340 if (VT.is128BitVector()) {
1341 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1343 // Do not attempt to custom lower other non-256-bit vectors
1344 if (!VT.is256BitVector())
1347 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1348 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1349 setOperationAction(ISD::VSELECT, VT, Custom);
1350 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1352 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1353 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1354 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1357 if (Subtarget->hasInt256())
1358 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1361 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1362 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1363 MVT VT = (MVT::SimpleValueType)i;
1365 // Do not attempt to promote non-256-bit vectors
1366 if (!VT.is256BitVector())
1369 setOperationAction(ISD::AND, VT, Promote);
1370 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1371 setOperationAction(ISD::OR, VT, Promote);
1372 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1373 setOperationAction(ISD::XOR, VT, Promote);
1374 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1375 setOperationAction(ISD::LOAD, VT, Promote);
1376 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1377 setOperationAction(ISD::SELECT, VT, Promote);
1378 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1382 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1383 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1384 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1385 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1386 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1388 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1389 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1390 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1392 for (MVT VT : MVT::fp_vector_valuetypes())
1393 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1395 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1396 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1397 setOperationAction(ISD::XOR, MVT::i1, Legal);
1398 setOperationAction(ISD::OR, MVT::i1, Legal);
1399 setOperationAction(ISD::AND, MVT::i1, Legal);
1400 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1401 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1402 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1403 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1404 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1406 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1407 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1408 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1409 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1410 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1411 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1413 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1414 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1415 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1416 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1417 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1418 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1419 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1420 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1423 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1424 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1425 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1426 if (Subtarget->is64Bit()) {
1427 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1428 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1429 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1430 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1432 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1433 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1434 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1435 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1436 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1437 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1438 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1439 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1440 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1441 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1442 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1443 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1444 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1445 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1447 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1448 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1449 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1450 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1451 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1452 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1453 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1454 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1455 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1456 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1457 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1458 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1459 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1461 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1462 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1463 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1464 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1465 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1466 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1467 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1468 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1469 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1470 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1474 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1475 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1476 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1477 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1479 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1480 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1482 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1484 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1485 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1486 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1487 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1488 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1489 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1491 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1492 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1494 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1495 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1497 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1498 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1500 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1502 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1503 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1505 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1506 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1508 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1509 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1511 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1512 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1513 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1514 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1515 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1516 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1518 if (Subtarget->hasCDI()) {
1519 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1520 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1523 // Custom lower several nodes.
1524 for (MVT VT : MVT::vector_valuetypes()) {
1525 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1526 // Extract subvector is special because the value type
1527 // (result) is 256/128-bit but the source is 512-bit wide.
1528 if (VT.is128BitVector() || VT.is256BitVector()) {
1529 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1531 if (VT.getVectorElementType() == MVT::i1)
1532 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1534 // Do not attempt to custom lower other non-512-bit vectors
1535 if (!VT.is512BitVector())
1538 if ( EltSize >= 32) {
1539 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1540 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1541 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1542 setOperationAction(ISD::VSELECT, VT, Legal);
1543 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1544 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1545 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1546 setOperationAction(ISD::MLOAD, VT, Legal);
1547 setOperationAction(ISD::MSTORE, VT, Legal);
1550 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1551 MVT VT = (MVT::SimpleValueType)i;
1553 // Do not attempt to promote non-512-bit vectors.
1554 if (!VT.is512BitVector())
1557 setOperationAction(ISD::SELECT, VT, Promote);
1558 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1562 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1563 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1564 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1566 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1567 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1569 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1570 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1571 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1572 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1573 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1574 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1575 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1576 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1577 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1579 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1580 const MVT VT = (MVT::SimpleValueType)i;
1582 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1584 // Do not attempt to promote non-512-bit vectors.
1585 if (!VT.is512BitVector())
1589 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1590 setOperationAction(ISD::VSELECT, VT, Legal);
1595 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1596 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1597 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1599 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1600 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1601 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Legal);
1603 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1604 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1605 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1606 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1607 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1608 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1611 // We want to custom lower some of our intrinsics.
1612 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1613 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1614 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1615 if (!Subtarget->is64Bit())
1616 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1618 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1619 // handle type legalization for these operations here.
1621 // FIXME: We really should do custom legalization for addition and
1622 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1623 // than generic legalization for 64-bit multiplication-with-overflow, though.
1624 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1625 // Add/Sub/Mul with overflow operations are custom lowered.
1627 setOperationAction(ISD::SADDO, VT, Custom);
1628 setOperationAction(ISD::UADDO, VT, Custom);
1629 setOperationAction(ISD::SSUBO, VT, Custom);
1630 setOperationAction(ISD::USUBO, VT, Custom);
1631 setOperationAction(ISD::SMULO, VT, Custom);
1632 setOperationAction(ISD::UMULO, VT, Custom);
1636 if (!Subtarget->is64Bit()) {
1637 // These libcalls are not available in 32-bit.
1638 setLibcallName(RTLIB::SHL_I128, nullptr);
1639 setLibcallName(RTLIB::SRL_I128, nullptr);
1640 setLibcallName(RTLIB::SRA_I128, nullptr);
1643 // Combine sin / cos into one node or libcall if possible.
1644 if (Subtarget->hasSinCos()) {
1645 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1646 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1647 if (Subtarget->isTargetDarwin()) {
1648 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1649 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1650 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1651 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1655 if (Subtarget->isTargetWin64()) {
1656 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1657 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1658 setOperationAction(ISD::SREM, MVT::i128, Custom);
1659 setOperationAction(ISD::UREM, MVT::i128, Custom);
1660 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1661 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1664 // We have target-specific dag combine patterns for the following nodes:
1665 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1666 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1667 setTargetDAGCombine(ISD::BITCAST);
1668 setTargetDAGCombine(ISD::VSELECT);
1669 setTargetDAGCombine(ISD::SELECT);
1670 setTargetDAGCombine(ISD::SHL);
1671 setTargetDAGCombine(ISD::SRA);
1672 setTargetDAGCombine(ISD::SRL);
1673 setTargetDAGCombine(ISD::OR);
1674 setTargetDAGCombine(ISD::AND);
1675 setTargetDAGCombine(ISD::ADD);
1676 setTargetDAGCombine(ISD::FADD);
1677 setTargetDAGCombine(ISD::FSUB);
1678 setTargetDAGCombine(ISD::FMA);
1679 setTargetDAGCombine(ISD::SUB);
1680 setTargetDAGCombine(ISD::LOAD);
1681 setTargetDAGCombine(ISD::MLOAD);
1682 setTargetDAGCombine(ISD::STORE);
1683 setTargetDAGCombine(ISD::MSTORE);
1684 setTargetDAGCombine(ISD::ZERO_EXTEND);
1685 setTargetDAGCombine(ISD::ANY_EXTEND);
1686 setTargetDAGCombine(ISD::SIGN_EXTEND);
1687 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1688 setTargetDAGCombine(ISD::TRUNCATE);
1689 setTargetDAGCombine(ISD::SINT_TO_FP);
1690 setTargetDAGCombine(ISD::SETCC);
1691 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1692 setTargetDAGCombine(ISD::BUILD_VECTOR);
1693 setTargetDAGCombine(ISD::MUL);
1694 setTargetDAGCombine(ISD::XOR);
1696 computeRegisterProperties(Subtarget->getRegisterInfo());
1698 // On Darwin, -Os means optimize for size without hurting performance,
1699 // do not reduce the limit.
1700 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1701 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1702 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1703 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1704 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1705 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1706 setPrefLoopAlignment(4); // 2^4 bytes.
1708 // Predictable cmov don't hurt on atom because it's in-order.
1709 PredictableSelectIsExpensive = !Subtarget->isAtom();
1710 EnableExtLdPromotion = true;
1711 setPrefFunctionAlignment(4); // 2^4 bytes.
1713 verifyIntrinsicTables();
1716 // This has so far only been implemented for 64-bit MachO.
1717 bool X86TargetLowering::useLoadStackGuardNode() const {
1718 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1721 TargetLoweringBase::LegalizeTypeAction
1722 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1723 if (ExperimentalVectorWideningLegalization &&
1724 VT.getVectorNumElements() != 1 &&
1725 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1726 return TypeWidenVector;
1728 return TargetLoweringBase::getPreferredVectorAction(VT);
1731 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1733 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1735 const unsigned NumElts = VT.getVectorNumElements();
1736 const EVT EltVT = VT.getVectorElementType();
1737 if (VT.is512BitVector()) {
1738 if (Subtarget->hasAVX512())
1739 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1740 EltVT == MVT::f32 || EltVT == MVT::f64)
1742 case 8: return MVT::v8i1;
1743 case 16: return MVT::v16i1;
1745 if (Subtarget->hasBWI())
1746 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1748 case 32: return MVT::v32i1;
1749 case 64: return MVT::v64i1;
1753 if (VT.is256BitVector() || VT.is128BitVector()) {
1754 if (Subtarget->hasVLX())
1755 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1756 EltVT == MVT::f32 || EltVT == MVT::f64)
1758 case 2: return MVT::v2i1;
1759 case 4: return MVT::v4i1;
1760 case 8: return MVT::v8i1;
1762 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1763 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1765 case 8: return MVT::v8i1;
1766 case 16: return MVT::v16i1;
1767 case 32: return MVT::v32i1;
1771 return VT.changeVectorElementTypeToInteger();
1774 /// Helper for getByValTypeAlignment to determine
1775 /// the desired ByVal argument alignment.
1776 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1779 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1780 if (VTy->getBitWidth() == 128)
1782 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1783 unsigned EltAlign = 0;
1784 getMaxByValAlign(ATy->getElementType(), EltAlign);
1785 if (EltAlign > MaxAlign)
1786 MaxAlign = EltAlign;
1787 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1788 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1789 unsigned EltAlign = 0;
1790 getMaxByValAlign(STy->getElementType(i), EltAlign);
1791 if (EltAlign > MaxAlign)
1792 MaxAlign = EltAlign;
1799 /// Return the desired alignment for ByVal aggregate
1800 /// function arguments in the caller parameter area. For X86, aggregates
1801 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1802 /// are at 4-byte boundaries.
1803 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1804 if (Subtarget->is64Bit()) {
1805 // Max of 8 and alignment of type.
1806 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1813 if (Subtarget->hasSSE1())
1814 getMaxByValAlign(Ty, Align);
1818 /// Returns the target specific optimal type for load
1819 /// and store operations as a result of memset, memcpy, and memmove
1820 /// lowering. If DstAlign is zero that means it's safe to destination
1821 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1822 /// means there isn't a need to check it against alignment requirement,
1823 /// probably because the source does not need to be loaded. If 'IsMemset' is
1824 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1825 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1826 /// source is constant so it does not need to be loaded.
1827 /// It returns EVT::Other if the type should be determined using generic
1828 /// target-independent logic.
1830 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1831 unsigned DstAlign, unsigned SrcAlign,
1832 bool IsMemset, bool ZeroMemset,
1834 MachineFunction &MF) const {
1835 const Function *F = MF.getFunction();
1836 if ((!IsMemset || ZeroMemset) &&
1837 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1839 (Subtarget->isUnalignedMemAccessFast() ||
1840 ((DstAlign == 0 || DstAlign >= 16) &&
1841 (SrcAlign == 0 || SrcAlign >= 16)))) {
1843 if (Subtarget->hasInt256())
1845 if (Subtarget->hasFp256())
1848 if (Subtarget->hasSSE2())
1850 if (Subtarget->hasSSE1())
1852 } else if (!MemcpyStrSrc && Size >= 8 &&
1853 !Subtarget->is64Bit() &&
1854 Subtarget->hasSSE2()) {
1855 // Do not use f64 to lower memcpy if source is string constant. It's
1856 // better to use i32 to avoid the loads.
1860 if (Subtarget->is64Bit() && Size >= 8)
1865 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1867 return X86ScalarSSEf32;
1868 else if (VT == MVT::f64)
1869 return X86ScalarSSEf64;
1874 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1879 *Fast = Subtarget->isUnalignedMemAccessFast();
1883 /// Return the entry encoding for a jump table in the
1884 /// current function. The returned value is a member of the
1885 /// MachineJumpTableInfo::JTEntryKind enum.
1886 unsigned X86TargetLowering::getJumpTableEncoding() const {
1887 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1889 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1890 Subtarget->isPICStyleGOT())
1891 return MachineJumpTableInfo::EK_Custom32;
1893 // Otherwise, use the normal jump table encoding heuristics.
1894 return TargetLowering::getJumpTableEncoding();
1898 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1899 const MachineBasicBlock *MBB,
1900 unsigned uid,MCContext &Ctx) const{
1901 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1902 Subtarget->isPICStyleGOT());
1903 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1905 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1906 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1909 /// Returns relocation base for the given PIC jumptable.
1910 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1911 SelectionDAG &DAG) const {
1912 if (!Subtarget->is64Bit())
1913 // This doesn't have SDLoc associated with it, but is not really the
1914 // same as a Register.
1915 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1919 /// This returns the relocation base for the given PIC jumptable,
1920 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1921 const MCExpr *X86TargetLowering::
1922 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1923 MCContext &Ctx) const {
1924 // X86-64 uses RIP relative addressing based on the jump table label.
1925 if (Subtarget->isPICStyleRIPRel())
1926 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1928 // Otherwise, the reference is relative to the PIC base.
1929 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1932 std::pair<const TargetRegisterClass *, uint8_t>
1933 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1935 const TargetRegisterClass *RRC = nullptr;
1937 switch (VT.SimpleTy) {
1939 return TargetLowering::findRepresentativeClass(TRI, VT);
1940 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1941 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1944 RRC = &X86::VR64RegClass;
1946 case MVT::f32: case MVT::f64:
1947 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1948 case MVT::v4f32: case MVT::v2f64:
1949 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1951 RRC = &X86::VR128RegClass;
1954 return std::make_pair(RRC, Cost);
1957 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1958 unsigned &Offset) const {
1959 if (!Subtarget->isTargetLinux())
1962 if (Subtarget->is64Bit()) {
1963 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1965 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1977 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1978 unsigned DestAS) const {
1979 assert(SrcAS != DestAS && "Expected different address spaces!");
1981 return SrcAS < 256 && DestAS < 256;
1984 //===----------------------------------------------------------------------===//
1985 // Return Value Calling Convention Implementation
1986 //===----------------------------------------------------------------------===//
1988 #include "X86GenCallingConv.inc"
1991 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1992 MachineFunction &MF, bool isVarArg,
1993 const SmallVectorImpl<ISD::OutputArg> &Outs,
1994 LLVMContext &Context) const {
1995 SmallVector<CCValAssign, 16> RVLocs;
1996 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1997 return CCInfo.CheckReturn(Outs, RetCC_X86);
2000 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2001 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2006 X86TargetLowering::LowerReturn(SDValue Chain,
2007 CallingConv::ID CallConv, bool isVarArg,
2008 const SmallVectorImpl<ISD::OutputArg> &Outs,
2009 const SmallVectorImpl<SDValue> &OutVals,
2010 SDLoc dl, SelectionDAG &DAG) const {
2011 MachineFunction &MF = DAG.getMachineFunction();
2012 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2014 SmallVector<CCValAssign, 16> RVLocs;
2015 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2016 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2019 SmallVector<SDValue, 6> RetOps;
2020 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2021 // Operand #1 = Bytes To Pop
2022 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2025 // Copy the result values into the output registers.
2026 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2027 CCValAssign &VA = RVLocs[i];
2028 assert(VA.isRegLoc() && "Can only return in registers!");
2029 SDValue ValToCopy = OutVals[i];
2030 EVT ValVT = ValToCopy.getValueType();
2032 // Promote values to the appropriate types.
2033 if (VA.getLocInfo() == CCValAssign::SExt)
2034 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2035 else if (VA.getLocInfo() == CCValAssign::ZExt)
2036 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2037 else if (VA.getLocInfo() == CCValAssign::AExt)
2038 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2039 else if (VA.getLocInfo() == CCValAssign::BCvt)
2040 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2042 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2043 "Unexpected FP-extend for return value.");
2045 // If this is x86-64, and we disabled SSE, we can't return FP values,
2046 // or SSE or MMX vectors.
2047 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2048 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2049 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2050 report_fatal_error("SSE register return with SSE disabled");
2052 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2053 // llvm-gcc has never done it right and no one has noticed, so this
2054 // should be OK for now.
2055 if (ValVT == MVT::f64 &&
2056 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2057 report_fatal_error("SSE2 register return with SSE2 disabled");
2059 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2060 // the RET instruction and handled by the FP Stackifier.
2061 if (VA.getLocReg() == X86::FP0 ||
2062 VA.getLocReg() == X86::FP1) {
2063 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2064 // change the value to the FP stack register class.
2065 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2066 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2067 RetOps.push_back(ValToCopy);
2068 // Don't emit a copytoreg.
2072 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2073 // which is returned in RAX / RDX.
2074 if (Subtarget->is64Bit()) {
2075 if (ValVT == MVT::x86mmx) {
2076 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2077 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2078 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2080 // If we don't have SSE2 available, convert to v4f32 so the generated
2081 // register is legal.
2082 if (!Subtarget->hasSSE2())
2083 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2088 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2089 Flag = Chain.getValue(1);
2090 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2093 // The x86-64 ABIs require that for returning structs by value we copy
2094 // the sret argument into %rax/%eax (depending on ABI) for the return.
2095 // Win32 requires us to put the sret argument to %eax as well.
2096 // We saved the argument into a virtual register in the entry block,
2097 // so now we copy the value out and into %rax/%eax.
2099 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2100 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2101 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2102 // either case FuncInfo->setSRetReturnReg() will have been called.
2103 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2104 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2105 "No need for an sret register");
2106 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2109 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2110 X86::RAX : X86::EAX;
2111 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2112 Flag = Chain.getValue(1);
2114 // RAX/EAX now acts like a return value.
2115 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2118 RetOps[0] = Chain; // Update chain.
2120 // Add the flag if we have it.
2122 RetOps.push_back(Flag);
2124 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2127 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2128 if (N->getNumValues() != 1)
2130 if (!N->hasNUsesOfValue(1, 0))
2133 SDValue TCChain = Chain;
2134 SDNode *Copy = *N->use_begin();
2135 if (Copy->getOpcode() == ISD::CopyToReg) {
2136 // If the copy has a glue operand, we conservatively assume it isn't safe to
2137 // perform a tail call.
2138 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2140 TCChain = Copy->getOperand(0);
2141 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2144 bool HasRet = false;
2145 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2147 if (UI->getOpcode() != X86ISD::RET_FLAG)
2149 // If we are returning more than one value, we can definitely
2150 // not make a tail call see PR19530
2151 if (UI->getNumOperands() > 4)
2153 if (UI->getNumOperands() == 4 &&
2154 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2167 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2168 ISD::NodeType ExtendKind) const {
2170 // TODO: Is this also valid on 32-bit?
2171 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2172 ReturnMVT = MVT::i8;
2174 ReturnMVT = MVT::i32;
2176 EVT MinVT = getRegisterType(Context, ReturnMVT);
2177 return VT.bitsLT(MinVT) ? MinVT : VT;
2180 /// Lower the result values of a call into the
2181 /// appropriate copies out of appropriate physical registers.
2184 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2185 CallingConv::ID CallConv, bool isVarArg,
2186 const SmallVectorImpl<ISD::InputArg> &Ins,
2187 SDLoc dl, SelectionDAG &DAG,
2188 SmallVectorImpl<SDValue> &InVals) const {
2190 // Assign locations to each value returned by this call.
2191 SmallVector<CCValAssign, 16> RVLocs;
2192 bool Is64Bit = Subtarget->is64Bit();
2193 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2195 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2197 // Copy all of the result registers out of their specified physreg.
2198 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2199 CCValAssign &VA = RVLocs[i];
2200 EVT CopyVT = VA.getValVT();
2202 // If this is x86-64, and we disabled SSE, we can't return FP values
2203 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2204 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2205 report_fatal_error("SSE register return with SSE disabled");
2208 // If we prefer to use the value in xmm registers, copy it out as f80 and
2209 // use a truncate to move it from fp stack reg to xmm reg.
2210 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2211 isScalarFPTypeInSSEReg(VA.getValVT()))
2214 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2215 CopyVT, InFlag).getValue(1);
2216 SDValue Val = Chain.getValue(0);
2218 if (CopyVT != VA.getValVT())
2219 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2220 // This truncation won't change the value.
2221 DAG.getIntPtrConstant(1));
2223 InFlag = Chain.getValue(2);
2224 InVals.push_back(Val);
2230 //===----------------------------------------------------------------------===//
2231 // C & StdCall & Fast Calling Convention implementation
2232 //===----------------------------------------------------------------------===//
2233 // StdCall calling convention seems to be standard for many Windows' API
2234 // routines and around. It differs from C calling convention just a little:
2235 // callee should clean up the stack, not caller. Symbols should be also
2236 // decorated in some fancy way :) It doesn't support any vector arguments.
2237 // For info on fast calling convention see Fast Calling Convention (tail call)
2238 // implementation LowerX86_32FastCCCallTo.
2240 /// CallIsStructReturn - Determines whether a call uses struct return
2242 enum StructReturnType {
2247 static StructReturnType
2248 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2250 return NotStructReturn;
2252 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2253 if (!Flags.isSRet())
2254 return NotStructReturn;
2255 if (Flags.isInReg())
2256 return RegStructReturn;
2257 return StackStructReturn;
2260 /// Determines whether a function uses struct return semantics.
2261 static StructReturnType
2262 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2264 return NotStructReturn;
2266 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2267 if (!Flags.isSRet())
2268 return NotStructReturn;
2269 if (Flags.isInReg())
2270 return RegStructReturn;
2271 return StackStructReturn;
2274 /// Make a copy of an aggregate at address specified by "Src" to address
2275 /// "Dst" with size and alignment information specified by the specific
2276 /// parameter attribute. The copy will be passed as a byval function parameter.
2278 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2279 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2281 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2283 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2284 /*isVolatile*/false, /*AlwaysInline=*/true,
2285 MachinePointerInfo(), MachinePointerInfo());
2288 /// Return true if the calling convention is one that
2289 /// supports tail call optimization.
2290 static bool IsTailCallConvention(CallingConv::ID CC) {
2291 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2292 CC == CallingConv::HiPE);
2295 /// \brief Return true if the calling convention is a C calling convention.
2296 static bool IsCCallConvention(CallingConv::ID CC) {
2297 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2298 CC == CallingConv::X86_64_SysV);
2301 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2302 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2306 CallingConv::ID CalleeCC = CS.getCallingConv();
2307 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2313 /// Return true if the function is being made into
2314 /// a tailcall target by changing its ABI.
2315 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2316 bool GuaranteedTailCallOpt) {
2317 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2321 X86TargetLowering::LowerMemArgument(SDValue Chain,
2322 CallingConv::ID CallConv,
2323 const SmallVectorImpl<ISD::InputArg> &Ins,
2324 SDLoc dl, SelectionDAG &DAG,
2325 const CCValAssign &VA,
2326 MachineFrameInfo *MFI,
2328 // Create the nodes corresponding to a load from this parameter slot.
2329 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2330 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2331 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2332 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2335 // If value is passed by pointer we have address passed instead of the value
2337 if (VA.getLocInfo() == CCValAssign::Indirect)
2338 ValVT = VA.getLocVT();
2340 ValVT = VA.getValVT();
2342 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343 // changed with more analysis.
2344 // In case of tail call optimization mark all arguments mutable. Since they
2345 // could be overwritten by lowering of arguments in case of a tail call.
2346 if (Flags.isByVal()) {
2347 unsigned Bytes = Flags.getByValSize();
2348 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350 return DAG.getFrameIndex(FI, getPointerTy());
2352 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353 VA.getLocMemOffset(), isImmutable);
2354 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355 return DAG.getLoad(ValVT, dl, Chain, FIN,
2356 MachinePointerInfo::getFixedStack(FI),
2357 false, false, false, 0);
2361 // FIXME: Get this from tablegen.
2362 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2363 const X86Subtarget *Subtarget) {
2364 assert(Subtarget->is64Bit());
2366 if (Subtarget->isCallingConvWin64(CallConv)) {
2367 static const MCPhysReg GPR64ArgRegsWin64[] = {
2368 X86::RCX, X86::RDX, X86::R8, X86::R9
2370 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2373 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2374 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2376 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2379 // FIXME: Get this from tablegen.
2380 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2381 CallingConv::ID CallConv,
2382 const X86Subtarget *Subtarget) {
2383 assert(Subtarget->is64Bit());
2384 if (Subtarget->isCallingConvWin64(CallConv)) {
2385 // The XMM registers which might contain var arg parameters are shadowed
2386 // in their paired GPR. So we only need to save the GPR to their home
2388 // TODO: __vectorcall will change this.
2392 const Function *Fn = MF.getFunction();
2393 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2394 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2395 "SSE register cannot be used when SSE is disabled!");
2396 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397 !Subtarget->hasSSE1())
2398 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2402 static const MCPhysReg XMMArgRegs64Bit[] = {
2403 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2404 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2406 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2410 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2411 CallingConv::ID CallConv,
2413 const SmallVectorImpl<ISD::InputArg> &Ins,
2416 SmallVectorImpl<SDValue> &InVals)
2418 MachineFunction &MF = DAG.getMachineFunction();
2419 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2421 const Function* Fn = MF.getFunction();
2422 if (Fn->hasExternalLinkage() &&
2423 Subtarget->isTargetCygMing() &&
2424 Fn->getName() == "main")
2425 FuncInfo->setForceFramePointer(true);
2427 MachineFrameInfo *MFI = MF.getFrameInfo();
2428 bool Is64Bit = Subtarget->is64Bit();
2429 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2431 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2432 "Var args not supported with calling convention fastcc, ghc or hipe");
2434 // Assign locations to all of the incoming arguments.
2435 SmallVector<CCValAssign, 16> ArgLocs;
2436 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2438 // Allocate shadow area for Win64
2440 CCInfo.AllocateStack(32, 8);
2442 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2444 unsigned LastVal = ~0U;
2446 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2447 CCValAssign &VA = ArgLocs[i];
2448 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2450 assert(VA.getValNo() != LastVal &&
2451 "Don't support value assigned to multiple locs yet");
2453 LastVal = VA.getValNo();
2455 if (VA.isRegLoc()) {
2456 EVT RegVT = VA.getLocVT();
2457 const TargetRegisterClass *RC;
2458 if (RegVT == MVT::i32)
2459 RC = &X86::GR32RegClass;
2460 else if (Is64Bit && RegVT == MVT::i64)
2461 RC = &X86::GR64RegClass;
2462 else if (RegVT == MVT::f32)
2463 RC = &X86::FR32RegClass;
2464 else if (RegVT == MVT::f64)
2465 RC = &X86::FR64RegClass;
2466 else if (RegVT.is512BitVector())
2467 RC = &X86::VR512RegClass;
2468 else if (RegVT.is256BitVector())
2469 RC = &X86::VR256RegClass;
2470 else if (RegVT.is128BitVector())
2471 RC = &X86::VR128RegClass;
2472 else if (RegVT == MVT::x86mmx)
2473 RC = &X86::VR64RegClass;
2474 else if (RegVT == MVT::i1)
2475 RC = &X86::VK1RegClass;
2476 else if (RegVT == MVT::v8i1)
2477 RC = &X86::VK8RegClass;
2478 else if (RegVT == MVT::v16i1)
2479 RC = &X86::VK16RegClass;
2480 else if (RegVT == MVT::v32i1)
2481 RC = &X86::VK32RegClass;
2482 else if (RegVT == MVT::v64i1)
2483 RC = &X86::VK64RegClass;
2485 llvm_unreachable("Unknown argument type!");
2487 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2488 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2490 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2491 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2493 if (VA.getLocInfo() == CCValAssign::SExt)
2494 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2495 DAG.getValueType(VA.getValVT()));
2496 else if (VA.getLocInfo() == CCValAssign::ZExt)
2497 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2498 DAG.getValueType(VA.getValVT()));
2499 else if (VA.getLocInfo() == CCValAssign::BCvt)
2500 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2502 if (VA.isExtInLoc()) {
2503 // Handle MMX values passed in XMM regs.
2504 if (RegVT.isVector())
2505 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2507 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2510 assert(VA.isMemLoc());
2511 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2514 // If value is passed via pointer - do a load.
2515 if (VA.getLocInfo() == CCValAssign::Indirect)
2516 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2517 MachinePointerInfo(), false, false, false, 0);
2519 InVals.push_back(ArgValue);
2522 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2523 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2524 // The x86-64 ABIs require that for returning structs by value we copy
2525 // the sret argument into %rax/%eax (depending on ABI) for the return.
2526 // Win32 requires us to put the sret argument to %eax as well.
2527 // Save the argument into a virtual register so that we can access it
2528 // from the return points.
2529 if (Ins[i].Flags.isSRet()) {
2530 unsigned Reg = FuncInfo->getSRetReturnReg();
2532 MVT PtrTy = getPointerTy();
2533 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2534 FuncInfo->setSRetReturnReg(Reg);
2536 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2537 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2543 unsigned StackSize = CCInfo.getNextStackOffset();
2544 // Align stack specially for tail calls.
2545 if (FuncIsMadeTailCallSafe(CallConv,
2546 MF.getTarget().Options.GuaranteedTailCallOpt))
2547 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2549 // If the function takes variable number of arguments, make a frame index for
2550 // the start of the first vararg value... for expansion of llvm.va_start. We
2551 // can skip this if there are no va_start calls.
2552 if (MFI->hasVAStart() &&
2553 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554 CallConv != CallingConv::X86_ThisCall))) {
2555 FuncInfo->setVarArgsFrameIndex(
2556 MFI->CreateFixedObject(1, StackSize, true));
2559 // Figure out if XMM registers are in use.
2560 assert(!(MF.getTarget().Options.UseSoftFloat &&
2561 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2562 "SSE register cannot be used when SSE is disabled!");
2564 // 64-bit calling conventions support varargs and register parameters, so we
2565 // have to do extra work to spill them in the prologue.
2566 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2567 // Find the first unallocated argument registers.
2568 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2569 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2570 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2571 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2572 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2573 "SSE register cannot be used when SSE is disabled!");
2575 // Gather all the live in physical registers.
2576 SmallVector<SDValue, 6> LiveGPRs;
2577 SmallVector<SDValue, 8> LiveXMMRegs;
2579 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2580 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2582 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2584 if (!ArgXMMs.empty()) {
2585 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2586 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2587 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2588 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2589 LiveXMMRegs.push_back(
2590 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2595 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2596 // Get to the caller-allocated home save location. Add 8 to account
2597 // for the return address.
2598 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2599 FuncInfo->setRegSaveFrameIndex(
2600 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2601 // Fixup to set vararg frame on shadow area (4 x i64).
2603 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2605 // For X86-64, if there are vararg parameters that are passed via
2606 // registers, then we must store them to their spots on the stack so
2607 // they may be loaded by deferencing the result of va_next.
2608 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2609 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2610 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2611 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2614 // Store the integer parameter registers.
2615 SmallVector<SDValue, 8> MemOps;
2616 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2618 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2619 for (SDValue Val : LiveGPRs) {
2620 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2621 DAG.getIntPtrConstant(Offset));
2623 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2624 MachinePointerInfo::getFixedStack(
2625 FuncInfo->getRegSaveFrameIndex(), Offset),
2627 MemOps.push_back(Store);
2631 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2632 // Now store the XMM (fp + vector) parameter registers.
2633 SmallVector<SDValue, 12> SaveXMMOps;
2634 SaveXMMOps.push_back(Chain);
2635 SaveXMMOps.push_back(ALVal);
2636 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2637 FuncInfo->getRegSaveFrameIndex()));
2638 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2639 FuncInfo->getVarArgsFPOffset()));
2640 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2642 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2643 MVT::Other, SaveXMMOps));
2646 if (!MemOps.empty())
2647 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2650 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2651 // Find the largest legal vector type.
2652 MVT VecVT = MVT::Other;
2653 // FIXME: Only some x86_32 calling conventions support AVX512.
2654 if (Subtarget->hasAVX512() &&
2655 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2656 CallConv == CallingConv::Intel_OCL_BI)))
2657 VecVT = MVT::v16f32;
2658 else if (Subtarget->hasAVX())
2660 else if (Subtarget->hasSSE2())
2663 // We forward some GPRs and some vector types.
2664 SmallVector<MVT, 2> RegParmTypes;
2665 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2666 RegParmTypes.push_back(IntVT);
2667 if (VecVT != MVT::Other)
2668 RegParmTypes.push_back(VecVT);
2670 // Compute the set of forwarded registers. The rest are scratch.
2671 SmallVectorImpl<ForwardedRegister> &Forwards =
2672 FuncInfo->getForwardedMustTailRegParms();
2673 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2675 // Conservatively forward AL on x86_64, since it might be used for varargs.
2676 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2677 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2678 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2681 // Copy all forwards from physical to virtual registers.
2682 for (ForwardedRegister &F : Forwards) {
2683 // FIXME: Can we use a less constrained schedule?
2684 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2685 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2686 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2690 // Some CCs need callee pop.
2691 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2692 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2693 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2695 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2696 // If this is an sret function, the return should pop the hidden pointer.
2697 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2698 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2699 argsAreStructReturn(Ins) == StackStructReturn)
2700 FuncInfo->setBytesToPopOnReturn(4);
2704 // RegSaveFrameIndex is X86-64 only.
2705 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2706 if (CallConv == CallingConv::X86_FastCall ||
2707 CallConv == CallingConv::X86_ThisCall)
2708 // fastcc functions can't have varargs.
2709 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2712 FuncInfo->setArgumentStackSize(StackSize);
2718 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2719 SDValue StackPtr, SDValue Arg,
2720 SDLoc dl, SelectionDAG &DAG,
2721 const CCValAssign &VA,
2722 ISD::ArgFlagsTy Flags) const {
2723 unsigned LocMemOffset = VA.getLocMemOffset();
2724 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2725 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2726 if (Flags.isByVal())
2727 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2729 return DAG.getStore(Chain, dl, Arg, PtrOff,
2730 MachinePointerInfo::getStack(LocMemOffset),
2734 /// Emit a load of return address if tail call
2735 /// optimization is performed and it is required.
2737 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2738 SDValue &OutRetAddr, SDValue Chain,
2739 bool IsTailCall, bool Is64Bit,
2740 int FPDiff, SDLoc dl) const {
2741 // Adjust the Return address stack slot.
2742 EVT VT = getPointerTy();
2743 OutRetAddr = getReturnAddressFrameIndex(DAG);
2745 // Load the "old" Return address.
2746 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2747 false, false, false, 0);
2748 return SDValue(OutRetAddr.getNode(), 1);
2751 /// Emit a store of the return address if tail call
2752 /// optimization is performed and it is required (FPDiff!=0).
2753 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2754 SDValue Chain, SDValue RetAddrFrIdx,
2755 EVT PtrVT, unsigned SlotSize,
2756 int FPDiff, SDLoc dl) {
2757 // Store the return address to the appropriate stack slot.
2758 if (!FPDiff) return Chain;
2759 // Calculate the new stack slot for the return address.
2760 int NewReturnAddrFI =
2761 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2763 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2764 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2765 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2771 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2772 SmallVectorImpl<SDValue> &InVals) const {
2773 SelectionDAG &DAG = CLI.DAG;
2775 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2776 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2777 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2778 SDValue Chain = CLI.Chain;
2779 SDValue Callee = CLI.Callee;
2780 CallingConv::ID CallConv = CLI.CallConv;
2781 bool &isTailCall = CLI.IsTailCall;
2782 bool isVarArg = CLI.IsVarArg;
2784 MachineFunction &MF = DAG.getMachineFunction();
2785 bool Is64Bit = Subtarget->is64Bit();
2786 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2787 StructReturnType SR = callIsStructReturn(Outs);
2788 bool IsSibcall = false;
2789 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2791 if (MF.getTarget().Options.DisableTailCalls)
2794 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2796 // Force this to be a tail call. The verifier rules are enough to ensure
2797 // that we can lower this successfully without moving the return address
2800 } else if (isTailCall) {
2801 // Check if it's really possible to do a tail call.
2802 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2803 isVarArg, SR != NotStructReturn,
2804 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2805 Outs, OutVals, Ins, DAG);
2807 // Sibcalls are automatically detected tailcalls which do not require
2809 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2816 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2817 "Var args not supported with calling convention fastcc, ghc or hipe");
2819 // Analyze operands of the call, assigning locations to each operand.
2820 SmallVector<CCValAssign, 16> ArgLocs;
2821 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2823 // Allocate shadow area for Win64
2825 CCInfo.AllocateStack(32, 8);
2827 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2829 // Get a count of how many bytes are to be pushed on the stack.
2830 unsigned NumBytes = CCInfo.getNextStackOffset();
2832 // This is a sibcall. The memory operands are available in caller's
2833 // own caller's stack.
2835 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2836 IsTailCallConvention(CallConv))
2837 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2840 if (isTailCall && !IsSibcall && !IsMustTail) {
2841 // Lower arguments at fp - stackoffset + fpdiff.
2842 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2844 FPDiff = NumBytesCallerPushed - NumBytes;
2846 // Set the delta of movement of the returnaddr stackslot.
2847 // But only set if delta is greater than previous delta.
2848 if (FPDiff < X86Info->getTCReturnAddrDelta())
2849 X86Info->setTCReturnAddrDelta(FPDiff);
2852 unsigned NumBytesToPush = NumBytes;
2853 unsigned NumBytesToPop = NumBytes;
2855 // If we have an inalloca argument, all stack space has already been allocated
2856 // for us and be right at the top of the stack. We don't support multiple
2857 // arguments passed in memory when using inalloca.
2858 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2860 if (!ArgLocs.back().isMemLoc())
2861 report_fatal_error("cannot use inalloca attribute on a register "
2863 if (ArgLocs.back().getLocMemOffset() != 0)
2864 report_fatal_error("any parameter with the inalloca attribute must be "
2865 "the only memory argument");
2869 Chain = DAG.getCALLSEQ_START(
2870 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2872 SDValue RetAddrFrIdx;
2873 // Load return address for tail calls.
2874 if (isTailCall && FPDiff)
2875 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2876 Is64Bit, FPDiff, dl);
2878 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2879 SmallVector<SDValue, 8> MemOpChains;
2882 // Walk the register/memloc assignments, inserting copies/loads. In the case
2883 // of tail call optimization arguments are handle later.
2884 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2885 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2886 // Skip inalloca arguments, they have already been written.
2887 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2888 if (Flags.isInAlloca())
2891 CCValAssign &VA = ArgLocs[i];
2892 EVT RegVT = VA.getLocVT();
2893 SDValue Arg = OutVals[i];
2894 bool isByVal = Flags.isByVal();
2896 // Promote the value if needed.
2897 switch (VA.getLocInfo()) {
2898 default: llvm_unreachable("Unknown loc info!");
2899 case CCValAssign::Full: break;
2900 case CCValAssign::SExt:
2901 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2903 case CCValAssign::ZExt:
2904 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2906 case CCValAssign::AExt:
2907 if (RegVT.is128BitVector()) {
2908 // Special case: passing MMX values in XMM registers.
2909 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2910 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2911 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2913 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2915 case CCValAssign::BCvt:
2916 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2918 case CCValAssign::Indirect: {
2919 // Store the argument.
2920 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2921 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2922 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2923 MachinePointerInfo::getFixedStack(FI),
2930 if (VA.isRegLoc()) {
2931 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2932 if (isVarArg && IsWin64) {
2933 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2934 // shadow reg if callee is a varargs function.
2935 unsigned ShadowReg = 0;
2936 switch (VA.getLocReg()) {
2937 case X86::XMM0: ShadowReg = X86::RCX; break;
2938 case X86::XMM1: ShadowReg = X86::RDX; break;
2939 case X86::XMM2: ShadowReg = X86::R8; break;
2940 case X86::XMM3: ShadowReg = X86::R9; break;
2943 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2945 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2946 assert(VA.isMemLoc());
2947 if (!StackPtr.getNode())
2948 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2950 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2951 dl, DAG, VA, Flags));
2955 if (!MemOpChains.empty())
2956 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2958 if (Subtarget->isPICStyleGOT()) {
2959 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2962 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2963 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2965 // If we are tail calling and generating PIC/GOT style code load the
2966 // address of the callee into ECX. The value in ecx is used as target of
2967 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2968 // for tail calls on PIC/GOT architectures. Normally we would just put the
2969 // address of GOT into ebx and then call target@PLT. But for tail calls
2970 // ebx would be restored (since ebx is callee saved) before jumping to the
2973 // Note: The actual moving to ECX is done further down.
2974 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2975 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2976 !G->getGlobal()->hasProtectedVisibility())
2977 Callee = LowerGlobalAddress(Callee, DAG);
2978 else if (isa<ExternalSymbolSDNode>(Callee))
2979 Callee = LowerExternalSymbol(Callee, DAG);
2983 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2984 // From AMD64 ABI document:
2985 // For calls that may call functions that use varargs or stdargs
2986 // (prototype-less calls or calls to functions containing ellipsis (...) in
2987 // the declaration) %al is used as hidden argument to specify the number
2988 // of SSE registers used. The contents of %al do not need to match exactly
2989 // the number of registers, but must be an ubound on the number of SSE
2990 // registers used and is in the range 0 - 8 inclusive.
2992 // Count the number of XMM registers allocated.
2993 static const MCPhysReg XMMArgRegs[] = {
2994 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2995 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2997 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2998 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2999 && "SSE registers cannot be used when SSE is disabled");
3001 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3002 DAG.getConstant(NumXMMRegs, MVT::i8)));
3005 if (isVarArg && IsMustTail) {
3006 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3007 for (const auto &F : Forwards) {
3008 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3009 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3013 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3014 // don't need this because the eligibility check rejects calls that require
3015 // shuffling arguments passed in memory.
3016 if (!IsSibcall && isTailCall) {
3017 // Force all the incoming stack arguments to be loaded from the stack
3018 // before any new outgoing arguments are stored to the stack, because the
3019 // outgoing stack slots may alias the incoming argument stack slots, and
3020 // the alias isn't otherwise explicit. This is slightly more conservative
3021 // than necessary, because it means that each store effectively depends
3022 // on every argument instead of just those arguments it would clobber.
3023 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3025 SmallVector<SDValue, 8> MemOpChains2;
3028 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3029 CCValAssign &VA = ArgLocs[i];
3032 assert(VA.isMemLoc());
3033 SDValue Arg = OutVals[i];
3034 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3035 // Skip inalloca arguments. They don't require any work.
3036 if (Flags.isInAlloca())
3038 // Create frame index.
3039 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3040 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3041 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3042 FIN = DAG.getFrameIndex(FI, getPointerTy());
3044 if (Flags.isByVal()) {
3045 // Copy relative to framepointer.
3046 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3047 if (!StackPtr.getNode())
3048 StackPtr = DAG.getCopyFromReg(Chain, dl,
3049 RegInfo->getStackRegister(),
3051 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3053 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3057 // Store relative to framepointer.
3058 MemOpChains2.push_back(
3059 DAG.getStore(ArgChain, dl, Arg, FIN,
3060 MachinePointerInfo::getFixedStack(FI),
3065 if (!MemOpChains2.empty())
3066 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3068 // Store the return address to the appropriate stack slot.
3069 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3070 getPointerTy(), RegInfo->getSlotSize(),
3074 // Build a sequence of copy-to-reg nodes chained together with token chain
3075 // and flag operands which copy the outgoing args into registers.
3077 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3078 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3079 RegsToPass[i].second, InFlag);
3080 InFlag = Chain.getValue(1);
3083 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3084 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3085 // In the 64-bit large code model, we have to make all calls
3086 // through a register, since the call instruction's 32-bit
3087 // pc-relative offset may not be large enough to hold the whole
3089 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3090 // If the callee is a GlobalAddress node (quite common, every direct call
3091 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3093 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3095 // We should use extra load for direct calls to dllimported functions in
3097 const GlobalValue *GV = G->getGlobal();
3098 if (!GV->hasDLLImportStorageClass()) {
3099 unsigned char OpFlags = 0;
3100 bool ExtraLoad = false;
3101 unsigned WrapperKind = ISD::DELETED_NODE;
3103 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3104 // external symbols most go through the PLT in PIC mode. If the symbol
3105 // has hidden or protected visibility, or if it is static or local, then
3106 // we don't need to use the PLT - we can directly call it.
3107 if (Subtarget->isTargetELF() &&
3108 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3109 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3110 OpFlags = X86II::MO_PLT;
3111 } else if (Subtarget->isPICStyleStubAny() &&
3112 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3113 (!Subtarget->getTargetTriple().isMacOSX() ||
3114 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115 // PC-relative references to external symbols should go through $stub,
3116 // unless we're building with the leopard linker or later, which
3117 // automatically synthesizes these stubs.
3118 OpFlags = X86II::MO_DARWIN_STUB;
3119 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3120 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3121 // If the function is marked as non-lazy, generate an indirect call
3122 // which loads from the GOT directly. This avoids runtime overhead
3123 // at the cost of eager binding (and one extra byte of encoding).
3124 OpFlags = X86II::MO_GOTPCREL;
3125 WrapperKind = X86ISD::WrapperRIP;
3129 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3130 G->getOffset(), OpFlags);
3132 // Add a wrapper if needed.
3133 if (WrapperKind != ISD::DELETED_NODE)
3134 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3135 // Add extra indirection if needed.
3137 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3138 MachinePointerInfo::getGOT(),
3139 false, false, false, 0);
3141 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3142 unsigned char OpFlags = 0;
3144 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3145 // external symbols should go through the PLT.
3146 if (Subtarget->isTargetELF() &&
3147 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3148 OpFlags = X86II::MO_PLT;
3149 } else if (Subtarget->isPICStyleStubAny() &&
3150 (!Subtarget->getTargetTriple().isMacOSX() ||
3151 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3152 // PC-relative references to external symbols should go through $stub,
3153 // unless we're building with the leopard linker or later, which
3154 // automatically synthesizes these stubs.
3155 OpFlags = X86II::MO_DARWIN_STUB;
3158 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3160 } else if (Subtarget->isTarget64BitILP32() &&
3161 Callee->getValueType(0) == MVT::i32) {
3162 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3163 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3166 // Returns a chain & a flag for retval copy to use.
3167 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3168 SmallVector<SDValue, 8> Ops;
3170 if (!IsSibcall && isTailCall) {
3171 Chain = DAG.getCALLSEQ_END(Chain,
3172 DAG.getIntPtrConstant(NumBytesToPop, true),
3173 DAG.getIntPtrConstant(0, true), InFlag, dl);
3174 InFlag = Chain.getValue(1);
3177 Ops.push_back(Chain);
3178 Ops.push_back(Callee);
3181 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3183 // Add argument registers to the end of the list so that they are known live
3185 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3186 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3187 RegsToPass[i].second.getValueType()));
3189 // Add a register mask operand representing the call-preserved registers.
3190 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3191 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3192 assert(Mask && "Missing call preserved mask for calling convention");
3193 Ops.push_back(DAG.getRegisterMask(Mask));
3195 if (InFlag.getNode())
3196 Ops.push_back(InFlag);
3200 //// If this is the first return lowered for this function, add the regs
3201 //// to the liveout set for the function.
3202 // This isn't right, although it's probably harmless on x86; liveouts
3203 // should be computed from returns not tail calls. Consider a void
3204 // function making a tail call to a function returning int.
3205 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3208 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3209 InFlag = Chain.getValue(1);
3211 // Create the CALLSEQ_END node.
3212 unsigned NumBytesForCalleeToPop;
3213 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3214 DAG.getTarget().Options.GuaranteedTailCallOpt))
3215 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3216 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3217 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3218 SR == StackStructReturn)
3219 // If this is a call to a struct-return function, the callee
3220 // pops the hidden struct pointer, so we have to push it back.
3221 // This is common for Darwin/X86, Linux & Mingw32 targets.
3222 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3223 NumBytesForCalleeToPop = 4;
3225 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3227 // Returns a flag for retval copy to use.
3229 Chain = DAG.getCALLSEQ_END(Chain,
3230 DAG.getIntPtrConstant(NumBytesToPop, true),
3231 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3234 InFlag = Chain.getValue(1);
3237 // Handle result values, copying them out of physregs into vregs that we
3239 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3240 Ins, dl, DAG, InVals);
3243 //===----------------------------------------------------------------------===//
3244 // Fast Calling Convention (tail call) implementation
3245 //===----------------------------------------------------------------------===//
3247 // Like std call, callee cleans arguments, convention except that ECX is
3248 // reserved for storing the tail called function address. Only 2 registers are
3249 // free for argument passing (inreg). Tail call optimization is performed
3251 // * tailcallopt is enabled
3252 // * caller/callee are fastcc
3253 // On X86_64 architecture with GOT-style position independent code only local
3254 // (within module) calls are supported at the moment.
3255 // To keep the stack aligned according to platform abi the function
3256 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3257 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3258 // If a tail called function callee has more arguments than the caller the
3259 // caller needs to make sure that there is room to move the RETADDR to. This is
3260 // achieved by reserving an area the size of the argument delta right after the
3261 // original RETADDR, but before the saved framepointer or the spilled registers
3262 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3274 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3275 /// for a 16 byte align requirement.
3277 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3278 SelectionDAG& DAG) const {
3279 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3280 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3281 unsigned StackAlignment = TFI.getStackAlignment();
3282 uint64_t AlignMask = StackAlignment - 1;
3283 int64_t Offset = StackSize;
3284 unsigned SlotSize = RegInfo->getSlotSize();
3285 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3286 // Number smaller than 12 so just add the difference.
3287 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3289 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3290 Offset = ((~AlignMask) & Offset) + StackAlignment +
3291 (StackAlignment-SlotSize);
3296 /// MatchingStackOffset - Return true if the given stack call argument is
3297 /// already available in the same position (relatively) of the caller's
3298 /// incoming argument stack.
3300 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3301 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3302 const X86InstrInfo *TII) {
3303 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3305 if (Arg.getOpcode() == ISD::CopyFromReg) {
3306 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3307 if (!TargetRegisterInfo::isVirtualRegister(VR))
3309 MachineInstr *Def = MRI->getVRegDef(VR);
3312 if (!Flags.isByVal()) {
3313 if (!TII->isLoadFromStackSlot(Def, FI))
3316 unsigned Opcode = Def->getOpcode();
3317 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3318 Opcode == X86::LEA64_32r) &&
3319 Def->getOperand(1).isFI()) {
3320 FI = Def->getOperand(1).getIndex();
3321 Bytes = Flags.getByValSize();
3325 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3326 if (Flags.isByVal())
3327 // ByVal argument is passed in as a pointer but it's now being
3328 // dereferenced. e.g.
3329 // define @foo(%struct.X* %A) {
3330 // tail call @bar(%struct.X* byval %A)
3333 SDValue Ptr = Ld->getBasePtr();
3334 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3337 FI = FINode->getIndex();
3338 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3339 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3340 FI = FINode->getIndex();
3341 Bytes = Flags.getByValSize();
3345 assert(FI != INT_MAX);
3346 if (!MFI->isFixedObjectIndex(FI))
3348 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3351 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3352 /// for tail call optimization. Targets which want to do tail call
3353 /// optimization should implement this function.
3355 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3356 CallingConv::ID CalleeCC,
3358 bool isCalleeStructRet,
3359 bool isCallerStructRet,
3361 const SmallVectorImpl<ISD::OutputArg> &Outs,
3362 const SmallVectorImpl<SDValue> &OutVals,
3363 const SmallVectorImpl<ISD::InputArg> &Ins,
3364 SelectionDAG &DAG) const {
3365 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3368 // If -tailcallopt is specified, make fastcc functions tail-callable.
3369 const MachineFunction &MF = DAG.getMachineFunction();
3370 const Function *CallerF = MF.getFunction();
3372 // If the function return type is x86_fp80 and the callee return type is not,
3373 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3374 // perform a tailcall optimization here.
3375 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3378 CallingConv::ID CallerCC = CallerF->getCallingConv();
3379 bool CCMatch = CallerCC == CalleeCC;
3380 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3381 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3383 // Win64 functions have extra shadow space for argument homing. Don't do the
3384 // sibcall if the caller and callee have mismatched expectations for this
3386 if (IsCalleeWin64 != IsCallerWin64)
3389 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3390 if (IsTailCallConvention(CalleeCC) && CCMatch)
3395 // Look for obvious safe cases to perform tail call optimization that do not
3396 // require ABI changes. This is what gcc calls sibcall.
3398 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3399 // emit a special epilogue.
3400 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3401 if (RegInfo->needsStackRealignment(MF))
3404 // Also avoid sibcall optimization if either caller or callee uses struct
3405 // return semantics.
3406 if (isCalleeStructRet || isCallerStructRet)
3409 // An stdcall/thiscall caller is expected to clean up its arguments; the
3410 // callee isn't going to do that.
3411 // FIXME: this is more restrictive than needed. We could produce a tailcall
3412 // when the stack adjustment matches. For example, with a thiscall that takes
3413 // only one argument.
3414 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3415 CallerCC == CallingConv::X86_ThisCall))
3418 // Do not sibcall optimize vararg calls unless all arguments are passed via
3420 if (isVarArg && !Outs.empty()) {
3422 // Optimizing for varargs on Win64 is unlikely to be safe without
3423 // additional testing.
3424 if (IsCalleeWin64 || IsCallerWin64)
3427 SmallVector<CCValAssign, 16> ArgLocs;
3428 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3431 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3432 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3433 if (!ArgLocs[i].isRegLoc())
3437 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3438 // stack. Therefore, if it's not used by the call it is not safe to optimize
3439 // this into a sibcall.
3440 bool Unused = false;
3441 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3448 SmallVector<CCValAssign, 16> RVLocs;
3449 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3451 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3452 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3453 CCValAssign &VA = RVLocs[i];
3454 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3459 // If the calling conventions do not match, then we'd better make sure the
3460 // results are returned in the same way as what the caller expects.
3462 SmallVector<CCValAssign, 16> RVLocs1;
3463 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3465 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3467 SmallVector<CCValAssign, 16> RVLocs2;
3468 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3470 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3472 if (RVLocs1.size() != RVLocs2.size())
3474 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3475 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3477 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3479 if (RVLocs1[i].isRegLoc()) {
3480 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3483 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3489 // If the callee takes no arguments then go on to check the results of the
3491 if (!Outs.empty()) {
3492 // Check if stack adjustment is needed. For now, do not do this if any
3493 // argument is passed on the stack.
3494 SmallVector<CCValAssign, 16> ArgLocs;
3495 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3498 // Allocate shadow area for Win64
3500 CCInfo.AllocateStack(32, 8);
3502 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3503 if (CCInfo.getNextStackOffset()) {
3504 MachineFunction &MF = DAG.getMachineFunction();
3505 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3508 // Check if the arguments are already laid out in the right way as
3509 // the caller's fixed stack objects.
3510 MachineFrameInfo *MFI = MF.getFrameInfo();
3511 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3512 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3513 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3514 CCValAssign &VA = ArgLocs[i];
3515 SDValue Arg = OutVals[i];
3516 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3517 if (VA.getLocInfo() == CCValAssign::Indirect)
3519 if (!VA.isRegLoc()) {
3520 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3527 // If the tailcall address may be in a register, then make sure it's
3528 // possible to register allocate for it. In 32-bit, the call address can
3529 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3530 // callee-saved registers are restored. These happen to be the same
3531 // registers used to pass 'inreg' arguments so watch out for those.
3532 if (!Subtarget->is64Bit() &&
3533 ((!isa<GlobalAddressSDNode>(Callee) &&
3534 !isa<ExternalSymbolSDNode>(Callee)) ||
3535 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3536 unsigned NumInRegs = 0;
3537 // In PIC we need an extra register to formulate the address computation
3539 unsigned MaxInRegs =
3540 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3542 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3543 CCValAssign &VA = ArgLocs[i];
3546 unsigned Reg = VA.getLocReg();
3549 case X86::EAX: case X86::EDX: case X86::ECX:
3550 if (++NumInRegs == MaxInRegs)
3562 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3563 const TargetLibraryInfo *libInfo) const {
3564 return X86::createFastISel(funcInfo, libInfo);
3567 //===----------------------------------------------------------------------===//
3568 // Other Lowering Hooks
3569 //===----------------------------------------------------------------------===//
3571 static bool MayFoldLoad(SDValue Op) {
3572 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3575 static bool MayFoldIntoStore(SDValue Op) {
3576 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3579 static bool isTargetShuffle(unsigned Opcode) {
3581 default: return false;
3582 case X86ISD::BLENDI:
3583 case X86ISD::PSHUFB:
3584 case X86ISD::PSHUFD:
3585 case X86ISD::PSHUFHW:
3586 case X86ISD::PSHUFLW:
3588 case X86ISD::PALIGNR:
3589 case X86ISD::MOVLHPS:
3590 case X86ISD::MOVLHPD:
3591 case X86ISD::MOVHLPS:
3592 case X86ISD::MOVLPS:
3593 case X86ISD::MOVLPD:
3594 case X86ISD::MOVSHDUP:
3595 case X86ISD::MOVSLDUP:
3596 case X86ISD::MOVDDUP:
3599 case X86ISD::UNPCKL:
3600 case X86ISD::UNPCKH:
3601 case X86ISD::VPERMILPI:
3602 case X86ISD::VPERM2X128:
3603 case X86ISD::VPERMI:
3608 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3609 SDValue V1, unsigned TargetMask,
3610 SelectionDAG &DAG) {
3612 default: llvm_unreachable("Unknown x86 shuffle node");
3613 case X86ISD::PSHUFD:
3614 case X86ISD::PSHUFHW:
3615 case X86ISD::PSHUFLW:
3616 case X86ISD::VPERMILPI:
3617 case X86ISD::VPERMI:
3618 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3622 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3623 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3625 default: llvm_unreachable("Unknown x86 shuffle node");
3626 case X86ISD::MOVLHPS:
3627 case X86ISD::MOVLHPD:
3628 case X86ISD::MOVHLPS:
3629 case X86ISD::MOVLPS:
3630 case X86ISD::MOVLPD:
3633 case X86ISD::UNPCKL:
3634 case X86ISD::UNPCKH:
3635 return DAG.getNode(Opc, dl, VT, V1, V2);
3639 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3640 MachineFunction &MF = DAG.getMachineFunction();
3641 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3642 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3643 int ReturnAddrIndex = FuncInfo->getRAIndex();
3645 if (ReturnAddrIndex == 0) {
3646 // Set up a frame object for the return address.
3647 unsigned SlotSize = RegInfo->getSlotSize();
3648 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3651 FuncInfo->setRAIndex(ReturnAddrIndex);
3654 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3657 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3658 bool hasSymbolicDisplacement) {
3659 // Offset should fit into 32 bit immediate field.
3660 if (!isInt<32>(Offset))
3663 // If we don't have a symbolic displacement - we don't have any extra
3665 if (!hasSymbolicDisplacement)
3668 // FIXME: Some tweaks might be needed for medium code model.
3669 if (M != CodeModel::Small && M != CodeModel::Kernel)
3672 // For small code model we assume that latest object is 16MB before end of 31
3673 // bits boundary. We may also accept pretty large negative constants knowing
3674 // that all objects are in the positive half of address space.
3675 if (M == CodeModel::Small && Offset < 16*1024*1024)
3678 // For kernel code model we know that all object resist in the negative half
3679 // of 32bits address space. We may not accept negative offsets, since they may
3680 // be just off and we may accept pretty large positive ones.
3681 if (M == CodeModel::Kernel && Offset >= 0)
3687 /// isCalleePop - Determines whether the callee is required to pop its
3688 /// own arguments. Callee pop is necessary to support tail calls.
3689 bool X86::isCalleePop(CallingConv::ID CallingConv,
3690 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3691 switch (CallingConv) {
3694 case CallingConv::X86_StdCall:
3695 case CallingConv::X86_FastCall:
3696 case CallingConv::X86_ThisCall:
3698 case CallingConv::Fast:
3699 case CallingConv::GHC:
3700 case CallingConv::HiPE:
3707 /// \brief Return true if the condition is an unsigned comparison operation.
3708 static bool isX86CCUnsigned(unsigned X86CC) {
3710 default: llvm_unreachable("Invalid integer condition!");
3711 case X86::COND_E: return true;
3712 case X86::COND_G: return false;
3713 case X86::COND_GE: return false;
3714 case X86::COND_L: return false;
3715 case X86::COND_LE: return false;
3716 case X86::COND_NE: return true;
3717 case X86::COND_B: return true;
3718 case X86::COND_A: return true;
3719 case X86::COND_BE: return true;
3720 case X86::COND_AE: return true;
3722 llvm_unreachable("covered switch fell through?!");
3725 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3726 /// specific condition code, returning the condition code and the LHS/RHS of the
3727 /// comparison to make.
3728 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3729 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3731 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3732 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3733 // X > -1 -> X == 0, jump !sign.
3734 RHS = DAG.getConstant(0, RHS.getValueType());
3735 return X86::COND_NS;
3737 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3738 // X < 0 -> X == 0, jump on sign.
3741 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3743 RHS = DAG.getConstant(0, RHS.getValueType());
3744 return X86::COND_LE;
3748 switch (SetCCOpcode) {
3749 default: llvm_unreachable("Invalid integer condition!");
3750 case ISD::SETEQ: return X86::COND_E;
3751 case ISD::SETGT: return X86::COND_G;
3752 case ISD::SETGE: return X86::COND_GE;
3753 case ISD::SETLT: return X86::COND_L;
3754 case ISD::SETLE: return X86::COND_LE;
3755 case ISD::SETNE: return X86::COND_NE;
3756 case ISD::SETULT: return X86::COND_B;
3757 case ISD::SETUGT: return X86::COND_A;
3758 case ISD::SETULE: return X86::COND_BE;
3759 case ISD::SETUGE: return X86::COND_AE;
3763 // First determine if it is required or is profitable to flip the operands.
3765 // If LHS is a foldable load, but RHS is not, flip the condition.
3766 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3767 !ISD::isNON_EXTLoad(RHS.getNode())) {
3768 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3769 std::swap(LHS, RHS);
3772 switch (SetCCOpcode) {
3778 std::swap(LHS, RHS);
3782 // On a floating point condition, the flags are set as follows:
3784 // 0 | 0 | 0 | X > Y
3785 // 0 | 0 | 1 | X < Y
3786 // 1 | 0 | 0 | X == Y
3787 // 1 | 1 | 1 | unordered
3788 switch (SetCCOpcode) {
3789 default: llvm_unreachable("Condcode should be pre-legalized away");
3791 case ISD::SETEQ: return X86::COND_E;
3792 case ISD::SETOLT: // flipped
3794 case ISD::SETGT: return X86::COND_A;
3795 case ISD::SETOLE: // flipped
3797 case ISD::SETGE: return X86::COND_AE;
3798 case ISD::SETUGT: // flipped
3800 case ISD::SETLT: return X86::COND_B;
3801 case ISD::SETUGE: // flipped
3803 case ISD::SETLE: return X86::COND_BE;
3805 case ISD::SETNE: return X86::COND_NE;
3806 case ISD::SETUO: return X86::COND_P;
3807 case ISD::SETO: return X86::COND_NP;
3809 case ISD::SETUNE: return X86::COND_INVALID;
3813 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3814 /// code. Current x86 isa includes the following FP cmov instructions:
3815 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3816 static bool hasFPCMov(unsigned X86CC) {
3832 /// isFPImmLegal - Returns true if the target can instruction select the
3833 /// specified FP immediate natively. If false, the legalizer will
3834 /// materialize the FP immediate as a load from a constant pool.
3835 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3836 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3837 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3843 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3844 ISD::LoadExtType ExtTy,
3846 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3847 // relocation target a movq or addq instruction: don't let the load shrink.
3848 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3849 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3850 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3851 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3855 /// \brief Returns true if it is beneficial to convert a load of a constant
3856 /// to just the constant itself.
3857 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3859 assert(Ty->isIntegerTy());
3861 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3862 if (BitSize == 0 || BitSize > 64)
3867 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3868 unsigned Index) const {
3869 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3872 return (Index == 0 || Index == ResVT.getVectorNumElements());
3875 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3876 // Speculate cttz only if we can directly use TZCNT.
3877 return Subtarget->hasBMI();
3880 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3881 // Speculate ctlz only if we can directly use LZCNT.
3882 return Subtarget->hasLZCNT();
3885 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3886 /// the specified range (L, H].
3887 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3888 return (Val < 0) || (Val >= Low && Val < Hi);
3891 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3892 /// specified value.
3893 static bool isUndefOrEqual(int Val, int CmpVal) {
3894 return (Val < 0 || Val == CmpVal);
3897 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3898 /// from position Pos and ending in Pos+Size, falls within the specified
3899 /// sequential range (Low, Low+Size]. or is undef.
3900 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3901 unsigned Pos, unsigned Size, int Low) {
3902 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3903 if (!isUndefOrEqual(Mask[i], Low))
3908 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3909 /// the two vector operands have swapped position.
3910 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3911 unsigned NumElems) {
3912 for (unsigned i = 0; i != NumElems; ++i) {
3916 else if (idx < (int)NumElems)
3917 Mask[i] = idx + NumElems;
3919 Mask[i] = idx - NumElems;
3923 /// isVEXTRACTIndex - Return true if the specified
3924 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3925 /// suitable for instruction that extract 128 or 256 bit vectors
3926 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3927 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3928 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3931 // The index should be aligned on a vecWidth-bit boundary.
3933 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3935 MVT VT = N->getSimpleValueType(0);
3936 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3937 bool Result = (Index * ElSize) % vecWidth == 0;
3942 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3943 /// operand specifies a subvector insert that is suitable for input to
3944 /// insertion of 128 or 256-bit subvectors
3945 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3946 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3947 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3949 // The index should be aligned on a vecWidth-bit boundary.
3951 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3953 MVT VT = N->getSimpleValueType(0);
3954 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3955 bool Result = (Index * ElSize) % vecWidth == 0;
3960 bool X86::isVINSERT128Index(SDNode *N) {
3961 return isVINSERTIndex(N, 128);
3964 bool X86::isVINSERT256Index(SDNode *N) {
3965 return isVINSERTIndex(N, 256);
3968 bool X86::isVEXTRACT128Index(SDNode *N) {
3969 return isVEXTRACTIndex(N, 128);
3972 bool X86::isVEXTRACT256Index(SDNode *N) {
3973 return isVEXTRACTIndex(N, 256);
3976 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3977 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3978 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3979 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3982 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3984 MVT VecVT = N->getOperand(0).getSimpleValueType();
3985 MVT ElVT = VecVT.getVectorElementType();
3987 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3988 return Index / NumElemsPerChunk;
3991 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3992 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3993 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3994 llvm_unreachable("Illegal insert subvector for VINSERT");
3997 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3999 MVT VecVT = N->getSimpleValueType(0);
4000 MVT ElVT = VecVT.getVectorElementType();
4002 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4003 return Index / NumElemsPerChunk;
4006 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4007 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 /// and VINSERTI128 instructions.
4009 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4010 return getExtractVEXTRACTImmediate(N, 128);
4013 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4014 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4015 /// and VINSERTI64x4 instructions.
4016 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4017 return getExtractVEXTRACTImmediate(N, 256);
4020 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4021 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4022 /// and VINSERTI128 instructions.
4023 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4024 return getInsertVINSERTImmediate(N, 128);
4027 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4028 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4029 /// and VINSERTI64x4 instructions.
4030 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4031 return getInsertVINSERTImmediate(N, 256);
4034 /// isZero - Returns true if Elt is a constant integer zero
4035 static bool isZero(SDValue V) {
4036 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4037 return C && C->isNullValue();
4040 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4042 bool X86::isZeroNode(SDValue Elt) {
4045 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4046 return CFP->getValueAPF().isPosZero();
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4052 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4053 SelectionDAG &DAG, SDLoc dl) {
4054 assert(VT.isVector() && "Expected a vector type");
4056 // Always build SSE zero vectors as <4 x i32> bitcasted
4057 // to their dest type. This ensures they get CSE'd.
4059 if (VT.is128BitVector()) { // SSE
4060 if (Subtarget->hasSSE2()) { // SSE2
4061 SDValue Cst = DAG.getConstant(0, MVT::i32);
4062 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4064 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4065 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4067 } else if (VT.is256BitVector()) { // AVX
4068 if (Subtarget->hasInt256()) { // AVX2
4069 SDValue Cst = DAG.getConstant(0, MVT::i32);
4070 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4071 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4073 // 256-bit logic and arithmetic instructions in AVX are all
4074 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4075 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4076 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4077 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4079 } else if (VT.is512BitVector()) { // AVX-512
4080 SDValue Cst = DAG.getConstant(0, MVT::i32);
4081 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4082 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4083 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4084 } else if (VT.getScalarType() == MVT::i1) {
4085 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4086 SDValue Cst = DAG.getConstant(0, MVT::i1);
4087 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4088 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4090 llvm_unreachable("Unexpected vector type");
4092 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4095 /// getOnesVector - Returns a vector of specified type with all bits set.
4096 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4097 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4098 /// Then bitcast to their original type, ensuring they get CSE'd.
4099 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4101 assert(VT.isVector() && "Expected a vector type");
4103 SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4105 if (VT.is256BitVector()) {
4106 if (HasInt256) { // AVX2
4107 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4108 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4110 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4111 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4113 } else if (VT.is128BitVector()) {
4114 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4116 llvm_unreachable("Unexpected vector type");
4118 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4121 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4122 /// operation of specified width.
4123 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4125 unsigned NumElems = VT.getVectorNumElements();
4126 SmallVector<int, 8> Mask;
4127 Mask.push_back(NumElems);
4128 for (unsigned i = 1; i != NumElems; ++i)
4130 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4133 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4134 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4136 unsigned NumElems = VT.getVectorNumElements();
4137 SmallVector<int, 8> Mask;
4138 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4140 Mask.push_back(i + NumElems);
4142 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4145 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4146 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4148 unsigned NumElems = VT.getVectorNumElements();
4149 SmallVector<int, 8> Mask;
4150 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4151 Mask.push_back(i + Half);
4152 Mask.push_back(i + NumElems + Half);
4154 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4157 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4158 /// vector of zero or undef vector. This produces a shuffle where the low
4159 /// element of V2 is swizzled into the zero/undef vector, landing at element
4160 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4161 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4163 const X86Subtarget *Subtarget,
4164 SelectionDAG &DAG) {
4165 MVT VT = V2.getSimpleValueType();
4167 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4168 unsigned NumElems = VT.getVectorNumElements();
4169 SmallVector<int, 16> MaskVec;
4170 for (unsigned i = 0; i != NumElems; ++i)
4171 // If this is the insertion idx, put the low elt of V2 here.
4172 MaskVec.push_back(i == Idx ? NumElems : i);
4173 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4176 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4177 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4178 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4179 /// shuffles which use a single input multiple times, and in those cases it will
4180 /// adjust the mask to only have indices within that single input.
4181 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4182 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4183 unsigned NumElems = VT.getVectorNumElements();
4187 bool IsFakeUnary = false;
4188 switch(N->getOpcode()) {
4189 case X86ISD::BLENDI:
4190 ImmN = N->getOperand(N->getNumOperands()-1);
4191 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4194 ImmN = N->getOperand(N->getNumOperands()-1);
4195 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4198 case X86ISD::UNPCKH:
4199 DecodeUNPCKHMask(VT, Mask);
4200 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4202 case X86ISD::UNPCKL:
4203 DecodeUNPCKLMask(VT, Mask);
4204 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4206 case X86ISD::MOVHLPS:
4207 DecodeMOVHLPSMask(NumElems, Mask);
4208 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4210 case X86ISD::MOVLHPS:
4211 DecodeMOVLHPSMask(NumElems, Mask);
4212 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4214 case X86ISD::PALIGNR:
4215 ImmN = N->getOperand(N->getNumOperands()-1);
4216 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4218 case X86ISD::PSHUFD:
4219 case X86ISD::VPERMILPI:
4220 ImmN = N->getOperand(N->getNumOperands()-1);
4221 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4224 case X86ISD::PSHUFHW:
4225 ImmN = N->getOperand(N->getNumOperands()-1);
4226 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4229 case X86ISD::PSHUFLW:
4230 ImmN = N->getOperand(N->getNumOperands()-1);
4231 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4234 case X86ISD::PSHUFB: {
4236 SDValue MaskNode = N->getOperand(1);
4237 while (MaskNode->getOpcode() == ISD::BITCAST)
4238 MaskNode = MaskNode->getOperand(0);
4240 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4241 // If we have a build-vector, then things are easy.
4242 EVT VT = MaskNode.getValueType();
4243 assert(VT.isVector() &&
4244 "Can't produce a non-vector with a build_vector!");
4245 if (!VT.isInteger())
4248 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4250 SmallVector<uint64_t, 32> RawMask;
4251 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4252 SDValue Op = MaskNode->getOperand(i);
4253 if (Op->getOpcode() == ISD::UNDEF) {
4254 RawMask.push_back((uint64_t)SM_SentinelUndef);
4257 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4260 APInt MaskElement = CN->getAPIntValue();
4262 // We now have to decode the element which could be any integer size and
4263 // extract each byte of it.
4264 for (int j = 0; j < NumBytesPerElement; ++j) {
4265 // Note that this is x86 and so always little endian: the low byte is
4266 // the first byte of the mask.
4267 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4268 MaskElement = MaskElement.lshr(8);
4271 DecodePSHUFBMask(RawMask, Mask);
4275 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4279 SDValue Ptr = MaskLoad->getBasePtr();
4280 if (Ptr->getOpcode() == X86ISD::Wrapper)
4281 Ptr = Ptr->getOperand(0);
4283 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4284 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4287 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4288 DecodePSHUFBMask(C, Mask);
4296 case X86ISD::VPERMI:
4297 ImmN = N->getOperand(N->getNumOperands()-1);
4298 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4303 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4305 case X86ISD::VPERM2X128:
4306 ImmN = N->getOperand(N->getNumOperands()-1);
4307 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308 if (Mask.empty()) return false;
4310 case X86ISD::MOVSLDUP:
4311 DecodeMOVSLDUPMask(VT, Mask);
4314 case X86ISD::MOVSHDUP:
4315 DecodeMOVSHDUPMask(VT, Mask);
4318 case X86ISD::MOVDDUP:
4319 DecodeMOVDDUPMask(VT, Mask);
4322 case X86ISD::MOVLHPD:
4323 case X86ISD::MOVLPD:
4324 case X86ISD::MOVLPS:
4325 // Not yet implemented
4327 default: llvm_unreachable("unknown target shuffle node");
4330 // If we have a fake unary shuffle, the shuffle mask is spread across two
4331 // inputs that are actually the same node. Re-map the mask to always point
4332 // into the first input.
4335 if (M >= (int)Mask.size())
4341 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4342 /// element of the result of the vector shuffle.
4343 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4346 return SDValue(); // Limit search depth.
4348 SDValue V = SDValue(N, 0);
4349 EVT VT = V.getValueType();
4350 unsigned Opcode = V.getOpcode();
4352 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4353 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4354 int Elt = SV->getMaskElt(Index);
4357 return DAG.getUNDEF(VT.getVectorElementType());
4359 unsigned NumElems = VT.getVectorNumElements();
4360 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4361 : SV->getOperand(1);
4362 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4365 // Recurse into target specific vector shuffles to find scalars.
4366 if (isTargetShuffle(Opcode)) {
4367 MVT ShufVT = V.getSimpleValueType();
4368 unsigned NumElems = ShufVT.getVectorNumElements();
4369 SmallVector<int, 16> ShuffleMask;
4372 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4375 int Elt = ShuffleMask[Index];
4377 return DAG.getUNDEF(ShufVT.getVectorElementType());
4379 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4381 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4385 // Actual nodes that may contain scalar elements
4386 if (Opcode == ISD::BITCAST) {
4387 V = V.getOperand(0);
4388 EVT SrcVT = V.getValueType();
4389 unsigned NumElems = VT.getVectorNumElements();
4391 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4395 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4396 return (Index == 0) ? V.getOperand(0)
4397 : DAG.getUNDEF(VT.getVectorElementType());
4399 if (V.getOpcode() == ISD::BUILD_VECTOR)
4400 return V.getOperand(Index);
4405 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4407 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4408 unsigned NumNonZero, unsigned NumZero,
4410 const X86Subtarget* Subtarget,
4411 const TargetLowering &TLI) {
4418 for (unsigned i = 0; i < 16; ++i) {
4419 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4420 if (ThisIsNonZero && First) {
4422 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4424 V = DAG.getUNDEF(MVT::v8i16);
4429 SDValue ThisElt, LastElt;
4430 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4431 if (LastIsNonZero) {
4432 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4433 MVT::i16, Op.getOperand(i-1));
4435 if (ThisIsNonZero) {
4436 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4437 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4438 ThisElt, DAG.getConstant(8, MVT::i8));
4440 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4444 if (ThisElt.getNode())
4445 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4446 DAG.getIntPtrConstant(i/2));
4450 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4453 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4455 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4456 unsigned NumNonZero, unsigned NumZero,
4458 const X86Subtarget* Subtarget,
4459 const TargetLowering &TLI) {
4466 for (unsigned i = 0; i < 8; ++i) {
4467 bool isNonZero = (NonZeros & (1 << i)) != 0;
4471 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4473 V = DAG.getUNDEF(MVT::v8i16);
4476 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4477 MVT::v8i16, V, Op.getOperand(i),
4478 DAG.getIntPtrConstant(i));
4485 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4486 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4487 const X86Subtarget *Subtarget,
4488 const TargetLowering &TLI) {
4489 // Find all zeroable elements.
4490 std::bitset<4> Zeroable;
4491 for (int i=0; i < 4; ++i) {
4492 SDValue Elt = Op->getOperand(i);
4493 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4495 assert(Zeroable.size() - Zeroable.count() > 1 &&
4496 "We expect at least two non-zero elements!");
4498 // We only know how to deal with build_vector nodes where elements are either
4499 // zeroable or extract_vector_elt with constant index.
4500 SDValue FirstNonZero;
4501 unsigned FirstNonZeroIdx;
4502 for (unsigned i=0; i < 4; ++i) {
4505 SDValue Elt = Op->getOperand(i);
4506 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4507 !isa<ConstantSDNode>(Elt.getOperand(1)))
4509 // Make sure that this node is extracting from a 128-bit vector.
4510 MVT VT = Elt.getOperand(0).getSimpleValueType();
4511 if (!VT.is128BitVector())
4513 if (!FirstNonZero.getNode()) {
4515 FirstNonZeroIdx = i;
4519 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4520 SDValue V1 = FirstNonZero.getOperand(0);
4521 MVT VT = V1.getSimpleValueType();
4523 // See if this build_vector can be lowered as a blend with zero.
4525 unsigned EltMaskIdx, EltIdx;
4527 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4528 if (Zeroable[EltIdx]) {
4529 // The zero vector will be on the right hand side.
4530 Mask[EltIdx] = EltIdx+4;
4534 Elt = Op->getOperand(EltIdx);
4535 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4536 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4537 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4539 Mask[EltIdx] = EltIdx;
4543 // Let the shuffle legalizer deal with blend operations.
4544 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4545 if (V1.getSimpleValueType() != VT)
4546 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4547 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4550 // See if we can lower this build_vector to a INSERTPS.
4551 if (!Subtarget->hasSSE41())
4554 SDValue V2 = Elt.getOperand(0);
4555 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4558 bool CanFold = true;
4559 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4563 SDValue Current = Op->getOperand(i);
4564 SDValue SrcVector = Current->getOperand(0);
4567 CanFold = SrcVector == V1 &&
4568 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4574 assert(V1.getNode() && "Expected at least two non-zero elements!");
4575 if (V1.getSimpleValueType() != MVT::v4f32)
4576 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4577 if (V2.getSimpleValueType() != MVT::v4f32)
4578 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4580 // Ok, we can emit an INSERTPS instruction.
4581 unsigned ZMask = Zeroable.to_ulong();
4583 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4584 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4585 SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4586 DAG.getIntPtrConstant(InsertPSMask));
4587 return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4590 /// Return a vector logical shift node.
4591 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4592 unsigned NumBits, SelectionDAG &DAG,
4593 const TargetLowering &TLI, SDLoc dl) {
4594 assert(VT.is128BitVector() && "Unknown type for VShift");
4595 MVT ShVT = MVT::v2i64;
4596 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4597 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4598 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4599 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4600 SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4601 return DAG.getNode(ISD::BITCAST, dl, VT,
4602 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4606 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4608 // Check if the scalar load can be widened into a vector load. And if
4609 // the address is "base + cst" see if the cst can be "absorbed" into
4610 // the shuffle mask.
4611 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4612 SDValue Ptr = LD->getBasePtr();
4613 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4615 EVT PVT = LD->getValueType(0);
4616 if (PVT != MVT::i32 && PVT != MVT::f32)
4621 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4622 FI = FINode->getIndex();
4624 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4625 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4626 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4627 Offset = Ptr.getConstantOperandVal(1);
4628 Ptr = Ptr.getOperand(0);
4633 // FIXME: 256-bit vector instructions don't require a strict alignment,
4634 // improve this code to support it better.
4635 unsigned RequiredAlign = VT.getSizeInBits()/8;
4636 SDValue Chain = LD->getChain();
4637 // Make sure the stack object alignment is at least 16 or 32.
4638 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4639 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4640 if (MFI->isFixedObjectIndex(FI)) {
4641 // Can't change the alignment. FIXME: It's possible to compute
4642 // the exact stack offset and reference FI + adjust offset instead.
4643 // If someone *really* cares about this. That's the way to implement it.
4646 MFI->setObjectAlignment(FI, RequiredAlign);
4650 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4651 // Ptr + (Offset & ~15).
4654 if ((Offset % RequiredAlign) & 3)
4656 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4658 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4659 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4661 int EltNo = (Offset - StartOffset) >> 2;
4662 unsigned NumElems = VT.getVectorNumElements();
4664 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4665 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4666 LD->getPointerInfo().getWithOffset(StartOffset),
4667 false, false, false, 0);
4669 SmallVector<int, 8> Mask(NumElems, EltNo);
4671 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4677 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4678 /// elements can be replaced by a single large load which has the same value as
4679 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4681 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4683 /// FIXME: we'd also like to handle the case where the last elements are zero
4684 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4685 /// There's even a handy isZeroNode for that purpose.
4686 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4687 SDLoc &DL, SelectionDAG &DAG,
4688 bool isAfterLegalize) {
4689 unsigned NumElems = Elts.size();
4691 LoadSDNode *LDBase = nullptr;
4692 unsigned LastLoadedElt = -1U;
4694 // For each element in the initializer, see if we've found a load or an undef.
4695 // If we don't find an initial load element, or later load elements are
4696 // non-consecutive, bail out.
4697 for (unsigned i = 0; i < NumElems; ++i) {
4698 SDValue Elt = Elts[i];
4699 // Look through a bitcast.
4700 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4701 Elt = Elt.getOperand(0);
4702 if (!Elt.getNode() ||
4703 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4706 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4708 LDBase = cast<LoadSDNode>(Elt.getNode());
4712 if (Elt.getOpcode() == ISD::UNDEF)
4715 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4716 EVT LdVT = Elt.getValueType();
4717 // Each loaded element must be the correct fractional portion of the
4718 // requested vector load.
4719 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4721 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4726 // If we have found an entire vector of loads and undefs, then return a large
4727 // load of the entire vector width starting at the base pointer. If we found
4728 // consecutive loads for the low half, generate a vzext_load node.
4729 if (LastLoadedElt == NumElems - 1) {
4730 assert(LDBase && "Did not find base load for merging consecutive loads");
4731 EVT EltVT = LDBase->getValueType(0);
4732 // Ensure that the input vector size for the merged loads matches the
4733 // cumulative size of the input elements.
4734 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4737 if (isAfterLegalize &&
4738 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4741 SDValue NewLd = SDValue();
4743 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4744 LDBase->getPointerInfo(), LDBase->isVolatile(),
4745 LDBase->isNonTemporal(), LDBase->isInvariant(),
4746 LDBase->getAlignment());
4748 if (LDBase->hasAnyUseOfValue(1)) {
4749 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4751 SDValue(NewLd.getNode(), 1));
4752 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4753 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4754 SDValue(NewLd.getNode(), 1));
4760 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4761 //of a v4i32 / v4f32. It's probably worth generalizing.
4762 EVT EltVT = VT.getVectorElementType();
4763 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4764 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4765 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4766 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4768 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4769 LDBase->getPointerInfo(),
4770 LDBase->getAlignment(),
4771 false/*isVolatile*/, true/*ReadMem*/,
4774 // Make sure the newly-created LOAD is in the same position as LDBase in
4775 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4776 // update uses of LDBase's output chain to use the TokenFactor.
4777 if (LDBase->hasAnyUseOfValue(1)) {
4778 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4779 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4780 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4781 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4782 SDValue(ResNode.getNode(), 1));
4785 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4790 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4791 /// to generate a splat value for the following cases:
4792 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4793 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4794 /// a scalar load, or a constant.
4795 /// The VBROADCAST node is returned when a pattern is found,
4796 /// or SDValue() otherwise.
4797 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4798 SelectionDAG &DAG) {
4799 // VBROADCAST requires AVX.
4800 // TODO: Splats could be generated for non-AVX CPUs using SSE
4801 // instructions, but there's less potential gain for only 128-bit vectors.
4802 if (!Subtarget->hasAVX())
4805 MVT VT = Op.getSimpleValueType();
4808 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4809 "Unsupported vector type for broadcast.");
4814 switch (Op.getOpcode()) {
4816 // Unknown pattern found.
4819 case ISD::BUILD_VECTOR: {
4820 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4821 BitVector UndefElements;
4822 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4824 // We need a splat of a single value to use broadcast, and it doesn't
4825 // make any sense if the value is only in one element of the vector.
4826 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4830 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4831 Ld.getOpcode() == ISD::ConstantFP);
4833 // Make sure that all of the users of a non-constant load are from the
4834 // BUILD_VECTOR node.
4835 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4840 case ISD::VECTOR_SHUFFLE: {
4841 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4843 // Shuffles must have a splat mask where the first element is
4845 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4848 SDValue Sc = Op.getOperand(0);
4849 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4850 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4852 if (!Subtarget->hasInt256())
4855 // Use the register form of the broadcast instruction available on AVX2.
4856 if (VT.getSizeInBits() >= 256)
4857 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4858 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4861 Ld = Sc.getOperand(0);
4862 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4863 Ld.getOpcode() == ISD::ConstantFP);
4865 // The scalar_to_vector node and the suspected
4866 // load node must have exactly one user.
4867 // Constants may have multiple users.
4869 // AVX-512 has register version of the broadcast
4870 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4871 Ld.getValueType().getSizeInBits() >= 32;
4872 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4879 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4880 bool IsGE256 = (VT.getSizeInBits() >= 256);
4882 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4883 // instruction to save 8 or more bytes of constant pool data.
4884 // TODO: If multiple splats are generated to load the same constant,
4885 // it may be detrimental to overall size. There needs to be a way to detect
4886 // that condition to know if this is truly a size win.
4887 const Function *F = DAG.getMachineFunction().getFunction();
4888 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4890 // Handle broadcasting a single constant scalar from the constant pool
4892 // On Sandybridge (no AVX2), it is still better to load a constant vector
4893 // from the constant pool and not to broadcast it from a scalar.
4894 // But override that restriction when optimizing for size.
4895 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4896 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4897 EVT CVT = Ld.getValueType();
4898 assert(!CVT.isVector() && "Must not broadcast a vector type");
4900 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4901 // For size optimization, also splat v2f64 and v2i64, and for size opt
4902 // with AVX2, also splat i8 and i16.
4903 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4904 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4905 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4906 const Constant *C = nullptr;
4907 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4908 C = CI->getConstantIntValue();
4909 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4910 C = CF->getConstantFPValue();
4912 assert(C && "Invalid constant type");
4914 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4915 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4916 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4917 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4918 MachinePointerInfo::getConstantPool(),
4919 false, false, false, Alignment);
4921 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4925 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4927 // Handle AVX2 in-register broadcasts.
4928 if (!IsLoad && Subtarget->hasInt256() &&
4929 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4930 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4932 // The scalar source must be a normal load.
4936 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4937 (Subtarget->hasVLX() && ScalarSize == 64))
4938 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4940 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4941 // double since there is no vbroadcastsd xmm
4942 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4943 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4944 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4947 // Unsupported broadcast.
4951 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4952 /// underlying vector and index.
4954 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4956 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4958 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4959 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4962 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4964 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4966 // (extract_vector_elt (vector_shuffle<2,u,u,u>
4967 // (extract_subvector (v8f32 %vreg0), Constant<4>),
4970 // In this case the vector is the extract_subvector expression and the index
4971 // is 2, as specified by the shuffle.
4972 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4973 SDValue ShuffleVec = SVOp->getOperand(0);
4974 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4975 assert(ShuffleVecVT.getVectorElementType() ==
4976 ExtractedFromVec.getSimpleValueType().getVectorElementType());
4978 int ShuffleIdx = SVOp->getMaskElt(Idx);
4979 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4980 ExtractedFromVec = ShuffleVec;
4986 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4987 MVT VT = Op.getSimpleValueType();
4989 // Skip if insert_vec_elt is not supported.
4990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4991 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4995 unsigned NumElems = Op.getNumOperands();
4999 SmallVector<unsigned, 4> InsertIndices;
5000 SmallVector<int, 8> Mask(NumElems, -1);
5002 for (unsigned i = 0; i != NumElems; ++i) {
5003 unsigned Opc = Op.getOperand(i).getOpcode();
5005 if (Opc == ISD::UNDEF)
5008 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5009 // Quit if more than 1 elements need inserting.
5010 if (InsertIndices.size() > 1)
5013 InsertIndices.push_back(i);
5017 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5018 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5019 // Quit if non-constant index.
5020 if (!isa<ConstantSDNode>(ExtIdx))
5022 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5024 // Quit if extracted from vector of different type.
5025 if (ExtractedFromVec.getValueType() != VT)
5028 if (!VecIn1.getNode())
5029 VecIn1 = ExtractedFromVec;
5030 else if (VecIn1 != ExtractedFromVec) {
5031 if (!VecIn2.getNode())
5032 VecIn2 = ExtractedFromVec;
5033 else if (VecIn2 != ExtractedFromVec)
5034 // Quit if more than 2 vectors to shuffle
5038 if (ExtractedFromVec == VecIn1)
5040 else if (ExtractedFromVec == VecIn2)
5041 Mask[i] = Idx + NumElems;
5044 if (!VecIn1.getNode())
5047 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5048 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5049 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5050 unsigned Idx = InsertIndices[i];
5051 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5052 DAG.getIntPtrConstant(Idx));
5058 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5060 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5062 MVT VT = Op.getSimpleValueType();
5063 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5064 "Unexpected type in LowerBUILD_VECTORvXi1!");
5067 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5068 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5069 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5070 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5073 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5074 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5075 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5076 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5079 bool AllContants = true;
5080 uint64_t Immediate = 0;
5081 int NonConstIdx = -1;
5082 bool IsSplat = true;
5083 unsigned NumNonConsts = 0;
5084 unsigned NumConsts = 0;
5085 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5086 SDValue In = Op.getOperand(idx);
5087 if (In.getOpcode() == ISD::UNDEF)
5089 if (!isa<ConstantSDNode>(In)) {
5090 AllContants = false;
5095 if (cast<ConstantSDNode>(In)->getZExtValue())
5096 Immediate |= (1ULL << idx);
5098 if (In != Op.getOperand(0))
5103 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5104 DAG.getConstant(Immediate, MVT::i16));
5105 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5106 DAG.getIntPtrConstant(0));
5109 if (NumNonConsts == 1 && NonConstIdx != 0) {
5112 SDValue VecAsImm = DAG.getConstant(Immediate,
5113 MVT::getIntegerVT(VT.getSizeInBits()));
5114 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5117 DstVec = DAG.getUNDEF(VT);
5118 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5119 Op.getOperand(NonConstIdx),
5120 DAG.getIntPtrConstant(NonConstIdx));
5122 if (!IsSplat && (NonConstIdx != 0))
5123 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5124 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5127 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5128 DAG.getConstant(-1, SelectVT),
5129 DAG.getConstant(0, SelectVT));
5131 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5132 DAG.getConstant((Immediate | 1), SelectVT),
5133 DAG.getConstant(Immediate, SelectVT));
5134 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5137 /// \brief Return true if \p N implements a horizontal binop and return the
5138 /// operands for the horizontal binop into V0 and V1.
5140 /// This is a helper function of PerformBUILD_VECTORCombine.
5141 /// This function checks that the build_vector \p N in input implements a
5142 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5143 /// operation to match.
5144 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5145 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5146 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5149 /// This function only analyzes elements of \p N whose indices are
5150 /// in range [BaseIdx, LastIdx).
5151 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5153 unsigned BaseIdx, unsigned LastIdx,
5154 SDValue &V0, SDValue &V1) {
5155 EVT VT = N->getValueType(0);
5157 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5158 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5159 "Invalid Vector in input!");
5161 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5162 bool CanFold = true;
5163 unsigned ExpectedVExtractIdx = BaseIdx;
5164 unsigned NumElts = LastIdx - BaseIdx;
5165 V0 = DAG.getUNDEF(VT);
5166 V1 = DAG.getUNDEF(VT);
5168 // Check if N implements a horizontal binop.
5169 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5170 SDValue Op = N->getOperand(i + BaseIdx);
5173 if (Op->getOpcode() == ISD::UNDEF) {
5174 // Update the expected vector extract index.
5175 if (i * 2 == NumElts)
5176 ExpectedVExtractIdx = BaseIdx;
5177 ExpectedVExtractIdx += 2;
5181 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5186 SDValue Op0 = Op.getOperand(0);
5187 SDValue Op1 = Op.getOperand(1);
5189 // Try to match the following pattern:
5190 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5191 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5192 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5193 Op0.getOperand(0) == Op1.getOperand(0) &&
5194 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5195 isa<ConstantSDNode>(Op1.getOperand(1)));
5199 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5200 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5202 if (i * 2 < NumElts) {
5203 if (V0.getOpcode() == ISD::UNDEF)
5204 V0 = Op0.getOperand(0);
5206 if (V1.getOpcode() == ISD::UNDEF)
5207 V1 = Op0.getOperand(0);
5208 if (i * 2 == NumElts)
5209 ExpectedVExtractIdx = BaseIdx;
5212 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5213 if (I0 == ExpectedVExtractIdx)
5214 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5215 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5216 // Try to match the following dag sequence:
5217 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5218 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5222 ExpectedVExtractIdx += 2;
5228 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5229 /// a concat_vector.
5231 /// This is a helper function of PerformBUILD_VECTORCombine.
5232 /// This function expects two 256-bit vectors called V0 and V1.
5233 /// At first, each vector is split into two separate 128-bit vectors.
5234 /// Then, the resulting 128-bit vectors are used to implement two
5235 /// horizontal binary operations.
5237 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5239 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5240 /// the two new horizontal binop.
5241 /// When Mode is set, the first horizontal binop dag node would take as input
5242 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5243 /// horizontal binop dag node would take as input the lower 128-bit of V1
5244 /// and the upper 128-bit of V1.
5246 /// HADD V0_LO, V0_HI
5247 /// HADD V1_LO, V1_HI
5249 /// Otherwise, the first horizontal binop dag node takes as input the lower
5250 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5251 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5253 /// HADD V0_LO, V1_LO
5254 /// HADD V0_HI, V1_HI
5256 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5257 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5258 /// the upper 128-bits of the result.
5259 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5260 SDLoc DL, SelectionDAG &DAG,
5261 unsigned X86Opcode, bool Mode,
5262 bool isUndefLO, bool isUndefHI) {
5263 EVT VT = V0.getValueType();
5264 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5265 "Invalid nodes in input!");
5267 unsigned NumElts = VT.getVectorNumElements();
5268 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5269 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5270 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5271 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5272 EVT NewVT = V0_LO.getValueType();
5274 SDValue LO = DAG.getUNDEF(NewVT);
5275 SDValue HI = DAG.getUNDEF(NewVT);
5278 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5279 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5280 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5281 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5282 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5284 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5285 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5286 V1_LO->getOpcode() != ISD::UNDEF))
5287 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5289 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5290 V1_HI->getOpcode() != ISD::UNDEF))
5291 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5294 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5297 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5298 /// sequence of 'vadd + vsub + blendi'.
5299 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5300 const X86Subtarget *Subtarget) {
5302 EVT VT = BV->getValueType(0);
5303 unsigned NumElts = VT.getVectorNumElements();
5304 SDValue InVec0 = DAG.getUNDEF(VT);
5305 SDValue InVec1 = DAG.getUNDEF(VT);
5307 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5308 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5310 // Odd-numbered elements in the input build vector are obtained from
5311 // adding two integer/float elements.
5312 // Even-numbered elements in the input build vector are obtained from
5313 // subtracting two integer/float elements.
5314 unsigned ExpectedOpcode = ISD::FSUB;
5315 unsigned NextExpectedOpcode = ISD::FADD;
5316 bool AddFound = false;
5317 bool SubFound = false;
5319 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5320 SDValue Op = BV->getOperand(i);
5322 // Skip 'undef' values.
5323 unsigned Opcode = Op.getOpcode();
5324 if (Opcode == ISD::UNDEF) {
5325 std::swap(ExpectedOpcode, NextExpectedOpcode);
5329 // Early exit if we found an unexpected opcode.
5330 if (Opcode != ExpectedOpcode)
5333 SDValue Op0 = Op.getOperand(0);
5334 SDValue Op1 = Op.getOperand(1);
5336 // Try to match the following pattern:
5337 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5338 // Early exit if we cannot match that sequence.
5339 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5340 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5341 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5342 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5343 Op0.getOperand(1) != Op1.getOperand(1))
5346 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5350 // We found a valid add/sub node. Update the information accordingly.
5356 // Update InVec0 and InVec1.
5357 if (InVec0.getOpcode() == ISD::UNDEF)
5358 InVec0 = Op0.getOperand(0);
5359 if (InVec1.getOpcode() == ISD::UNDEF)
5360 InVec1 = Op1.getOperand(0);
5362 // Make sure that operands in input to each add/sub node always
5363 // come from a same pair of vectors.
5364 if (InVec0 != Op0.getOperand(0)) {
5365 if (ExpectedOpcode == ISD::FSUB)
5368 // FADD is commutable. Try to commute the operands
5369 // and then test again.
5370 std::swap(Op0, Op1);
5371 if (InVec0 != Op0.getOperand(0))
5375 if (InVec1 != Op1.getOperand(0))
5378 // Update the pair of expected opcodes.
5379 std::swap(ExpectedOpcode, NextExpectedOpcode);
5382 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5383 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5384 InVec1.getOpcode() != ISD::UNDEF)
5385 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5390 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5391 const X86Subtarget *Subtarget) {
5393 EVT VT = N->getValueType(0);
5394 unsigned NumElts = VT.getVectorNumElements();
5395 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5396 SDValue InVec0, InVec1;
5398 // Try to match an ADDSUB.
5399 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5400 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5401 SDValue Value = matchAddSub(BV, DAG, Subtarget);
5402 if (Value.getNode())
5406 // Try to match horizontal ADD/SUB.
5407 unsigned NumUndefsLO = 0;
5408 unsigned NumUndefsHI = 0;
5409 unsigned Half = NumElts/2;
5411 // Count the number of UNDEF operands in the build_vector in input.
5412 for (unsigned i = 0, e = Half; i != e; ++i)
5413 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5416 for (unsigned i = Half, e = NumElts; i != e; ++i)
5417 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5420 // Early exit if this is either a build_vector of all UNDEFs or all the
5421 // operands but one are UNDEF.
5422 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5425 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5426 // Try to match an SSE3 float HADD/HSUB.
5427 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5428 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5430 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5431 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5432 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5433 // Try to match an SSSE3 integer HADD/HSUB.
5434 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5435 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5437 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5438 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5441 if (!Subtarget->hasAVX())
5444 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5445 // Try to match an AVX horizontal add/sub of packed single/double
5446 // precision floating point values from 256-bit vectors.
5447 SDValue InVec2, InVec3;
5448 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5449 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5450 ((InVec0.getOpcode() == ISD::UNDEF ||
5451 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5452 ((InVec1.getOpcode() == ISD::UNDEF ||
5453 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5454 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5456 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5457 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5458 ((InVec0.getOpcode() == ISD::UNDEF ||
5459 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5460 ((InVec1.getOpcode() == ISD::UNDEF ||
5461 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5462 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5463 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5464 // Try to match an AVX2 horizontal add/sub of signed integers.
5465 SDValue InVec2, InVec3;
5467 bool CanFold = true;
5469 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5470 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5471 ((InVec0.getOpcode() == ISD::UNDEF ||
5472 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5473 ((InVec1.getOpcode() == ISD::UNDEF ||
5474 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5475 X86Opcode = X86ISD::HADD;
5476 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5477 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5478 ((InVec0.getOpcode() == ISD::UNDEF ||
5479 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5480 ((InVec1.getOpcode() == ISD::UNDEF ||
5481 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5482 X86Opcode = X86ISD::HSUB;
5487 // Fold this build_vector into a single horizontal add/sub.
5488 // Do this only if the target has AVX2.
5489 if (Subtarget->hasAVX2())
5490 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5492 // Do not try to expand this build_vector into a pair of horizontal
5493 // add/sub if we can emit a pair of scalar add/sub.
5494 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5497 // Convert this build_vector into a pair of horizontal binop followed by
5499 bool isUndefLO = NumUndefsLO == Half;
5500 bool isUndefHI = NumUndefsHI == Half;
5501 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5502 isUndefLO, isUndefHI);
5506 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5507 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5509 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5510 X86Opcode = X86ISD::HADD;
5511 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5512 X86Opcode = X86ISD::HSUB;
5513 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5514 X86Opcode = X86ISD::FHADD;
5515 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5516 X86Opcode = X86ISD::FHSUB;
5520 // Don't try to expand this build_vector into a pair of horizontal add/sub
5521 // if we can simply emit a pair of scalar add/sub.
5522 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5525 // Convert this build_vector into two horizontal add/sub followed by
5527 bool isUndefLO = NumUndefsLO == Half;
5528 bool isUndefHI = NumUndefsHI == Half;
5529 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5530 isUndefLO, isUndefHI);
5537 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5540 MVT VT = Op.getSimpleValueType();
5541 MVT ExtVT = VT.getVectorElementType();
5542 unsigned NumElems = Op.getNumOperands();
5544 // Generate vectors for predicate vectors.
5545 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5546 return LowerBUILD_VECTORvXi1(Op, DAG);
5548 // Vectors containing all zeros can be matched by pxor and xorps later
5549 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5550 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5551 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5552 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5555 return getZeroVector(VT, Subtarget, DAG, dl);
5558 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5559 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5560 // vpcmpeqd on 256-bit vectors.
5561 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5562 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5565 if (!VT.is512BitVector())
5566 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5569 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5570 if (Broadcast.getNode())
5573 unsigned EVTBits = ExtVT.getSizeInBits();
5575 unsigned NumZero = 0;
5576 unsigned NumNonZero = 0;
5577 unsigned NonZeros = 0;
5578 bool IsAllConstants = true;
5579 SmallSet<SDValue, 8> Values;
5580 for (unsigned i = 0; i < NumElems; ++i) {
5581 SDValue Elt = Op.getOperand(i);
5582 if (Elt.getOpcode() == ISD::UNDEF)
5585 if (Elt.getOpcode() != ISD::Constant &&
5586 Elt.getOpcode() != ISD::ConstantFP)
5587 IsAllConstants = false;
5588 if (X86::isZeroNode(Elt))
5591 NonZeros |= (1 << i);
5596 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5597 if (NumNonZero == 0)
5598 return DAG.getUNDEF(VT);
5600 // Special case for single non-zero, non-undef, element.
5601 if (NumNonZero == 1) {
5602 unsigned Idx = countTrailingZeros(NonZeros);
5603 SDValue Item = Op.getOperand(Idx);
5605 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5606 // the value are obviously zero, truncate the value to i32 and do the
5607 // insertion that way. Only do this if the value is non-constant or if the
5608 // value is a constant being inserted into element 0. It is cheaper to do
5609 // a constant pool load than it is to do a movd + shuffle.
5610 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5611 (!IsAllConstants || Idx == 0)) {
5612 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5614 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5615 EVT VecVT = MVT::v4i32;
5617 // Truncate the value (which may itself be a constant) to i32, and
5618 // convert it to a vector with movd (S2V+shuffle to zero extend).
5619 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5620 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5622 ISD::BITCAST, dl, VT,
5623 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5627 // If we have a constant or non-constant insertion into the low element of
5628 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5629 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5630 // depending on what the source datatype is.
5633 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5635 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5636 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5637 if (VT.is256BitVector() || VT.is512BitVector()) {
5638 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5639 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5640 Item, DAG.getIntPtrConstant(0));
5642 assert(VT.is128BitVector() && "Expected an SSE value type!");
5643 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5644 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5645 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5648 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5649 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5650 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5651 if (VT.is256BitVector()) {
5652 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5653 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5655 assert(VT.is128BitVector() && "Expected an SSE value type!");
5656 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5658 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5662 // Is it a vector logical left shift?
5663 if (NumElems == 2 && Idx == 1 &&
5664 X86::isZeroNode(Op.getOperand(0)) &&
5665 !X86::isZeroNode(Op.getOperand(1))) {
5666 unsigned NumBits = VT.getSizeInBits();
5667 return getVShift(true, VT,
5668 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5669 VT, Op.getOperand(1)),
5670 NumBits/2, DAG, *this, dl);
5673 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5676 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5677 // is a non-constant being inserted into an element other than the low one,
5678 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5679 // movd/movss) to move this into the low element, then shuffle it into
5681 if (EVTBits == 32) {
5682 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5683 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5687 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5688 if (Values.size() == 1) {
5689 if (EVTBits == 32) {
5690 // Instead of a shuffle like this:
5691 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5692 // Check if it's possible to issue this instead.
5693 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5694 unsigned Idx = countTrailingZeros(NonZeros);
5695 SDValue Item = Op.getOperand(Idx);
5696 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5697 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5702 // A vector full of immediates; various special cases are already
5703 // handled, so this is best done with a single constant-pool load.
5707 // For AVX-length vectors, see if we can use a vector load to get all of the
5708 // elements, otherwise build the individual 128-bit pieces and use
5709 // shuffles to put them in place.
5710 if (VT.is256BitVector() || VT.is512BitVector()) {
5711 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5713 // Check for a build vector of consecutive loads.
5714 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5717 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5719 // Build both the lower and upper subvector.
5720 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5721 makeArrayRef(&V[0], NumElems/2));
5722 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5723 makeArrayRef(&V[NumElems / 2], NumElems/2));
5725 // Recreate the wider vector with the lower and upper part.
5726 if (VT.is256BitVector())
5727 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5728 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5731 // Let legalizer expand 2-wide build_vectors.
5732 if (EVTBits == 64) {
5733 if (NumNonZero == 1) {
5734 // One half is zero or undef.
5735 unsigned Idx = countTrailingZeros(NonZeros);
5736 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5737 Op.getOperand(Idx));
5738 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5743 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5744 if (EVTBits == 8 && NumElems == 16) {
5745 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5747 if (V.getNode()) return V;
5750 if (EVTBits == 16 && NumElems == 8) {
5751 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5753 if (V.getNode()) return V;
5756 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5757 if (EVTBits == 32 && NumElems == 4) {
5758 SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5763 // If element VT is == 32 bits, turn it into a number of shuffles.
5764 SmallVector<SDValue, 8> V(NumElems);
5765 if (NumElems == 4 && NumZero > 0) {
5766 for (unsigned i = 0; i < 4; ++i) {
5767 bool isZero = !(NonZeros & (1 << i));
5769 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5771 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5774 for (unsigned i = 0; i < 2; ++i) {
5775 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5778 V[i] = V[i*2]; // Must be a zero vector.
5781 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5784 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5787 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5792 bool Reverse1 = (NonZeros & 0x3) == 2;
5793 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5797 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5798 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5800 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5803 if (Values.size() > 1 && VT.is128BitVector()) {
5804 // Check for a build vector of consecutive loads.
5805 for (unsigned i = 0; i < NumElems; ++i)
5806 V[i] = Op.getOperand(i);
5808 // Check for elements which are consecutive loads.
5809 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5813 // Check for a build vector from mostly shuffle plus few inserting.
5814 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5818 // For SSE 4.1, use insertps to put the high elements into the low element.
5819 if (Subtarget->hasSSE41()) {
5821 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5822 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5824 Result = DAG.getUNDEF(VT);
5826 for (unsigned i = 1; i < NumElems; ++i) {
5827 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5828 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5829 Op.getOperand(i), DAG.getIntPtrConstant(i));
5834 // Otherwise, expand into a number of unpckl*, start by extending each of
5835 // our (non-undef) elements to the full vector width with the element in the
5836 // bottom slot of the vector (which generates no code for SSE).
5837 for (unsigned i = 0; i < NumElems; ++i) {
5838 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5839 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5841 V[i] = DAG.getUNDEF(VT);
5844 // Next, we iteratively mix elements, e.g. for v4f32:
5845 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5846 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5847 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5848 unsigned EltStride = NumElems >> 1;
5849 while (EltStride != 0) {
5850 for (unsigned i = 0; i < EltStride; ++i) {
5851 // If V[i+EltStride] is undef and this is the first round of mixing,
5852 // then it is safe to just drop this shuffle: V[i] is already in the
5853 // right place, the one element (since it's the first round) being
5854 // inserted as undef can be dropped. This isn't safe for successive
5855 // rounds because they will permute elements within both vectors.
5856 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5857 EltStride == NumElems/2)
5860 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5869 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5870 // to create 256-bit vectors from two other 128-bit ones.
5871 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5873 MVT ResVT = Op.getSimpleValueType();
5875 assert((ResVT.is256BitVector() ||
5876 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5878 SDValue V1 = Op.getOperand(0);
5879 SDValue V2 = Op.getOperand(1);
5880 unsigned NumElems = ResVT.getVectorNumElements();
5881 if(ResVT.is256BitVector())
5882 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5884 if (Op.getNumOperands() == 4) {
5885 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5886 ResVT.getVectorNumElements()/2);
5887 SDValue V3 = Op.getOperand(2);
5888 SDValue V4 = Op.getOperand(3);
5889 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5890 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5892 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5895 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5896 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
5897 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5898 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5899 Op.getNumOperands() == 4)));
5901 // AVX can use the vinsertf128 instruction to create 256-bit vectors
5902 // from two other 128-bit ones.
5904 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5905 return LowerAVXCONCAT_VECTORS(Op, DAG);
5909 //===----------------------------------------------------------------------===//
5910 // Vector shuffle lowering
5912 // This is an experimental code path for lowering vector shuffles on x86. It is
5913 // designed to handle arbitrary vector shuffles and blends, gracefully
5914 // degrading performance as necessary. It works hard to recognize idiomatic
5915 // shuffles and lower them to optimal instruction patterns without leaving
5916 // a framework that allows reasonably efficient handling of all vector shuffle
5918 //===----------------------------------------------------------------------===//
5920 /// \brief Tiny helper function to identify a no-op mask.
5922 /// This is a somewhat boring predicate function. It checks whether the mask
5923 /// array input, which is assumed to be a single-input shuffle mask of the kind
5924 /// used by the X86 shuffle instructions (not a fully general
5925 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5926 /// in-place shuffle are 'no-op's.
5927 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5928 for (int i = 0, Size = Mask.size(); i < Size; ++i)
5929 if (Mask[i] != -1 && Mask[i] != i)
5934 /// \brief Helper function to classify a mask as a single-input mask.
5936 /// This isn't a generic single-input test because in the vector shuffle
5937 /// lowering we canonicalize single inputs to be the first input operand. This
5938 /// means we can more quickly test for a single input by only checking whether
5939 /// an input from the second operand exists. We also assume that the size of
5940 /// mask corresponds to the size of the input vectors which isn't true in the
5941 /// fully general case.
5942 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5944 if (M >= (int)Mask.size())
5949 /// \brief Test whether there are elements crossing 128-bit lanes in this
5952 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5953 /// and we routinely test for these.
5954 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5955 int LaneSize = 128 / VT.getScalarSizeInBits();
5956 int Size = Mask.size();
5957 for (int i = 0; i < Size; ++i)
5958 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5963 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5965 /// This checks a shuffle mask to see if it is performing the same
5966 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5967 /// that it is also not lane-crossing. It may however involve a blend from the
5968 /// same lane of a second vector.
5970 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5971 /// non-trivial to compute in the face of undef lanes. The representation is
5972 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5973 /// entries from both V1 and V2 inputs to the wider mask.
5975 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5976 SmallVectorImpl<int> &RepeatedMask) {
5977 int LaneSize = 128 / VT.getScalarSizeInBits();
5978 RepeatedMask.resize(LaneSize, -1);
5979 int Size = Mask.size();
5980 for (int i = 0; i < Size; ++i) {
5983 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
5984 // This entry crosses lanes, so there is no way to model this shuffle.
5987 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
5988 if (RepeatedMask[i % LaneSize] == -1)
5989 // This is the first non-undef entry in this slot of a 128-bit lane.
5990 RepeatedMask[i % LaneSize] =
5991 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
5992 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
5993 // Found a mismatch with the repeated mask.
5999 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6002 /// This is a fast way to test a shuffle mask against a fixed pattern:
6004 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6006 /// It returns true if the mask is exactly as wide as the argument list, and
6007 /// each element of the mask is either -1 (signifying undef) or the value given
6008 /// in the argument.
6009 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6010 ArrayRef<int> ExpectedMask) {
6011 if (Mask.size() != ExpectedMask.size())
6014 int Size = Mask.size();
6016 // If the values are build vectors, we can look through them to find
6017 // equivalent inputs that make the shuffles equivalent.
6018 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6019 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6021 for (int i = 0; i < Size; ++i)
6022 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6023 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6024 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6025 if (!MaskBV || !ExpectedBV ||
6026 MaskBV->getOperand(Mask[i] % Size) !=
6027 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6034 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6036 /// This helper function produces an 8-bit shuffle immediate corresponding to
6037 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6038 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6041 /// NB: We rely heavily on "undef" masks preserving the input lane.
6042 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6043 SelectionDAG &DAG) {
6044 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6045 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6046 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6047 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6048 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6051 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6052 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6053 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6054 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6055 return DAG.getConstant(Imm, MVT::i8);
6058 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6060 /// This is used as a fallback approach when first class blend instructions are
6061 /// unavailable. Currently it is only suitable for integer vectors, but could
6062 /// be generalized for floating point vectors if desirable.
6063 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6064 SDValue V2, ArrayRef<int> Mask,
6065 SelectionDAG &DAG) {
6066 assert(VT.isInteger() && "Only supports integer vector types!");
6067 MVT EltVT = VT.getScalarType();
6068 int NumEltBits = EltVT.getSizeInBits();
6069 SDValue Zero = DAG.getConstant(0, EltVT);
6070 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6071 SmallVector<SDValue, 16> MaskOps;
6072 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6073 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6074 return SDValue(); // Shuffled input!
6075 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6078 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6079 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6080 // We have to cast V2 around.
6081 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6082 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6083 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6084 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6085 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6086 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6089 /// \brief Try to emit a blend instruction for a shuffle.
6091 /// This doesn't do any checks for the availability of instructions for blending
6092 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6093 /// be matched in the backend with the type given. What it does check for is
6094 /// that the shuffle mask is in fact a blend.
6095 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6096 SDValue V2, ArrayRef<int> Mask,
6097 const X86Subtarget *Subtarget,
6098 SelectionDAG &DAG) {
6099 unsigned BlendMask = 0;
6100 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6101 if (Mask[i] >= Size) {
6102 if (Mask[i] != i + Size)
6103 return SDValue(); // Shuffled V2 input!
6104 BlendMask |= 1u << i;
6107 if (Mask[i] >= 0 && Mask[i] != i)
6108 return SDValue(); // Shuffled V1 input!
6110 switch (VT.SimpleTy) {
6115 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6116 DAG.getConstant(BlendMask, MVT::i8));
6120 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6124 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6125 // that instruction.
6126 if (Subtarget->hasAVX2()) {
6127 // Scale the blend by the number of 32-bit dwords per element.
6128 int Scale = VT.getScalarSizeInBits() / 32;
6130 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6131 if (Mask[i] >= Size)
6132 for (int j = 0; j < Scale; ++j)
6133 BlendMask |= 1u << (i * Scale + j);
6135 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6136 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6137 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6138 return DAG.getNode(ISD::BITCAST, DL, VT,
6139 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6140 DAG.getConstant(BlendMask, MVT::i8)));
6144 // For integer shuffles we need to expand the mask and cast the inputs to
6145 // v8i16s prior to blending.
6146 int Scale = 8 / VT.getVectorNumElements();
6148 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6149 if (Mask[i] >= Size)
6150 for (int j = 0; j < Scale; ++j)
6151 BlendMask |= 1u << (i * Scale + j);
6153 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6154 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6155 return DAG.getNode(ISD::BITCAST, DL, VT,
6156 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6157 DAG.getConstant(BlendMask, MVT::i8)));
6161 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6162 SmallVector<int, 8> RepeatedMask;
6163 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6164 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6165 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6167 for (int i = 0; i < 8; ++i)
6168 if (RepeatedMask[i] >= 16)
6169 BlendMask |= 1u << i;
6170 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6171 DAG.getConstant(BlendMask, MVT::i8));
6177 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6178 "256-bit byte-blends require AVX2 support!");
6180 // Scale the blend by the number of bytes per element.
6181 int Scale = VT.getScalarSizeInBits() / 8;
6183 // This form of blend is always done on bytes. Compute the byte vector
6185 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6187 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6188 // mix of LLVM's code generator and the x86 backend. We tell the code
6189 // generator that boolean values in the elements of an x86 vector register
6190 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6191 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6192 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6193 // of the element (the remaining are ignored) and 0 in that high bit would
6194 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6195 // the LLVM model for boolean values in vector elements gets the relevant
6196 // bit set, it is set backwards and over constrained relative to x86's
6198 SmallVector<SDValue, 32> VSELECTMask;
6199 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6200 for (int j = 0; j < Scale; ++j)
6201 VSELECTMask.push_back(
6202 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6203 : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6205 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6206 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6208 ISD::BITCAST, DL, VT,
6209 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6210 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6215 llvm_unreachable("Not a supported integer vector type!");
6219 /// \brief Try to lower as a blend of elements from two inputs followed by
6220 /// a single-input permutation.
6222 /// This matches the pattern where we can blend elements from two inputs and
6223 /// then reduce the shuffle to a single-input permutation.
6224 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6227 SelectionDAG &DAG) {
6228 // We build up the blend mask while checking whether a blend is a viable way
6229 // to reduce the shuffle.
6230 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6231 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6233 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6237 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6239 if (BlendMask[Mask[i] % Size] == -1)
6240 BlendMask[Mask[i] % Size] = Mask[i];
6241 else if (BlendMask[Mask[i] % Size] != Mask[i])
6242 return SDValue(); // Can't blend in the needed input!
6244 PermuteMask[i] = Mask[i] % Size;
6247 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6248 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6251 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6252 /// blends and permutes.
6254 /// This matches the extremely common pattern for handling combined
6255 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6256 /// operations. It will try to pick the best arrangement of shuffles and
6258 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6262 SelectionDAG &DAG) {
6263 // Shuffle the input elements into the desired positions in V1 and V2 and
6264 // blend them together.
6265 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6266 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6267 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6268 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6269 if (Mask[i] >= 0 && Mask[i] < Size) {
6270 V1Mask[i] = Mask[i];
6272 } else if (Mask[i] >= Size) {
6273 V2Mask[i] = Mask[i] - Size;
6274 BlendMask[i] = i + Size;
6277 // Try to lower with the simpler initial blend strategy unless one of the
6278 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6279 // shuffle may be able to fold with a load or other benefit. However, when
6280 // we'll have to do 2x as many shuffles in order to achieve this, blending
6281 // first is a better strategy.
6282 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6283 if (SDValue BlendPerm =
6284 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6287 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6288 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6289 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6292 /// \brief Try to lower a vector shuffle as a byte rotation.
6294 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6295 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6296 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6297 /// try to generically lower a vector shuffle through such an pattern. It
6298 /// does not check for the profitability of lowering either as PALIGNR or
6299 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6300 /// This matches shuffle vectors that look like:
6302 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6304 /// Essentially it concatenates V1 and V2, shifts right by some number of
6305 /// elements, and takes the low elements as the result. Note that while this is
6306 /// specified as a *right shift* because x86 is little-endian, it is a *left
6307 /// rotate* of the vector lanes.
6308 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6311 const X86Subtarget *Subtarget,
6312 SelectionDAG &DAG) {
6313 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6315 int NumElts = Mask.size();
6316 int NumLanes = VT.getSizeInBits() / 128;
6317 int NumLaneElts = NumElts / NumLanes;
6319 // We need to detect various ways of spelling a rotation:
6320 // [11, 12, 13, 14, 15, 0, 1, 2]
6321 // [-1, 12, 13, 14, -1, -1, 1, -1]
6322 // [-1, -1, -1, -1, -1, -1, 1, 2]
6323 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6324 // [-1, 4, 5, 6, -1, -1, 9, -1]
6325 // [-1, 4, 5, 6, -1, -1, -1, -1]
6328 for (int l = 0; l < NumElts; l += NumLaneElts) {
6329 for (int i = 0; i < NumLaneElts; ++i) {
6330 if (Mask[l + i] == -1)
6332 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6334 // Get the mod-Size index and lane correct it.
6335 int LaneIdx = (Mask[l + i] % NumElts) - l;
6336 // Make sure it was in this lane.
6337 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6340 // Determine where a rotated vector would have started.
6341 int StartIdx = i - LaneIdx;
6343 // The identity rotation isn't interesting, stop.
6346 // If we found the tail of a vector the rotation must be the missing
6347 // front. If we found the head of a vector, it must be how much of the
6349 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6352 Rotation = CandidateRotation;
6353 else if (Rotation != CandidateRotation)
6354 // The rotations don't match, so we can't match this mask.
6357 // Compute which value this mask is pointing at.
6358 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6360 // Compute which of the two target values this index should be assigned
6361 // to. This reflects whether the high elements are remaining or the low
6362 // elements are remaining.
6363 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6365 // Either set up this value if we've not encountered it before, or check
6366 // that it remains consistent.
6369 else if (TargetV != MaskV)
6370 // This may be a rotation, but it pulls from the inputs in some
6371 // unsupported interleaving.
6376 // Check that we successfully analyzed the mask, and normalize the results.
6377 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6378 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6384 // The actual rotate instruction rotates bytes, so we need to scale the
6385 // rotation based on how many bytes are in the vector lane.
6386 int Scale = 16 / NumLaneElts;
6388 // SSSE3 targets can use the palignr instruction.
6389 if (Subtarget->hasSSSE3()) {
6390 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6391 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6392 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6393 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6395 return DAG.getNode(ISD::BITCAST, DL, VT,
6396 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6397 DAG.getConstant(Rotation * Scale, MVT::i8)));
6400 assert(VT.getSizeInBits() == 128 &&
6401 "Rotate-based lowering only supports 128-bit lowering!");
6402 assert(Mask.size() <= 16 &&
6403 "Can shuffle at most 16 bytes in a 128-bit vector!");
6405 // Default SSE2 implementation
6406 int LoByteShift = 16 - Rotation * Scale;
6407 int HiByteShift = Rotation * Scale;
6409 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6410 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6411 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6413 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6414 DAG.getConstant(LoByteShift, MVT::i8));
6415 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6416 DAG.getConstant(HiByteShift, MVT::i8));
6417 return DAG.getNode(ISD::BITCAST, DL, VT,
6418 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6421 /// \brief Compute whether each element of a shuffle is zeroable.
6423 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6424 /// Either it is an undef element in the shuffle mask, the element of the input
6425 /// referenced is undef, or the element of the input referenced is known to be
6426 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6427 /// as many lanes with this technique as possible to simplify the remaining
6429 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6430 SDValue V1, SDValue V2) {
6431 SmallBitVector Zeroable(Mask.size(), false);
6433 while (V1.getOpcode() == ISD::BITCAST)
6434 V1 = V1->getOperand(0);
6435 while (V2.getOpcode() == ISD::BITCAST)
6436 V2 = V2->getOperand(0);
6438 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6439 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6441 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6443 // Handle the easy cases.
6444 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6449 // If this is an index into a build_vector node (which has the same number
6450 // of elements), dig out the input value and use it.
6451 SDValue V = M < Size ? V1 : V2;
6452 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6455 SDValue Input = V.getOperand(M % Size);
6456 // The UNDEF opcode check really should be dead code here, but not quite
6457 // worth asserting on (it isn't invalid, just unexpected).
6458 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6465 /// \brief Try to emit a bitmask instruction for a shuffle.
6467 /// This handles cases where we can model a blend exactly as a bitmask due to
6468 /// one of the inputs being zeroable.
6469 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6470 SDValue V2, ArrayRef<int> Mask,
6471 SelectionDAG &DAG) {
6472 MVT EltVT = VT.getScalarType();
6473 int NumEltBits = EltVT.getSizeInBits();
6474 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6475 SDValue Zero = DAG.getConstant(0, IntEltVT);
6476 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6477 if (EltVT.isFloatingPoint()) {
6478 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6479 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6481 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6482 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6484 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6487 if (Mask[i] % Size != i)
6488 return SDValue(); // Not a blend.
6490 V = Mask[i] < Size ? V1 : V2;
6491 else if (V != (Mask[i] < Size ? V1 : V2))
6492 return SDValue(); // Can only let one input through the mask.
6494 VMaskOps[i] = AllOnes;
6497 return SDValue(); // No non-zeroable elements!
6499 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6500 V = DAG.getNode(VT.isFloatingPoint()
6501 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6506 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6508 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6509 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6510 /// matches elements from one of the input vectors shuffled to the left or
6511 /// right with zeroable elements 'shifted in'. It handles both the strictly
6512 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6515 /// PSHL : (little-endian) left bit shift.
6516 /// [ zz, 0, zz, 2 ]
6517 /// [ -1, 4, zz, -1 ]
6518 /// PSRL : (little-endian) right bit shift.
6520 /// [ -1, -1, 7, zz]
6521 /// PSLLDQ : (little-endian) left byte shift
6522 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6523 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6524 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6525 /// PSRLDQ : (little-endian) right byte shift
6526 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6527 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6528 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6529 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6530 SDValue V2, ArrayRef<int> Mask,
6531 SelectionDAG &DAG) {
6532 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6534 int Size = Mask.size();
6535 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6537 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6538 for (int i = 0; i < Size; i += Scale)
6539 for (int j = 0; j < Shift; ++j)
6540 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6546 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6547 for (int i = 0; i != Size; i += Scale) {
6548 unsigned Pos = Left ? i + Shift : i;
6549 unsigned Low = Left ? i : i + Shift;
6550 unsigned Len = Scale - Shift;
6551 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6552 Low + (V == V1 ? 0 : Size)))
6556 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6557 bool ByteShift = ShiftEltBits > 64;
6558 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6559 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6560 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6562 // Normalize the scale for byte shifts to still produce an i64 element
6564 Scale = ByteShift ? Scale / 2 : Scale;
6566 // We need to round trip through the appropriate type for the shift.
6567 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6568 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6569 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6570 "Illegal integer vector type");
6571 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6573 V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6574 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6577 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6578 // keep doubling the size of the integer elements up to that. We can
6579 // then shift the elements of the integer vector by whole multiples of
6580 // their width within the elements of the larger integer vector. Test each
6581 // multiple to see if we can find a match with the moved element indices
6582 // and that the shifted in elements are all zeroable.
6583 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6584 for (int Shift = 1; Shift != Scale; ++Shift)
6585 for (bool Left : {true, false})
6586 if (CheckZeros(Shift, Scale, Left))
6587 for (SDValue V : {V1, V2})
6588 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6595 /// \brief Lower a vector shuffle as a zero or any extension.
6597 /// Given a specific number of elements, element bit width, and extension
6598 /// stride, produce either a zero or any extension based on the available
6599 /// features of the subtarget.
6600 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6601 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6602 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6603 assert(Scale > 1 && "Need a scale to extend.");
6604 int NumElements = VT.getVectorNumElements();
6605 int EltBits = VT.getScalarSizeInBits();
6606 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6607 "Only 8, 16, and 32 bit elements can be extended.");
6608 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6610 // Found a valid zext mask! Try various lowering strategies based on the
6611 // input type and available ISA extensions.
6612 if (Subtarget->hasSSE41()) {
6613 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6614 NumElements / Scale);
6615 return DAG.getNode(ISD::BITCAST, DL, VT,
6616 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6619 // For any extends we can cheat for larger element sizes and use shuffle
6620 // instructions that can fold with a load and/or copy.
6621 if (AnyExt && EltBits == 32) {
6622 int PSHUFDMask[4] = {0, -1, 1, -1};
6624 ISD::BITCAST, DL, VT,
6625 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6626 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6627 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6629 if (AnyExt && EltBits == 16 && Scale > 2) {
6630 int PSHUFDMask[4] = {0, -1, 0, -1};
6631 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6632 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6633 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6634 int PSHUFHWMask[4] = {1, -1, -1, -1};
6636 ISD::BITCAST, DL, VT,
6637 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6638 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6639 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6642 // If this would require more than 2 unpack instructions to expand, use
6643 // pshufb when available. We can only use more than 2 unpack instructions
6644 // when zero extending i8 elements which also makes it easier to use pshufb.
6645 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6646 assert(NumElements == 16 && "Unexpected byte vector width!");
6647 SDValue PSHUFBMask[16];
6648 for (int i = 0; i < 16; ++i)
6650 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6651 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6652 return DAG.getNode(ISD::BITCAST, DL, VT,
6653 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6654 DAG.getNode(ISD::BUILD_VECTOR, DL,
6655 MVT::v16i8, PSHUFBMask)));
6658 // Otherwise emit a sequence of unpacks.
6660 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6661 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6662 : getZeroVector(InputVT, Subtarget, DAG, DL);
6663 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6664 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6668 } while (Scale > 1);
6669 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6672 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6674 /// This routine will try to do everything in its power to cleverly lower
6675 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6676 /// check for the profitability of this lowering, it tries to aggressively
6677 /// match this pattern. It will use all of the micro-architectural details it
6678 /// can to emit an efficient lowering. It handles both blends with all-zero
6679 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6680 /// masking out later).
6682 /// The reason we have dedicated lowering for zext-style shuffles is that they
6683 /// are both incredibly common and often quite performance sensitive.
6684 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6685 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6686 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6687 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6689 int Bits = VT.getSizeInBits();
6690 int NumElements = VT.getVectorNumElements();
6691 assert(VT.getScalarSizeInBits() <= 32 &&
6692 "Exceeds 32-bit integer zero extension limit");
6693 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6695 // Define a helper function to check a particular ext-scale and lower to it if
6697 auto Lower = [&](int Scale) -> SDValue {
6700 for (int i = 0; i < NumElements; ++i) {
6702 continue; // Valid anywhere but doesn't tell us anything.
6703 if (i % Scale != 0) {
6704 // Each of the extended elements need to be zeroable.
6708 // We no longer are in the anyext case.
6713 // Each of the base elements needs to be consecutive indices into the
6714 // same input vector.
6715 SDValue V = Mask[i] < NumElements ? V1 : V2;
6718 else if (InputV != V)
6719 return SDValue(); // Flip-flopping inputs.
6721 if (Mask[i] % NumElements != i / Scale)
6722 return SDValue(); // Non-consecutive strided elements.
6725 // If we fail to find an input, we have a zero-shuffle which should always
6726 // have already been handled.
6727 // FIXME: Maybe handle this here in case during blending we end up with one?
6731 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6732 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6735 // The widest scale possible for extending is to a 64-bit integer.
6736 assert(Bits % 64 == 0 &&
6737 "The number of bits in a vector must be divisible by 64 on x86!");
6738 int NumExtElements = Bits / 64;
6740 // Each iteration, try extending the elements half as much, but into twice as
6742 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6743 assert(NumElements % NumExtElements == 0 &&
6744 "The input vector size must be divisible by the extended size.");
6745 if (SDValue V = Lower(NumElements / NumExtElements))
6749 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6753 // Returns one of the source operands if the shuffle can be reduced to a
6754 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6755 auto CanZExtLowHalf = [&]() {
6756 for (int i = NumElements / 2; i != NumElements; ++i)
6759 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6761 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6766 if (SDValue V = CanZExtLowHalf()) {
6767 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6768 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6769 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6772 // No viable ext lowering found.
6776 /// \brief Try to get a scalar value for a specific element of a vector.
6778 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6779 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6780 SelectionDAG &DAG) {
6781 MVT VT = V.getSimpleValueType();
6782 MVT EltVT = VT.getVectorElementType();
6783 while (V.getOpcode() == ISD::BITCAST)
6784 V = V.getOperand(0);
6785 // If the bitcasts shift the element size, we can't extract an equivalent
6787 MVT NewVT = V.getSimpleValueType();
6788 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6791 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6792 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6793 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6798 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6800 /// This is particularly important because the set of instructions varies
6801 /// significantly based on whether the operand is a load or not.
6802 static bool isShuffleFoldableLoad(SDValue V) {
6803 while (V.getOpcode() == ISD::BITCAST)
6804 V = V.getOperand(0);
6806 return ISD::isNON_EXTLoad(V.getNode());
6809 /// \brief Try to lower insertion of a single element into a zero vector.
6811 /// This is a common pattern that we have especially efficient patterns to lower
6812 /// across all subtarget feature sets.
6813 static SDValue lowerVectorShuffleAsElementInsertion(
6814 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6815 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6816 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6818 MVT EltVT = VT.getVectorElementType();
6820 int V2Index = std::find_if(Mask.begin(), Mask.end(),
6821 [&Mask](int M) { return M >= (int)Mask.size(); }) -
6823 bool IsV1Zeroable = true;
6824 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6825 if (i != V2Index && !Zeroable[i]) {
6826 IsV1Zeroable = false;
6830 // Check for a single input from a SCALAR_TO_VECTOR node.
6831 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6832 // all the smarts here sunk into that routine. However, the current
6833 // lowering of BUILD_VECTOR makes that nearly impossible until the old
6834 // vector shuffle lowering is dead.
6835 if (SDValue V2S = getScalarValueForVectorElement(
6836 V2, Mask[V2Index] - Mask.size(), DAG)) {
6837 // We need to zext the scalar if it is smaller than an i32.
6838 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6839 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6840 // Using zext to expand a narrow element won't work for non-zero
6845 // Zero-extend directly to i32.
6847 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6849 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6850 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6851 EltVT == MVT::i16) {
6852 // Either not inserting from the low element of the input or the input
6853 // element size is too small to use VZEXT_MOVL to clear the high bits.
6857 if (!IsV1Zeroable) {
6858 // If V1 can't be treated as a zero vector we have fewer options to lower
6859 // this. We can't support integer vectors or non-zero targets cheaply, and
6860 // the V1 elements can't be permuted in any way.
6861 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6862 if (!VT.isFloatingPoint() || V2Index != 0)
6864 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6865 V1Mask[V2Index] = -1;
6866 if (!isNoopShuffleMask(V1Mask))
6868 // This is essentially a special case blend operation, but if we have
6869 // general purpose blend operations, they are always faster. Bail and let
6870 // the rest of the lowering handle these as blends.
6871 if (Subtarget->hasSSE41())
6874 // Otherwise, use MOVSD or MOVSS.
6875 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6876 "Only two types of floating point element types to handle!");
6877 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6881 // This lowering only works for the low element with floating point vectors.
6882 if (VT.isFloatingPoint() && V2Index != 0)
6885 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6887 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6890 // If we have 4 or fewer lanes we can cheaply shuffle the element into
6891 // the desired position. Otherwise it is more efficient to do a vector
6892 // shift left. We know that we can do a vector shift left because all
6893 // the inputs are zero.
6894 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6895 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6896 V2Shuffle[V2Index] = 0;
6897 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6899 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6901 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6903 V2Index * EltVT.getSizeInBits()/8,
6904 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6905 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6911 /// \brief Try to lower broadcast of a single element.
6913 /// For convenience, this code also bundles all of the subtarget feature set
6914 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6915 /// a convenient way to factor it out.
6916 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6918 const X86Subtarget *Subtarget,
6919 SelectionDAG &DAG) {
6920 if (!Subtarget->hasAVX())
6922 if (VT.isInteger() && !Subtarget->hasAVX2())
6925 // Check that the mask is a broadcast.
6926 int BroadcastIdx = -1;
6928 if (M >= 0 && BroadcastIdx == -1)
6930 else if (M >= 0 && M != BroadcastIdx)
6933 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6934 "a sorted mask where the broadcast "
6937 // Go up the chain of (vector) values to try and find a scalar load that
6938 // we can combine with the broadcast.
6940 switch (V.getOpcode()) {
6941 case ISD::CONCAT_VECTORS: {
6942 int OperandSize = Mask.size() / V.getNumOperands();
6943 V = V.getOperand(BroadcastIdx / OperandSize);
6944 BroadcastIdx %= OperandSize;
6948 case ISD::INSERT_SUBVECTOR: {
6949 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6950 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6954 int BeginIdx = (int)ConstantIdx->getZExtValue();
6956 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6957 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6958 BroadcastIdx -= BeginIdx;
6969 // Check if this is a broadcast of a scalar. We special case lowering
6970 // for scalars so that we can more effectively fold with loads.
6971 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6972 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6973 V = V.getOperand(BroadcastIdx);
6975 // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6977 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6979 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6980 // We can't broadcast from a vector register w/o AVX2, and we can only
6981 // broadcast from the zero-element of a vector register.
6985 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
6988 // Check for whether we can use INSERTPS to perform the shuffle. We only use
6989 // INSERTPS when the V1 elements are already in the correct locations
6990 // because otherwise we can just always use two SHUFPS instructions which
6991 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
6992 // perform INSERTPS if a single V1 element is out of place and all V2
6993 // elements are zeroable.
6994 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
6996 SelectionDAG &DAG) {
6997 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
6998 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6999 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7000 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7002 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7005 int V1DstIndex = -1;
7006 int V2DstIndex = -1;
7007 bool V1UsedInPlace = false;
7009 for (int i = 0; i < 4; ++i) {
7010 // Synthesize a zero mask from the zeroable elements (includes undefs).
7016 // Flag if we use any V1 inputs in place.
7018 V1UsedInPlace = true;
7022 // We can only insert a single non-zeroable element.
7023 if (V1DstIndex != -1 || V2DstIndex != -1)
7027 // V1 input out of place for insertion.
7030 // V2 input for insertion.
7035 // Don't bother if we have no (non-zeroable) element for insertion.
7036 if (V1DstIndex == -1 && V2DstIndex == -1)
7039 // Determine element insertion src/dst indices. The src index is from the
7040 // start of the inserted vector, not the start of the concatenated vector.
7041 unsigned V2SrcIndex = 0;
7042 if (V1DstIndex != -1) {
7043 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7044 // and don't use the original V2 at all.
7045 V2SrcIndex = Mask[V1DstIndex];
7046 V2DstIndex = V1DstIndex;
7049 V2SrcIndex = Mask[V2DstIndex] - 4;
7052 // If no V1 inputs are used in place, then the result is created only from
7053 // the zero mask and the V2 insertion - so remove V1 dependency.
7055 V1 = DAG.getUNDEF(MVT::v4f32);
7057 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7058 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7060 // Insert the V2 element into the desired position.
7062 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7063 DAG.getConstant(InsertPSMask, MVT::i8));
7066 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7067 /// UNPCK instruction.
7069 /// This specifically targets cases where we end up with alternating between
7070 /// the two inputs, and so can permute them into something that feeds a single
7071 /// UNPCK instruction. Note that this routine only targets integer vectors
7072 /// because for floating point vectors we have a generalized SHUFPS lowering
7073 /// strategy that handles everything that doesn't *exactly* match an unpack,
7074 /// making this clever lowering unnecessary.
7075 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7076 SDValue V2, ArrayRef<int> Mask,
7077 SelectionDAG &DAG) {
7078 assert(!VT.isFloatingPoint() &&
7079 "This routine only supports integer vectors.");
7080 assert(!isSingleInputShuffleMask(Mask) &&
7081 "This routine should only be used when blending two inputs.");
7082 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7084 int Size = Mask.size();
7086 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7087 return M >= 0 && M % Size < Size / 2;
7089 int NumHiInputs = std::count_if(
7090 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7092 bool UnpackLo = NumLoInputs >= NumHiInputs;
7094 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7095 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7096 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7098 for (int i = 0; i < Size; ++i) {
7102 // Each element of the unpack contains Scale elements from this mask.
7103 int UnpackIdx = i / Scale;
7105 // We only handle the case where V1 feeds the first slots of the unpack.
7106 // We rely on canonicalization to ensure this is the case.
7107 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7110 // Setup the mask for this input. The indexing is tricky as we have to
7111 // handle the unpack stride.
7112 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7113 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7117 // If we will have to shuffle both inputs to use the unpack, check whether
7118 // we can just unpack first and shuffle the result. If so, skip this unpack.
7119 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7120 !isNoopShuffleMask(V2Mask))
7123 // Shuffle the inputs into place.
7124 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7125 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7127 // Cast the inputs to the type we will use to unpack them.
7128 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7129 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7131 // Unpack the inputs and cast the result back to the desired type.
7132 return DAG.getNode(ISD::BITCAST, DL, VT,
7133 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7134 DL, UnpackVT, V1, V2));
7137 // We try each unpack from the largest to the smallest to try and find one
7138 // that fits this mask.
7139 int OrigNumElements = VT.getVectorNumElements();
7140 int OrigScalarSize = VT.getScalarSizeInBits();
7141 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7142 int Scale = ScalarSize / OrigScalarSize;
7143 int NumElements = OrigNumElements / Scale;
7144 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7145 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7149 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7151 if (NumLoInputs == 0 || NumHiInputs == 0) {
7152 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7153 "We have to have *some* inputs!");
7154 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7156 // FIXME: We could consider the total complexity of the permute of each
7157 // possible unpacking. Or at the least we should consider how many
7158 // half-crossings are created.
7159 // FIXME: We could consider commuting the unpacks.
7161 SmallVector<int, 32> PermMask;
7162 PermMask.assign(Size, -1);
7163 for (int i = 0; i < Size; ++i) {
7167 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7170 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7172 return DAG.getVectorShuffle(
7173 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7175 DAG.getUNDEF(VT), PermMask);
7181 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7183 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7184 /// support for floating point shuffles but not integer shuffles. These
7185 /// instructions will incur a domain crossing penalty on some chips though so
7186 /// it is better to avoid lowering through this for integer vectors where
7188 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7189 const X86Subtarget *Subtarget,
7190 SelectionDAG &DAG) {
7192 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7193 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7194 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7195 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7196 ArrayRef<int> Mask = SVOp->getMask();
7197 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7199 if (isSingleInputShuffleMask(Mask)) {
7200 // Use low duplicate instructions for masks that match their pattern.
7201 if (Subtarget->hasSSE3())
7202 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7203 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7205 // Straight shuffle of a single input vector. Simulate this by using the
7206 // single input as both of the "inputs" to this instruction..
7207 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7209 if (Subtarget->hasAVX()) {
7210 // If we have AVX, we can use VPERMILPS which will allow folding a load
7211 // into the shuffle.
7212 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7213 DAG.getConstant(SHUFPDMask, MVT::i8));
7216 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7217 DAG.getConstant(SHUFPDMask, MVT::i8));
7219 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7220 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7222 // If we have a single input, insert that into V1 if we can do so cheaply.
7223 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7224 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7225 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7227 // Try inverting the insertion since for v2 masks it is easy to do and we
7228 // can't reliably sort the mask one way or the other.
7229 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7230 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7231 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7232 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7236 // Try to use one of the special instruction patterns to handle two common
7237 // blend patterns if a zero-blend above didn't work.
7238 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7239 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7240 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7241 // We can either use a special instruction to load over the low double or
7242 // to move just the low double.
7244 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7246 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7248 if (Subtarget->hasSSE41())
7249 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7253 // Use dedicated unpack instructions for masks that match their pattern.
7254 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7255 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7256 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7257 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7259 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7260 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7261 DAG.getConstant(SHUFPDMask, MVT::i8));
7264 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7266 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7267 /// the integer unit to minimize domain crossing penalties. However, for blends
7268 /// it falls back to the floating point shuffle operation with appropriate bit
7270 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7271 const X86Subtarget *Subtarget,
7272 SelectionDAG &DAG) {
7274 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7275 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7276 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7277 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7278 ArrayRef<int> Mask = SVOp->getMask();
7279 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7281 if (isSingleInputShuffleMask(Mask)) {
7282 // Check for being able to broadcast a single element.
7283 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7284 Mask, Subtarget, DAG))
7287 // Straight shuffle of a single input vector. For everything from SSE2
7288 // onward this has a single fast instruction with no scary immediates.
7289 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7290 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7291 int WidenedMask[4] = {
7292 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7293 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7295 ISD::BITCAST, DL, MVT::v2i64,
7296 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7297 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7299 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7300 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7301 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7302 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7304 // If we have a blend of two PACKUS operations an the blend aligns with the
7305 // low and half halves, we can just merge the PACKUS operations. This is
7306 // particularly important as it lets us merge shuffles that this routine itself
7308 auto GetPackNode = [](SDValue V) {
7309 while (V.getOpcode() == ISD::BITCAST)
7310 V = V.getOperand(0);
7312 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7314 if (SDValue V1Pack = GetPackNode(V1))
7315 if (SDValue V2Pack = GetPackNode(V2))
7316 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7317 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7318 Mask[0] == 0 ? V1Pack.getOperand(0)
7319 : V1Pack.getOperand(1),
7320 Mask[1] == 2 ? V2Pack.getOperand(0)
7321 : V2Pack.getOperand(1)));
7323 // Try to use shift instructions.
7325 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7328 // When loading a scalar and then shuffling it into a vector we can often do
7329 // the insertion cheaply.
7330 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7331 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7333 // Try inverting the insertion since for v2 masks it is easy to do and we
7334 // can't reliably sort the mask one way or the other.
7335 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7336 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7337 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7340 // We have different paths for blend lowering, but they all must use the
7341 // *exact* same predicate.
7342 bool IsBlendSupported = Subtarget->hasSSE41();
7343 if (IsBlendSupported)
7344 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7348 // Use dedicated unpack instructions for masks that match their pattern.
7349 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7350 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7351 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7352 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7354 // Try to use byte rotation instructions.
7355 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7356 if (Subtarget->hasSSSE3())
7357 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7358 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7361 // If we have direct support for blends, we should lower by decomposing into
7362 // a permute. That will be faster than the domain cross.
7363 if (IsBlendSupported)
7364 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7367 // We implement this with SHUFPD which is pretty lame because it will likely
7368 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7369 // However, all the alternatives are still more cycles and newer chips don't
7370 // have this problem. It would be really nice if x86 had better shuffles here.
7371 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7372 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7373 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7374 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7377 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7379 /// This is used to disable more specialized lowerings when the shufps lowering
7380 /// will happen to be efficient.
7381 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7382 // This routine only handles 128-bit shufps.
7383 assert(Mask.size() == 4 && "Unsupported mask size!");
7385 // To lower with a single SHUFPS we need to have the low half and high half
7386 // each requiring a single input.
7387 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7389 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7395 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7397 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7398 /// It makes no assumptions about whether this is the *best* lowering, it simply
7400 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7401 ArrayRef<int> Mask, SDValue V1,
7402 SDValue V2, SelectionDAG &DAG) {
7403 SDValue LowV = V1, HighV = V2;
7404 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7407 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7409 if (NumV2Elements == 1) {
7411 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7414 // Compute the index adjacent to V2Index and in the same half by toggling
7416 int V2AdjIndex = V2Index ^ 1;
7418 if (Mask[V2AdjIndex] == -1) {
7419 // Handles all the cases where we have a single V2 element and an undef.
7420 // This will only ever happen in the high lanes because we commute the
7421 // vector otherwise.
7423 std::swap(LowV, HighV);
7424 NewMask[V2Index] -= 4;
7426 // Handle the case where the V2 element ends up adjacent to a V1 element.
7427 // To make this work, blend them together as the first step.
7428 int V1Index = V2AdjIndex;
7429 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7430 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7431 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7433 // Now proceed to reconstruct the final blend as we have the necessary
7434 // high or low half formed.
7441 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7442 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7444 } else if (NumV2Elements == 2) {
7445 if (Mask[0] < 4 && Mask[1] < 4) {
7446 // Handle the easy case where we have V1 in the low lanes and V2 in the
7450 } else if (Mask[2] < 4 && Mask[3] < 4) {
7451 // We also handle the reversed case because this utility may get called
7452 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7453 // arrange things in the right direction.
7459 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7460 // trying to place elements directly, just blend them and set up the final
7461 // shuffle to place them.
7463 // The first two blend mask elements are for V1, the second two are for
7465 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7466 Mask[2] < 4 ? Mask[2] : Mask[3],
7467 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7468 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7469 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7470 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7472 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7475 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7476 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7477 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7478 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7481 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7482 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7485 /// \brief Lower 4-lane 32-bit floating point shuffles.
7487 /// Uses instructions exclusively from the floating point unit to minimize
7488 /// domain crossing penalties, as these are sufficient to implement all v4f32
7490 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7491 const X86Subtarget *Subtarget,
7492 SelectionDAG &DAG) {
7494 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7495 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7496 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7497 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7498 ArrayRef<int> Mask = SVOp->getMask();
7499 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7502 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7504 if (NumV2Elements == 0) {
7505 // Check for being able to broadcast a single element.
7506 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7507 Mask, Subtarget, DAG))
7510 // Use even/odd duplicate instructions for masks that match their pattern.
7511 if (Subtarget->hasSSE3()) {
7512 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7513 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7514 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7515 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7518 if (Subtarget->hasAVX()) {
7519 // If we have AVX, we can use VPERMILPS which will allow folding a load
7520 // into the shuffle.
7521 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7522 getV4X86ShuffleImm8ForMask(Mask, DAG));
7525 // Otherwise, use a straight shuffle of a single input vector. We pass the
7526 // input vector to both operands to simulate this with a SHUFPS.
7527 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7528 getV4X86ShuffleImm8ForMask(Mask, DAG));
7531 // There are special ways we can lower some single-element blends. However, we
7532 // have custom ways we can lower more complex single-element blends below that
7533 // we defer to if both this and BLENDPS fail to match, so restrict this to
7534 // when the V2 input is targeting element 0 of the mask -- that is the fast
7536 if (NumV2Elements == 1 && Mask[0] >= 4)
7537 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7538 Mask, Subtarget, DAG))
7541 if (Subtarget->hasSSE41()) {
7542 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7546 // Use INSERTPS if we can complete the shuffle efficiently.
7547 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7550 if (!isSingleSHUFPSMask(Mask))
7551 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7552 DL, MVT::v4f32, V1, V2, Mask, DAG))
7556 // Use dedicated unpack instructions for masks that match their pattern.
7557 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7558 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7559 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7560 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7561 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7562 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7563 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7564 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7566 // Otherwise fall back to a SHUFPS lowering strategy.
7567 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7570 /// \brief Lower 4-lane i32 vector shuffles.
7572 /// We try to handle these with integer-domain shuffles where we can, but for
7573 /// blends we use the floating point domain blend instructions.
7574 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7575 const X86Subtarget *Subtarget,
7576 SelectionDAG &DAG) {
7578 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7579 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7580 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7581 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7582 ArrayRef<int> Mask = SVOp->getMask();
7583 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7585 // Whenever we can lower this as a zext, that instruction is strictly faster
7586 // than any alternative. It also allows us to fold memory operands into the
7587 // shuffle in many cases.
7588 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7589 Mask, Subtarget, DAG))
7593 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7595 if (NumV2Elements == 0) {
7596 // Check for being able to broadcast a single element.
7597 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7598 Mask, Subtarget, DAG))
7601 // Straight shuffle of a single input vector. For everything from SSE2
7602 // onward this has a single fast instruction with no scary immediates.
7603 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7604 // but we aren't actually going to use the UNPCK instruction because doing
7605 // so prevents folding a load into this instruction or making a copy.
7606 const int UnpackLoMask[] = {0, 0, 1, 1};
7607 const int UnpackHiMask[] = {2, 2, 3, 3};
7608 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7609 Mask = UnpackLoMask;
7610 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7611 Mask = UnpackHiMask;
7613 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7614 getV4X86ShuffleImm8ForMask(Mask, DAG));
7617 // Try to use shift instructions.
7619 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7622 // There are special ways we can lower some single-element blends.
7623 if (NumV2Elements == 1)
7624 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7625 Mask, Subtarget, DAG))
7628 // We have different paths for blend lowering, but they all must use the
7629 // *exact* same predicate.
7630 bool IsBlendSupported = Subtarget->hasSSE41();
7631 if (IsBlendSupported)
7632 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7636 if (SDValue Masked =
7637 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7640 // Use dedicated unpack instructions for masks that match their pattern.
7641 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7642 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7643 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7644 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7645 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7646 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7647 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7648 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7650 // Try to use byte rotation instructions.
7651 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7652 if (Subtarget->hasSSSE3())
7653 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7654 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7657 // If we have direct support for blends, we should lower by decomposing into
7658 // a permute. That will be faster than the domain cross.
7659 if (IsBlendSupported)
7660 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7663 // Try to lower by permuting the inputs into an unpack instruction.
7664 if (SDValue Unpack =
7665 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7668 // We implement this with SHUFPS because it can blend from two vectors.
7669 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7670 // up the inputs, bypassing domain shift penalties that we would encur if we
7671 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7673 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7674 DAG.getVectorShuffle(
7676 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7677 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7680 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7681 /// shuffle lowering, and the most complex part.
7683 /// The lowering strategy is to try to form pairs of input lanes which are
7684 /// targeted at the same half of the final vector, and then use a dword shuffle
7685 /// to place them onto the right half, and finally unpack the paired lanes into
7686 /// their final position.
7688 /// The exact breakdown of how to form these dword pairs and align them on the
7689 /// correct sides is really tricky. See the comments within the function for
7690 /// more of the details.
7692 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7693 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7694 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7695 /// vector, form the analogous 128-bit 8-element Mask.
7696 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7697 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7698 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7699 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7700 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7702 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7703 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7704 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7706 SmallVector<int, 4> LoInputs;
7707 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7708 [](int M) { return M >= 0; });
7709 std::sort(LoInputs.begin(), LoInputs.end());
7710 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7711 SmallVector<int, 4> HiInputs;
7712 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7713 [](int M) { return M >= 0; });
7714 std::sort(HiInputs.begin(), HiInputs.end());
7715 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7717 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7718 int NumHToL = LoInputs.size() - NumLToL;
7720 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7721 int NumHToH = HiInputs.size() - NumLToH;
7722 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7723 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7724 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7725 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7727 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7728 // such inputs we can swap two of the dwords across the half mark and end up
7729 // with <=2 inputs to each half in each half. Once there, we can fall through
7730 // to the generic code below. For example:
7732 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7733 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7735 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7736 // and an existing 2-into-2 on the other half. In this case we may have to
7737 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7738 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7739 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7740 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7741 // half than the one we target for fixing) will be fixed when we re-enter this
7742 // path. We will also combine away any sequence of PSHUFD instructions that
7743 // result into a single instruction. Here is an example of the tricky case:
7745 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7746 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7748 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7750 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7751 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7753 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7754 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7756 // The result is fine to be handled by the generic logic.
7757 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7758 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7759 int AOffset, int BOffset) {
7760 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7761 "Must call this with A having 3 or 1 inputs from the A half.");
7762 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7763 "Must call this with B having 1 or 3 inputs from the B half.");
7764 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7765 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7767 // Compute the index of dword with only one word among the three inputs in
7768 // a half by taking the sum of the half with three inputs and subtracting
7769 // the sum of the actual three inputs. The difference is the remaining
7772 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7773 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7774 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7775 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7776 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7777 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7778 int TripleNonInputIdx =
7779 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7780 TripleDWord = TripleNonInputIdx / 2;
7782 // We use xor with one to compute the adjacent DWord to whichever one the
7784 OneInputDWord = (OneInput / 2) ^ 1;
7786 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7787 // and BToA inputs. If there is also such a problem with the BToB and AToB
7788 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7789 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7790 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7791 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7792 // Compute how many inputs will be flipped by swapping these DWords. We
7794 // to balance this to ensure we don't form a 3-1 shuffle in the other
7796 int NumFlippedAToBInputs =
7797 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7798 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7799 int NumFlippedBToBInputs =
7800 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7801 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7802 if ((NumFlippedAToBInputs == 1 &&
7803 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7804 (NumFlippedBToBInputs == 1 &&
7805 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7806 // We choose whether to fix the A half or B half based on whether that
7807 // half has zero flipped inputs. At zero, we may not be able to fix it
7808 // with that half. We also bias towards fixing the B half because that
7809 // will more commonly be the high half, and we have to bias one way.
7810 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7811 ArrayRef<int> Inputs) {
7812 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7813 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7814 PinnedIdx ^ 1) != Inputs.end();
7815 // Determine whether the free index is in the flipped dword or the
7816 // unflipped dword based on where the pinned index is. We use this bit
7817 // in an xor to conditionally select the adjacent dword.
7818 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7819 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7820 FixFreeIdx) != Inputs.end();
7821 if (IsFixIdxInput == IsFixFreeIdxInput)
7823 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7824 FixFreeIdx) != Inputs.end();
7825 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7826 "We need to be changing the number of flipped inputs!");
7827 int PSHUFHalfMask[] = {0, 1, 2, 3};
7828 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7829 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7831 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7834 if (M != -1 && M == FixIdx)
7836 else if (M != -1 && M == FixFreeIdx)
7839 if (NumFlippedBToBInputs != 0) {
7841 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7842 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7844 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7846 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7847 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7852 int PSHUFDMask[] = {0, 1, 2, 3};
7853 PSHUFDMask[ADWord] = BDWord;
7854 PSHUFDMask[BDWord] = ADWord;
7855 V = DAG.getNode(ISD::BITCAST, DL, VT,
7856 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7857 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7858 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7860 // Adjust the mask to match the new locations of A and B.
7862 if (M != -1 && M/2 == ADWord)
7863 M = 2 * BDWord + M % 2;
7864 else if (M != -1 && M/2 == BDWord)
7865 M = 2 * ADWord + M % 2;
7867 // Recurse back into this routine to re-compute state now that this isn't
7868 // a 3 and 1 problem.
7869 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7872 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7873 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7874 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7875 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7877 // At this point there are at most two inputs to the low and high halves from
7878 // each half. That means the inputs can always be grouped into dwords and
7879 // those dwords can then be moved to the correct half with a dword shuffle.
7880 // We use at most one low and one high word shuffle to collect these paired
7881 // inputs into dwords, and finally a dword shuffle to place them.
7882 int PSHUFLMask[4] = {-1, -1, -1, -1};
7883 int PSHUFHMask[4] = {-1, -1, -1, -1};
7884 int PSHUFDMask[4] = {-1, -1, -1, -1};
7886 // First fix the masks for all the inputs that are staying in their
7887 // original halves. This will then dictate the targets of the cross-half
7889 auto fixInPlaceInputs =
7890 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7891 MutableArrayRef<int> SourceHalfMask,
7892 MutableArrayRef<int> HalfMask, int HalfOffset) {
7893 if (InPlaceInputs.empty())
7895 if (InPlaceInputs.size() == 1) {
7896 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7897 InPlaceInputs[0] - HalfOffset;
7898 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7901 if (IncomingInputs.empty()) {
7902 // Just fix all of the in place inputs.
7903 for (int Input : InPlaceInputs) {
7904 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7905 PSHUFDMask[Input / 2] = Input / 2;
7910 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7911 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7912 InPlaceInputs[0] - HalfOffset;
7913 // Put the second input next to the first so that they are packed into
7914 // a dword. We find the adjacent index by toggling the low bit.
7915 int AdjIndex = InPlaceInputs[0] ^ 1;
7916 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7917 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7918 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7920 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7921 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7923 // Now gather the cross-half inputs and place them into a free dword of
7924 // their target half.
7925 // FIXME: This operation could almost certainly be simplified dramatically to
7926 // look more like the 3-1 fixing operation.
7927 auto moveInputsToRightHalf = [&PSHUFDMask](
7928 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7929 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7930 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7932 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7933 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7935 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7937 int LowWord = Word & ~1;
7938 int HighWord = Word | 1;
7939 return isWordClobbered(SourceHalfMask, LowWord) ||
7940 isWordClobbered(SourceHalfMask, HighWord);
7943 if (IncomingInputs.empty())
7946 if (ExistingInputs.empty()) {
7947 // Map any dwords with inputs from them into the right half.
7948 for (int Input : IncomingInputs) {
7949 // If the source half mask maps over the inputs, turn those into
7950 // swaps and use the swapped lane.
7951 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7952 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7953 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7954 Input - SourceOffset;
7955 // We have to swap the uses in our half mask in one sweep.
7956 for (int &M : HalfMask)
7957 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7959 else if (M == Input)
7960 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7962 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7963 Input - SourceOffset &&
7964 "Previous placement doesn't match!");
7966 // Note that this correctly re-maps both when we do a swap and when
7967 // we observe the other side of the swap above. We rely on that to
7968 // avoid swapping the members of the input list directly.
7969 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7972 // Map the input's dword into the correct half.
7973 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7974 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7976 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7978 "Previous placement doesn't match!");
7981 // And just directly shift any other-half mask elements to be same-half
7982 // as we will have mirrored the dword containing the element into the
7983 // same position within that half.
7984 for (int &M : HalfMask)
7985 if (M >= SourceOffset && M < SourceOffset + 4) {
7986 M = M - SourceOffset + DestOffset;
7987 assert(M >= 0 && "This should never wrap below zero!");
7992 // Ensure we have the input in a viable dword of its current half. This
7993 // is particularly tricky because the original position may be clobbered
7994 // by inputs being moved and *staying* in that half.
7995 if (IncomingInputs.size() == 1) {
7996 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7997 int InputFixed = std::find(std::begin(SourceHalfMask),
7998 std::end(SourceHalfMask), -1) -
7999 std::begin(SourceHalfMask) + SourceOffset;
8000 SourceHalfMask[InputFixed - SourceOffset] =
8001 IncomingInputs[0] - SourceOffset;
8002 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8004 IncomingInputs[0] = InputFixed;
8006 } else if (IncomingInputs.size() == 2) {
8007 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8008 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8009 // We have two non-adjacent or clobbered inputs we need to extract from
8010 // the source half. To do this, we need to map them into some adjacent
8011 // dword slot in the source mask.
8012 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8013 IncomingInputs[1] - SourceOffset};
8015 // If there is a free slot in the source half mask adjacent to one of
8016 // the inputs, place the other input in it. We use (Index XOR 1) to
8017 // compute an adjacent index.
8018 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8019 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8020 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8021 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8022 InputsFixed[1] = InputsFixed[0] ^ 1;
8023 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8024 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8025 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8026 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8027 InputsFixed[0] = InputsFixed[1] ^ 1;
8028 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8029 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8030 // The two inputs are in the same DWord but it is clobbered and the
8031 // adjacent DWord isn't used at all. Move both inputs to the free
8033 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8034 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8035 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8036 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8038 // The only way we hit this point is if there is no clobbering
8039 // (because there are no off-half inputs to this half) and there is no
8040 // free slot adjacent to one of the inputs. In this case, we have to
8041 // swap an input with a non-input.
8042 for (int i = 0; i < 4; ++i)
8043 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8044 "We can't handle any clobbers here!");
8045 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8046 "Cannot have adjacent inputs here!");
8048 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8049 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8051 // We also have to update the final source mask in this case because
8052 // it may need to undo the above swap.
8053 for (int &M : FinalSourceHalfMask)
8054 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8055 M = InputsFixed[1] + SourceOffset;
8056 else if (M == InputsFixed[1] + SourceOffset)
8057 M = (InputsFixed[0] ^ 1) + SourceOffset;
8059 InputsFixed[1] = InputsFixed[0] ^ 1;
8062 // Point everything at the fixed inputs.
8063 for (int &M : HalfMask)
8064 if (M == IncomingInputs[0])
8065 M = InputsFixed[0] + SourceOffset;
8066 else if (M == IncomingInputs[1])
8067 M = InputsFixed[1] + SourceOffset;
8069 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8070 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8073 llvm_unreachable("Unhandled input size!");
8076 // Now hoist the DWord down to the right half.
8077 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8078 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8079 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8080 for (int &M : HalfMask)
8081 for (int Input : IncomingInputs)
8083 M = FreeDWord * 2 + Input % 2;
8085 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8086 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8087 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8088 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8090 // Now enact all the shuffles we've computed to move the inputs into their
8092 if (!isNoopShuffleMask(PSHUFLMask))
8093 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8094 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8095 if (!isNoopShuffleMask(PSHUFHMask))
8096 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8097 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8098 if (!isNoopShuffleMask(PSHUFDMask))
8099 V = DAG.getNode(ISD::BITCAST, DL, VT,
8100 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8101 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8102 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8104 // At this point, each half should contain all its inputs, and we can then
8105 // just shuffle them into their final position.
8106 assert(std::count_if(LoMask.begin(), LoMask.end(),
8107 [](int M) { return M >= 4; }) == 0 &&
8108 "Failed to lift all the high half inputs to the low mask!");
8109 assert(std::count_if(HiMask.begin(), HiMask.end(),
8110 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8111 "Failed to lift all the low half inputs to the high mask!");
8113 // Do a half shuffle for the low mask.
8114 if (!isNoopShuffleMask(LoMask))
8115 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8116 getV4X86ShuffleImm8ForMask(LoMask, DAG));
8118 // Do a half shuffle with the high mask after shifting its values down.
8119 for (int &M : HiMask)
8122 if (!isNoopShuffleMask(HiMask))
8123 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8124 getV4X86ShuffleImm8ForMask(HiMask, DAG));
8129 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8130 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8131 SDValue V2, ArrayRef<int> Mask,
8132 SelectionDAG &DAG, bool &V1InUse,
8134 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8140 int Size = Mask.size();
8141 int Scale = 16 / Size;
8142 for (int i = 0; i < 16; ++i) {
8143 if (Mask[i / Scale] == -1) {
8144 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8146 const int ZeroMask = 0x80;
8147 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8149 int V2Idx = Mask[i / Scale] < Size
8151 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8152 if (Zeroable[i / Scale])
8153 V1Idx = V2Idx = ZeroMask;
8154 V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8155 V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8156 V1InUse |= (ZeroMask != V1Idx);
8157 V2InUse |= (ZeroMask != V2Idx);
8162 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8163 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8164 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8166 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8167 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8168 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8170 // If we need shuffled inputs from both, blend the two.
8172 if (V1InUse && V2InUse)
8173 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8175 V = V1InUse ? V1 : V2;
8177 // Cast the result back to the correct type.
8178 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8181 /// \brief Generic lowering of 8-lane i16 shuffles.
8183 /// This handles both single-input shuffles and combined shuffle/blends with
8184 /// two inputs. The single input shuffles are immediately delegated to
8185 /// a dedicated lowering routine.
8187 /// The blends are lowered in one of three fundamental ways. If there are few
8188 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8189 /// of the input is significantly cheaper when lowered as an interleaving of
8190 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8191 /// halves of the inputs separately (making them have relatively few inputs)
8192 /// and then concatenate them.
8193 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8194 const X86Subtarget *Subtarget,
8195 SelectionDAG &DAG) {
8197 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8198 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8199 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8200 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8201 ArrayRef<int> OrigMask = SVOp->getMask();
8202 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8203 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8204 MutableArrayRef<int> Mask(MaskStorage);
8206 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8208 // Whenever we can lower this as a zext, that instruction is strictly faster
8209 // than any alternative.
8210 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8211 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8214 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8216 auto isV2 = [](int M) { return M >= 8; };
8218 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8220 if (NumV2Inputs == 0) {
8221 // Check for being able to broadcast a single element.
8222 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8223 Mask, Subtarget, DAG))
8226 // Try to use shift instructions.
8228 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8231 // Use dedicated unpack instructions for masks that match their pattern.
8232 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8233 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8234 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8235 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8237 // Try to use byte rotation instructions.
8238 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8239 Mask, Subtarget, DAG))
8242 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8246 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8247 "All single-input shuffles should be canonicalized to be V1-input "
8250 // Try to use shift instructions.
8252 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8255 // There are special ways we can lower some single-element blends.
8256 if (NumV2Inputs == 1)
8257 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8258 Mask, Subtarget, DAG))
8261 // We have different paths for blend lowering, but they all must use the
8262 // *exact* same predicate.
8263 bool IsBlendSupported = Subtarget->hasSSE41();
8264 if (IsBlendSupported)
8265 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8269 if (SDValue Masked =
8270 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8273 // Use dedicated unpack instructions for masks that match their pattern.
8274 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8275 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8276 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8277 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8279 // Try to use byte rotation instructions.
8280 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8281 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8284 if (SDValue BitBlend =
8285 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8288 if (SDValue Unpack =
8289 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8292 // If we can't directly blend but can use PSHUFB, that will be better as it
8293 // can both shuffle and set up the inefficient blend.
8294 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8295 bool V1InUse, V2InUse;
8296 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8300 // We can always bit-blend if we have to so the fallback strategy is to
8301 // decompose into single-input permutes and blends.
8302 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8306 /// \brief Check whether a compaction lowering can be done by dropping even
8307 /// elements and compute how many times even elements must be dropped.
8309 /// This handles shuffles which take every Nth element where N is a power of
8310 /// two. Example shuffle masks:
8312 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8313 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8314 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8315 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8316 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8317 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8319 /// Any of these lanes can of course be undef.
8321 /// This routine only supports N <= 3.
8322 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8325 /// \returns N above, or the number of times even elements must be dropped if
8326 /// there is such a number. Otherwise returns zero.
8327 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8328 // Figure out whether we're looping over two inputs or just one.
8329 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8331 // The modulus for the shuffle vector entries is based on whether this is
8332 // a single input or not.
8333 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8334 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8335 "We should only be called with masks with a power-of-2 size!");
8337 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8339 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8340 // and 2^3 simultaneously. This is because we may have ambiguity with
8341 // partially undef inputs.
8342 bool ViableForN[3] = {true, true, true};
8344 for (int i = 0, e = Mask.size(); i < e; ++i) {
8345 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8350 bool IsAnyViable = false;
8351 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8352 if (ViableForN[j]) {
8355 // The shuffle mask must be equal to (i * 2^N) % M.
8356 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8359 ViableForN[j] = false;
8361 // Early exit if we exhaust the possible powers of two.
8366 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8370 // Return 0 as there is no viable power of two.
8374 /// \brief Generic lowering of v16i8 shuffles.
8376 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8377 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8378 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8379 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8381 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8382 const X86Subtarget *Subtarget,
8383 SelectionDAG &DAG) {
8385 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8386 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8387 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8388 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8389 ArrayRef<int> Mask = SVOp->getMask();
8390 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8392 // Try to use shift instructions.
8394 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8397 // Try to use byte rotation instructions.
8398 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8399 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8402 // Try to use a zext lowering.
8403 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8404 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8408 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8410 // For single-input shuffles, there are some nicer lowering tricks we can use.
8411 if (NumV2Elements == 0) {
8412 // Check for being able to broadcast a single element.
8413 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8414 Mask, Subtarget, DAG))
8417 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8418 // Notably, this handles splat and partial-splat shuffles more efficiently.
8419 // However, it only makes sense if the pre-duplication shuffle simplifies
8420 // things significantly. Currently, this means we need to be able to
8421 // express the pre-duplication shuffle as an i16 shuffle.
8423 // FIXME: We should check for other patterns which can be widened into an
8424 // i16 shuffle as well.
8425 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8426 for (int i = 0; i < 16; i += 2)
8427 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8432 auto tryToWidenViaDuplication = [&]() -> SDValue {
8433 if (!canWidenViaDuplication(Mask))
8435 SmallVector<int, 4> LoInputs;
8436 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8437 [](int M) { return M >= 0 && M < 8; });
8438 std::sort(LoInputs.begin(), LoInputs.end());
8439 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8441 SmallVector<int, 4> HiInputs;
8442 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8443 [](int M) { return M >= 8; });
8444 std::sort(HiInputs.begin(), HiInputs.end());
8445 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8448 bool TargetLo = LoInputs.size() >= HiInputs.size();
8449 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8450 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8452 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8453 SmallDenseMap<int, int, 8> LaneMap;
8454 for (int I : InPlaceInputs) {
8455 PreDupI16Shuffle[I/2] = I/2;
8458 int j = TargetLo ? 0 : 4, je = j + 4;
8459 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8460 // Check if j is already a shuffle of this input. This happens when
8461 // there are two adjacent bytes after we move the low one.
8462 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8463 // If we haven't yet mapped the input, search for a slot into which
8465 while (j < je && PreDupI16Shuffle[j] != -1)
8469 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8472 // Map this input with the i16 shuffle.
8473 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8476 // Update the lane map based on the mapping we ended up with.
8477 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8480 ISD::BITCAST, DL, MVT::v16i8,
8481 DAG.getVectorShuffle(MVT::v8i16, DL,
8482 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8483 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8485 // Unpack the bytes to form the i16s that will be shuffled into place.
8486 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8487 MVT::v16i8, V1, V1);
8489 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8490 for (int i = 0; i < 16; ++i)
8491 if (Mask[i] != -1) {
8492 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8493 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8494 if (PostDupI16Shuffle[i / 2] == -1)
8495 PostDupI16Shuffle[i / 2] = MappedMask;
8497 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8498 "Conflicting entrties in the original shuffle!");
8501 ISD::BITCAST, DL, MVT::v16i8,
8502 DAG.getVectorShuffle(MVT::v8i16, DL,
8503 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8504 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8506 if (SDValue V = tryToWidenViaDuplication())
8510 // Use dedicated unpack instructions for masks that match their pattern.
8511 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8512 0, 16, 1, 17, 2, 18, 3, 19,
8514 4, 20, 5, 21, 6, 22, 7, 23}))
8515 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8516 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8517 8, 24, 9, 25, 10, 26, 11, 27,
8519 12, 28, 13, 29, 14, 30, 15, 31}))
8520 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8522 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8523 // with PSHUFB. It is important to do this before we attempt to generate any
8524 // blends but after all of the single-input lowerings. If the single input
8525 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8526 // want to preserve that and we can DAG combine any longer sequences into
8527 // a PSHUFB in the end. But once we start blending from multiple inputs,
8528 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8529 // and there are *very* few patterns that would actually be faster than the
8530 // PSHUFB approach because of its ability to zero lanes.
8532 // FIXME: The only exceptions to the above are blends which are exact
8533 // interleavings with direct instructions supporting them. We currently don't
8534 // handle those well here.
8535 if (Subtarget->hasSSSE3()) {
8536 bool V1InUse = false;
8537 bool V2InUse = false;
8539 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8540 DAG, V1InUse, V2InUse);
8542 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8543 // do so. This avoids using them to handle blends-with-zero which is
8544 // important as a single pshufb is significantly faster for that.
8545 if (V1InUse && V2InUse) {
8546 if (Subtarget->hasSSE41())
8547 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8548 Mask, Subtarget, DAG))
8551 // We can use an unpack to do the blending rather than an or in some
8552 // cases. Even though the or may be (very minorly) more efficient, we
8553 // preference this lowering because there are common cases where part of
8554 // the complexity of the shuffles goes away when we do the final blend as
8556 // FIXME: It might be worth trying to detect if the unpack-feeding
8557 // shuffles will both be pshufb, in which case we shouldn't bother with
8559 if (SDValue Unpack =
8560 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8567 // There are special ways we can lower some single-element blends.
8568 if (NumV2Elements == 1)
8569 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8570 Mask, Subtarget, DAG))
8573 if (SDValue BitBlend =
8574 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8577 // Check whether a compaction lowering can be done. This handles shuffles
8578 // which take every Nth element for some even N. See the helper function for
8581 // We special case these as they can be particularly efficiently handled with
8582 // the PACKUSB instruction on x86 and they show up in common patterns of
8583 // rearranging bytes to truncate wide elements.
8584 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8585 // NumEvenDrops is the power of two stride of the elements. Another way of
8586 // thinking about it is that we need to drop the even elements this many
8587 // times to get the original input.
8588 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8590 // First we need to zero all the dropped bytes.
8591 assert(NumEvenDrops <= 3 &&
8592 "No support for dropping even elements more than 3 times.");
8593 // We use the mask type to pick which bytes are preserved based on how many
8594 // elements are dropped.
8595 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8596 SDValue ByteClearMask =
8597 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8598 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8599 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8601 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8603 // Now pack things back together.
8604 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8605 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8606 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8607 for (int i = 1; i < NumEvenDrops; ++i) {
8608 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8609 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8615 // Handle multi-input cases by blending single-input shuffles.
8616 if (NumV2Elements > 0)
8617 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8620 // The fallback path for single-input shuffles widens this into two v8i16
8621 // vectors with unpacks, shuffles those, and then pulls them back together
8625 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8626 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8627 for (int i = 0; i < 16; ++i)
8629 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8631 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8633 SDValue VLoHalf, VHiHalf;
8634 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8635 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8637 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8638 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8639 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8640 [](int M) { return M >= 0 && M % 2 == 1; })) {
8641 // Use a mask to drop the high bytes.
8642 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8643 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8644 DAG.getConstant(0x00FF, MVT::v8i16));
8646 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8647 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8649 // Squash the masks to point directly into VLoHalf.
8650 for (int &M : LoBlendMask)
8653 for (int &M : HiBlendMask)
8657 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8658 // VHiHalf so that we can blend them as i16s.
8659 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8660 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8661 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8662 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8665 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8666 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8668 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8671 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8673 /// This routine breaks down the specific type of 128-bit shuffle and
8674 /// dispatches to the lowering routines accordingly.
8675 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8676 MVT VT, const X86Subtarget *Subtarget,
8677 SelectionDAG &DAG) {
8678 switch (VT.SimpleTy) {
8680 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8682 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8684 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8686 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8688 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8690 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8693 llvm_unreachable("Unimplemented!");
8697 /// \brief Helper function to test whether a shuffle mask could be
8698 /// simplified by widening the elements being shuffled.
8700 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8701 /// leaves it in an unspecified state.
8703 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8704 /// shuffle masks. The latter have the special property of a '-2' representing
8705 /// a zero-ed lane of a vector.
8706 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8707 SmallVectorImpl<int> &WidenedMask) {
8708 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8709 // If both elements are undef, its trivial.
8710 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8711 WidenedMask.push_back(SM_SentinelUndef);
8715 // Check for an undef mask and a mask value properly aligned to fit with
8716 // a pair of values. If we find such a case, use the non-undef mask's value.
8717 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8718 WidenedMask.push_back(Mask[i + 1] / 2);
8721 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8722 WidenedMask.push_back(Mask[i] / 2);
8726 // When zeroing, we need to spread the zeroing across both lanes to widen.
8727 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8728 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8729 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8730 WidenedMask.push_back(SM_SentinelZero);
8736 // Finally check if the two mask values are adjacent and aligned with
8738 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8739 WidenedMask.push_back(Mask[i] / 2);
8743 // Otherwise we can't safely widen the elements used in this shuffle.
8746 assert(WidenedMask.size() == Mask.size() / 2 &&
8747 "Incorrect size of mask after widening the elements!");
8752 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8754 /// This routine just extracts two subvectors, shuffles them independently, and
8755 /// then concatenates them back together. This should work effectively with all
8756 /// AVX vector shuffle types.
8757 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8758 SDValue V2, ArrayRef<int> Mask,
8759 SelectionDAG &DAG) {
8760 assert(VT.getSizeInBits() >= 256 &&
8761 "Only for 256-bit or wider vector shuffles!");
8762 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8763 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8765 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8766 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8768 int NumElements = VT.getVectorNumElements();
8769 int SplitNumElements = NumElements / 2;
8770 MVT ScalarVT = VT.getScalarType();
8771 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8773 // Rather than splitting build-vectors, just build two narrower build
8774 // vectors. This helps shuffling with splats and zeros.
8775 auto SplitVector = [&](SDValue V) {
8776 while (V.getOpcode() == ISD::BITCAST)
8777 V = V->getOperand(0);
8779 MVT OrigVT = V.getSimpleValueType();
8780 int OrigNumElements = OrigVT.getVectorNumElements();
8781 int OrigSplitNumElements = OrigNumElements / 2;
8782 MVT OrigScalarVT = OrigVT.getScalarType();
8783 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8787 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8789 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8790 DAG.getIntPtrConstant(0));
8791 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8792 DAG.getIntPtrConstant(OrigSplitNumElements));
8795 SmallVector<SDValue, 16> LoOps, HiOps;
8796 for (int i = 0; i < OrigSplitNumElements; ++i) {
8797 LoOps.push_back(BV->getOperand(i));
8798 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8800 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8801 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8803 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8804 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8807 SDValue LoV1, HiV1, LoV2, HiV2;
8808 std::tie(LoV1, HiV1) = SplitVector(V1);
8809 std::tie(LoV2, HiV2) = SplitVector(V2);
8811 // Now create two 4-way blends of these half-width vectors.
8812 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8813 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8814 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8815 for (int i = 0; i < SplitNumElements; ++i) {
8816 int M = HalfMask[i];
8817 if (M >= NumElements) {
8818 if (M >= NumElements + SplitNumElements)
8822 V2BlendMask.push_back(M - NumElements);
8823 V1BlendMask.push_back(-1);
8824 BlendMask.push_back(SplitNumElements + i);
8825 } else if (M >= 0) {
8826 if (M >= SplitNumElements)
8830 V2BlendMask.push_back(-1);
8831 V1BlendMask.push_back(M);
8832 BlendMask.push_back(i);
8834 V2BlendMask.push_back(-1);
8835 V1BlendMask.push_back(-1);
8836 BlendMask.push_back(-1);
8840 // Because the lowering happens after all combining takes place, we need to
8841 // manually combine these blend masks as much as possible so that we create
8842 // a minimal number of high-level vector shuffle nodes.
8844 // First try just blending the halves of V1 or V2.
8845 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8846 return DAG.getUNDEF(SplitVT);
8847 if (!UseLoV2 && !UseHiV2)
8848 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8849 if (!UseLoV1 && !UseHiV1)
8850 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8852 SDValue V1Blend, V2Blend;
8853 if (UseLoV1 && UseHiV1) {
8855 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8857 // We only use half of V1 so map the usage down into the final blend mask.
8858 V1Blend = UseLoV1 ? LoV1 : HiV1;
8859 for (int i = 0; i < SplitNumElements; ++i)
8860 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8861 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8863 if (UseLoV2 && UseHiV2) {
8865 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8867 // We only use half of V2 so map the usage down into the final blend mask.
8868 V2Blend = UseLoV2 ? LoV2 : HiV2;
8869 for (int i = 0; i < SplitNumElements; ++i)
8870 if (BlendMask[i] >= SplitNumElements)
8871 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8873 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8875 SDValue Lo = HalfBlend(LoMask);
8876 SDValue Hi = HalfBlend(HiMask);
8877 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8880 /// \brief Either split a vector in halves or decompose the shuffles and the
8883 /// This is provided as a good fallback for many lowerings of non-single-input
8884 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8885 /// between splitting the shuffle into 128-bit components and stitching those
8886 /// back together vs. extracting the single-input shuffles and blending those
8888 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8889 SDValue V2, ArrayRef<int> Mask,
8890 SelectionDAG &DAG) {
8891 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8892 "lower single-input shuffles as it "
8893 "could then recurse on itself.");
8894 int Size = Mask.size();
8896 // If this can be modeled as a broadcast of two elements followed by a blend,
8897 // prefer that lowering. This is especially important because broadcasts can
8898 // often fold with memory operands.
8899 auto DoBothBroadcast = [&] {
8900 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8903 if (V2BroadcastIdx == -1)
8904 V2BroadcastIdx = M - Size;
8905 else if (M - Size != V2BroadcastIdx)
8907 } else if (M >= 0) {
8908 if (V1BroadcastIdx == -1)
8910 else if (M != V1BroadcastIdx)
8915 if (DoBothBroadcast())
8916 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8919 // If the inputs all stem from a single 128-bit lane of each input, then we
8920 // split them rather than blending because the split will decompose to
8921 // unusually few instructions.
8922 int LaneCount = VT.getSizeInBits() / 128;
8923 int LaneSize = Size / LaneCount;
8924 SmallBitVector LaneInputs[2];
8925 LaneInputs[0].resize(LaneCount, false);
8926 LaneInputs[1].resize(LaneCount, false);
8927 for (int i = 0; i < Size; ++i)
8929 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8930 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8931 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8933 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8934 // that the decomposed single-input shuffles don't end up here.
8935 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8938 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8939 /// a permutation and blend of those lanes.
8941 /// This essentially blends the out-of-lane inputs to each lane into the lane
8942 /// from a permuted copy of the vector. This lowering strategy results in four
8943 /// instructions in the worst case for a single-input cross lane shuffle which
8944 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8945 /// of. Special cases for each particular shuffle pattern should be handled
8946 /// prior to trying this lowering.
8947 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8948 SDValue V1, SDValue V2,
8950 SelectionDAG &DAG) {
8951 // FIXME: This should probably be generalized for 512-bit vectors as well.
8952 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8953 int LaneSize = Mask.size() / 2;
8955 // If there are only inputs from one 128-bit lane, splitting will in fact be
8956 // less expensive. The flags track wether the given lane contains an element
8957 // that crosses to another lane.
8958 bool LaneCrossing[2] = {false, false};
8959 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8960 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8961 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8962 if (!LaneCrossing[0] || !LaneCrossing[1])
8963 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8965 if (isSingleInputShuffleMask(Mask)) {
8966 SmallVector<int, 32> FlippedBlendMask;
8967 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8968 FlippedBlendMask.push_back(
8969 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8971 : Mask[i] % LaneSize +
8972 (i / LaneSize) * LaneSize + Size));
8974 // Flip the vector, and blend the results which should now be in-lane. The
8975 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8976 // 5 for the high source. The value 3 selects the high half of source 2 and
8977 // the value 2 selects the low half of source 2. We only use source 2 to
8978 // allow folding it into a memory operand.
8979 unsigned PERMMask = 3 | 2 << 4;
8980 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
8981 V1, DAG.getConstant(PERMMask, MVT::i8));
8982 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
8985 // This now reduces to two single-input shuffles of V1 and V2 which at worst
8986 // will be handled by the above logic and a blend of the results, much like
8987 // other patterns in AVX.
8988 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8991 /// \brief Handle lowering 2-lane 128-bit shuffles.
8992 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8993 SDValue V2, ArrayRef<int> Mask,
8994 const X86Subtarget *Subtarget,
8995 SelectionDAG &DAG) {
8996 // Blends are faster and handle all the non-lane-crossing cases.
8997 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9001 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9002 VT.getVectorNumElements() / 2);
9003 // Check for patterns which can be matched with a single insert of a 128-bit
9005 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}) ||
9006 isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9007 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9008 DAG.getIntPtrConstant(0));
9009 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9010 Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9011 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9013 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9014 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9015 DAG.getIntPtrConstant(0));
9016 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9017 DAG.getIntPtrConstant(2));
9018 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9021 // Otherwise form a 128-bit permutation.
9022 // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9023 unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9024 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9025 DAG.getConstant(PermMask, MVT::i8));
9028 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9029 /// shuffling each lane.
9031 /// This will only succeed when the result of fixing the 128-bit lanes results
9032 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9033 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9034 /// the lane crosses early and then use simpler shuffles within each lane.
9036 /// FIXME: It might be worthwhile at some point to support this without
9037 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9038 /// in x86 only floating point has interesting non-repeating shuffles, and even
9039 /// those are still *marginally* more expensive.
9040 static SDValue lowerVectorShuffleByMerging128BitLanes(
9041 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9042 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9043 assert(!isSingleInputShuffleMask(Mask) &&
9044 "This is only useful with multiple inputs.");
9046 int Size = Mask.size();
9047 int LaneSize = 128 / VT.getScalarSizeInBits();
9048 int NumLanes = Size / LaneSize;
9049 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9051 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9052 // check whether the in-128-bit lane shuffles share a repeating pattern.
9053 SmallVector<int, 4> Lanes;
9054 Lanes.resize(NumLanes, -1);
9055 SmallVector<int, 4> InLaneMask;
9056 InLaneMask.resize(LaneSize, -1);
9057 for (int i = 0; i < Size; ++i) {
9061 int j = i / LaneSize;
9064 // First entry we've seen for this lane.
9065 Lanes[j] = Mask[i] / LaneSize;
9066 } else if (Lanes[j] != Mask[i] / LaneSize) {
9067 // This doesn't match the lane selected previously!
9071 // Check that within each lane we have a consistent shuffle mask.
9072 int k = i % LaneSize;
9073 if (InLaneMask[k] < 0) {
9074 InLaneMask[k] = Mask[i] % LaneSize;
9075 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9076 // This doesn't fit a repeating in-lane mask.
9081 // First shuffle the lanes into place.
9082 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9083 VT.getSizeInBits() / 64);
9084 SmallVector<int, 8> LaneMask;
9085 LaneMask.resize(NumLanes * 2, -1);
9086 for (int i = 0; i < NumLanes; ++i)
9087 if (Lanes[i] >= 0) {
9088 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9089 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9092 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9093 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9094 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9096 // Cast it back to the type we actually want.
9097 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9099 // Now do a simple shuffle that isn't lane crossing.
9100 SmallVector<int, 8> NewMask;
9101 NewMask.resize(Size, -1);
9102 for (int i = 0; i < Size; ++i)
9104 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9105 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9106 "Must not introduce lane crosses at this point!");
9108 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9111 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9114 /// This returns true if the elements from a particular input are already in the
9115 /// slot required by the given mask and require no permutation.
9116 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9117 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9118 int Size = Mask.size();
9119 for (int i = 0; i < Size; ++i)
9120 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9126 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9128 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9129 /// isn't available.
9130 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9131 const X86Subtarget *Subtarget,
9132 SelectionDAG &DAG) {
9134 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9135 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9136 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9137 ArrayRef<int> Mask = SVOp->getMask();
9138 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9140 SmallVector<int, 4> WidenedMask;
9141 if (canWidenShuffleElements(Mask, WidenedMask))
9142 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9145 if (isSingleInputShuffleMask(Mask)) {
9146 // Check for being able to broadcast a single element.
9147 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9148 Mask, Subtarget, DAG))
9151 // Use low duplicate instructions for masks that match their pattern.
9152 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9153 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9155 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9156 // Non-half-crossing single input shuffles can be lowerid with an
9157 // interleaved permutation.
9158 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9159 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9160 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9161 DAG.getConstant(VPERMILPMask, MVT::i8));
9164 // With AVX2 we have direct support for this permutation.
9165 if (Subtarget->hasAVX2())
9166 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9167 getV4X86ShuffleImm8ForMask(Mask, DAG));
9169 // Otherwise, fall back.
9170 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9174 // X86 has dedicated unpack instructions that can handle specific blend
9175 // operations: UNPCKH and UNPCKL.
9176 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9177 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9178 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9179 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9180 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9181 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9182 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9183 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9185 // If we have a single input to the zero element, insert that into V1 if we
9186 // can do so cheaply.
9188 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9189 if (NumV2Elements == 1 && Mask[0] >= 4)
9190 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9191 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9194 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9198 // Check if the blend happens to exactly fit that of SHUFPD.
9199 if ((Mask[0] == -1 || Mask[0] < 2) &&
9200 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9201 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9202 (Mask[3] == -1 || Mask[3] >= 6)) {
9203 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9204 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9205 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9206 DAG.getConstant(SHUFPDMask, MVT::i8));
9208 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9209 (Mask[1] == -1 || Mask[1] < 2) &&
9210 (Mask[2] == -1 || Mask[2] >= 6) &&
9211 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9212 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9213 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9214 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9215 DAG.getConstant(SHUFPDMask, MVT::i8));
9218 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9219 // shuffle. However, if we have AVX2 and either inputs are already in place,
9220 // we will be able to shuffle even across lanes the other input in a single
9221 // instruction so skip this pattern.
9222 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9223 isShuffleMaskInputInPlace(1, Mask))))
9224 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9225 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9228 // If we have AVX2 then we always want to lower with a blend because an v4 we
9229 // can fully permute the elements.
9230 if (Subtarget->hasAVX2())
9231 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9234 // Otherwise fall back on generic lowering.
9235 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9238 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9240 /// This routine is only called when we have AVX2 and thus a reasonable
9241 /// instruction set for v4i64 shuffling..
9242 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9243 const X86Subtarget *Subtarget,
9244 SelectionDAG &DAG) {
9246 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9247 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9248 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9249 ArrayRef<int> Mask = SVOp->getMask();
9250 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9251 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9253 SmallVector<int, 4> WidenedMask;
9254 if (canWidenShuffleElements(Mask, WidenedMask))
9255 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9258 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9262 // Check for being able to broadcast a single element.
9263 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9264 Mask, Subtarget, DAG))
9267 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9268 // use lower latency instructions that will operate on both 128-bit lanes.
9269 SmallVector<int, 2> RepeatedMask;
9270 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9271 if (isSingleInputShuffleMask(Mask)) {
9272 int PSHUFDMask[] = {-1, -1, -1, -1};
9273 for (int i = 0; i < 2; ++i)
9274 if (RepeatedMask[i] >= 0) {
9275 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9276 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9279 ISD::BITCAST, DL, MVT::v4i64,
9280 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9281 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9282 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9286 // AVX2 provides a direct instruction for permuting a single input across
9288 if (isSingleInputShuffleMask(Mask))
9289 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9290 getV4X86ShuffleImm8ForMask(Mask, DAG));
9292 // Try to use shift instructions.
9294 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9297 // Use dedicated unpack instructions for masks that match their pattern.
9298 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9299 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9300 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9301 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9302 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9303 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9304 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9305 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9307 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9308 // shuffle. However, if we have AVX2 and either inputs are already in place,
9309 // we will be able to shuffle even across lanes the other input in a single
9310 // instruction so skip this pattern.
9311 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9312 isShuffleMaskInputInPlace(1, Mask))))
9313 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9314 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9317 // Otherwise fall back on generic blend lowering.
9318 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9322 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9324 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9325 /// isn't available.
9326 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9327 const X86Subtarget *Subtarget,
9328 SelectionDAG &DAG) {
9330 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9331 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9332 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9333 ArrayRef<int> Mask = SVOp->getMask();
9334 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9336 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9340 // Check for being able to broadcast a single element.
9341 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9342 Mask, Subtarget, DAG))
9345 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9346 // options to efficiently lower the shuffle.
9347 SmallVector<int, 4> RepeatedMask;
9348 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9349 assert(RepeatedMask.size() == 4 &&
9350 "Repeated masks must be half the mask width!");
9352 // Use even/odd duplicate instructions for masks that match their pattern.
9353 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9354 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9355 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9356 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9358 if (isSingleInputShuffleMask(Mask))
9359 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9360 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9362 // Use dedicated unpack instructions for masks that match their pattern.
9363 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9364 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9365 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9366 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9367 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9368 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9369 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9370 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9372 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9373 // have already handled any direct blends. We also need to squash the
9374 // repeated mask into a simulated v4f32 mask.
9375 for (int i = 0; i < 4; ++i)
9376 if (RepeatedMask[i] >= 8)
9377 RepeatedMask[i] -= 4;
9378 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9381 // If we have a single input shuffle with different shuffle patterns in the
9382 // two 128-bit lanes use the variable mask to VPERMILPS.
9383 if (isSingleInputShuffleMask(Mask)) {
9384 SDValue VPermMask[8];
9385 for (int i = 0; i < 8; ++i)
9386 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9387 : DAG.getConstant(Mask[i], MVT::i32);
9388 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9390 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9391 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9393 if (Subtarget->hasAVX2())
9394 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9395 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9396 DAG.getNode(ISD::BUILD_VECTOR, DL,
9397 MVT::v8i32, VPermMask)),
9400 // Otherwise, fall back.
9401 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9405 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9407 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9408 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9411 // If we have AVX2 then we always want to lower with a blend because at v8 we
9412 // can fully permute the elements.
9413 if (Subtarget->hasAVX2())
9414 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9417 // Otherwise fall back on generic lowering.
9418 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9421 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9423 /// This routine is only called when we have AVX2 and thus a reasonable
9424 /// instruction set for v8i32 shuffling..
9425 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9426 const X86Subtarget *Subtarget,
9427 SelectionDAG &DAG) {
9429 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9430 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9431 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9432 ArrayRef<int> Mask = SVOp->getMask();
9433 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9434 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9436 // Whenever we can lower this as a zext, that instruction is strictly faster
9437 // than any alternative. It also allows us to fold memory operands into the
9438 // shuffle in many cases.
9439 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9440 Mask, Subtarget, DAG))
9443 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9447 // Check for being able to broadcast a single element.
9448 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9449 Mask, Subtarget, DAG))
9452 // If the shuffle mask is repeated in each 128-bit lane we can use more
9453 // efficient instructions that mirror the shuffles across the two 128-bit
9455 SmallVector<int, 4> RepeatedMask;
9456 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9457 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9458 if (isSingleInputShuffleMask(Mask))
9459 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9460 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9462 // Use dedicated unpack instructions for masks that match their pattern.
9463 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9464 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9465 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9466 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9467 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9468 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9469 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9470 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9473 // Try to use shift instructions.
9475 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9478 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9479 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9482 // If the shuffle patterns aren't repeated but it is a single input, directly
9483 // generate a cross-lane VPERMD instruction.
9484 if (isSingleInputShuffleMask(Mask)) {
9485 SDValue VPermMask[8];
9486 for (int i = 0; i < 8; ++i)
9487 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9488 : DAG.getConstant(Mask[i], MVT::i32);
9490 X86ISD::VPERMV, DL, MVT::v8i32,
9491 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9494 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9496 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9497 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9500 // Otherwise fall back on generic blend lowering.
9501 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9505 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9507 /// This routine is only called when we have AVX2 and thus a reasonable
9508 /// instruction set for v16i16 shuffling..
9509 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9510 const X86Subtarget *Subtarget,
9511 SelectionDAG &DAG) {
9513 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9514 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9515 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9516 ArrayRef<int> Mask = SVOp->getMask();
9517 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9518 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9520 // Whenever we can lower this as a zext, that instruction is strictly faster
9521 // than any alternative. It also allows us to fold memory operands into the
9522 // shuffle in many cases.
9523 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9524 Mask, Subtarget, DAG))
9527 // Check for being able to broadcast a single element.
9528 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9529 Mask, Subtarget, DAG))
9532 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9536 // Use dedicated unpack instructions for masks that match their pattern.
9537 if (isShuffleEquivalent(V1, V2, Mask,
9538 {// First 128-bit lane:
9539 0, 16, 1, 17, 2, 18, 3, 19,
9540 // Second 128-bit lane:
9541 8, 24, 9, 25, 10, 26, 11, 27}))
9542 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9543 if (isShuffleEquivalent(V1, V2, Mask,
9544 {// First 128-bit lane:
9545 4, 20, 5, 21, 6, 22, 7, 23,
9546 // Second 128-bit lane:
9547 12, 28, 13, 29, 14, 30, 15, 31}))
9548 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9550 // Try to use shift instructions.
9552 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9555 // Try to use byte rotation instructions.
9556 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9557 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9560 if (isSingleInputShuffleMask(Mask)) {
9561 // There are no generalized cross-lane shuffle operations available on i16
9563 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9564 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9567 SmallVector<int, 8> RepeatedMask;
9568 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9569 // As this is a single-input shuffle, the repeated mask should be
9570 // a strictly valid v8i16 mask that we can pass through to the v8i16
9571 // lowering to handle even the v16 case.
9572 return lowerV8I16GeneralSingleInputVectorShuffle(
9573 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9576 SDValue PSHUFBMask[32];
9577 for (int i = 0; i < 16; ++i) {
9578 if (Mask[i] == -1) {
9579 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9583 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9584 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9585 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9586 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9589 ISD::BITCAST, DL, MVT::v16i16,
9591 X86ISD::PSHUFB, DL, MVT::v32i8,
9592 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9593 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9596 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9598 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9599 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9602 // Otherwise fall back on generic lowering.
9603 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9606 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9608 /// This routine is only called when we have AVX2 and thus a reasonable
9609 /// instruction set for v32i8 shuffling..
9610 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9611 const X86Subtarget *Subtarget,
9612 SelectionDAG &DAG) {
9614 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9615 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9616 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9617 ArrayRef<int> Mask = SVOp->getMask();
9618 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9619 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9621 // Whenever we can lower this as a zext, that instruction is strictly faster
9622 // than any alternative. It also allows us to fold memory operands into the
9623 // shuffle in many cases.
9624 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9625 Mask, Subtarget, DAG))
9628 // Check for being able to broadcast a single element.
9629 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9630 Mask, Subtarget, DAG))
9633 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9637 // Use dedicated unpack instructions for masks that match their pattern.
9638 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9640 if (isShuffleEquivalent(
9642 {// First 128-bit lane:
9643 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9644 // Second 128-bit lane:
9645 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9646 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9647 if (isShuffleEquivalent(
9649 {// First 128-bit lane:
9650 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9651 // Second 128-bit lane:
9652 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9653 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9655 // Try to use shift instructions.
9657 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9660 // Try to use byte rotation instructions.
9661 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9662 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9665 if (isSingleInputShuffleMask(Mask)) {
9666 // There are no generalized cross-lane shuffle operations available on i8
9668 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9669 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9672 SDValue PSHUFBMask[32];
9673 for (int i = 0; i < 32; ++i)
9676 ? DAG.getUNDEF(MVT::i8)
9677 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9680 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9681 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9684 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9686 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9687 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9690 // Otherwise fall back on generic lowering.
9691 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9694 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9696 /// This routine either breaks down the specific type of a 256-bit x86 vector
9697 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9698 /// together based on the available instructions.
9699 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9700 MVT VT, const X86Subtarget *Subtarget,
9701 SelectionDAG &DAG) {
9703 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9704 ArrayRef<int> Mask = SVOp->getMask();
9706 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9707 // check for those subtargets here and avoid much of the subtarget querying in
9708 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9709 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9710 // floating point types there eventually, just immediately cast everything to
9711 // a float and operate entirely in that domain.
9712 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9713 int ElementBits = VT.getScalarSizeInBits();
9714 if (ElementBits < 32)
9715 // No floating point type available, decompose into 128-bit vectors.
9716 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9718 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9719 VT.getVectorNumElements());
9720 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9721 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9722 return DAG.getNode(ISD::BITCAST, DL, VT,
9723 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9726 switch (VT.SimpleTy) {
9728 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9730 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9732 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9734 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9736 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9738 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9741 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9745 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9746 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9747 const X86Subtarget *Subtarget,
9748 SelectionDAG &DAG) {
9750 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9751 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9752 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9753 ArrayRef<int> Mask = SVOp->getMask();
9754 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9756 // X86 has dedicated unpack instructions that can handle specific blend
9757 // operations: UNPCKH and UNPCKL.
9758 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9759 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9760 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9761 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9763 // FIXME: Implement direct support for this type!
9764 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9767 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9768 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9769 const X86Subtarget *Subtarget,
9770 SelectionDAG &DAG) {
9772 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9773 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9774 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9775 ArrayRef<int> Mask = SVOp->getMask();
9776 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9778 // Use dedicated unpack instructions for masks that match their pattern.
9779 if (isShuffleEquivalent(V1, V2, Mask,
9780 {// First 128-bit lane.
9781 0, 16, 1, 17, 4, 20, 5, 21,
9782 // Second 128-bit lane.
9783 8, 24, 9, 25, 12, 28, 13, 29}))
9784 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9785 if (isShuffleEquivalent(V1, V2, Mask,
9786 {// First 128-bit lane.
9787 2, 18, 3, 19, 6, 22, 7, 23,
9788 // Second 128-bit lane.
9789 10, 26, 11, 27, 14, 30, 15, 31}))
9790 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9792 // FIXME: Implement direct support for this type!
9793 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9796 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9797 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9798 const X86Subtarget *Subtarget,
9799 SelectionDAG &DAG) {
9801 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9802 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9803 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9804 ArrayRef<int> Mask = SVOp->getMask();
9805 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9807 // X86 has dedicated unpack instructions that can handle specific blend
9808 // operations: UNPCKH and UNPCKL.
9809 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9810 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9811 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9812 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9814 // FIXME: Implement direct support for this type!
9815 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9818 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9819 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9820 const X86Subtarget *Subtarget,
9821 SelectionDAG &DAG) {
9823 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9824 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9825 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9826 ArrayRef<int> Mask = SVOp->getMask();
9827 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9829 // Use dedicated unpack instructions for masks that match their pattern.
9830 if (isShuffleEquivalent(V1, V2, Mask,
9831 {// First 128-bit lane.
9832 0, 16, 1, 17, 4, 20, 5, 21,
9833 // Second 128-bit lane.
9834 8, 24, 9, 25, 12, 28, 13, 29}))
9835 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9836 if (isShuffleEquivalent(V1, V2, Mask,
9837 {// First 128-bit lane.
9838 2, 18, 3, 19, 6, 22, 7, 23,
9839 // Second 128-bit lane.
9840 10, 26, 11, 27, 14, 30, 15, 31}))
9841 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9843 // FIXME: Implement direct support for this type!
9844 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9847 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9848 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9849 const X86Subtarget *Subtarget,
9850 SelectionDAG &DAG) {
9852 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9853 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9854 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9855 ArrayRef<int> Mask = SVOp->getMask();
9856 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9857 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9859 // FIXME: Implement direct support for this type!
9860 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9863 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9864 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9865 const X86Subtarget *Subtarget,
9866 SelectionDAG &DAG) {
9868 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9869 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9870 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9871 ArrayRef<int> Mask = SVOp->getMask();
9872 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9873 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9875 // FIXME: Implement direct support for this type!
9876 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9879 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9881 /// This routine either breaks down the specific type of a 512-bit x86 vector
9882 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9883 /// together based on the available instructions.
9884 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885 MVT VT, const X86Subtarget *Subtarget,
9886 SelectionDAG &DAG) {
9888 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9889 ArrayRef<int> Mask = SVOp->getMask();
9890 assert(Subtarget->hasAVX512() &&
9891 "Cannot lower 512-bit vectors w/ basic ISA!");
9893 // Check for being able to broadcast a single element.
9894 if (SDValue Broadcast =
9895 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9898 // Dispatch to each element type for lowering. If we don't have supprot for
9899 // specific element type shuffles at 512 bits, immediately split them and
9900 // lower them. Each lowering routine of a given type is allowed to assume that
9901 // the requisite ISA extensions for that element type are available.
9902 switch (VT.SimpleTy) {
9904 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9906 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9908 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9910 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9912 if (Subtarget->hasBWI())
9913 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9916 if (Subtarget->hasBWI())
9917 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9921 llvm_unreachable("Not a valid 512-bit x86 vector type!");
9924 // Otherwise fall back on splitting.
9925 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9928 /// \brief Top-level lowering for x86 vector shuffles.
9930 /// This handles decomposition, canonicalization, and lowering of all x86
9931 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9932 /// above in helper routines. The canonicalization attempts to widen shuffles
9933 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9934 /// s.t. only one of the two inputs needs to be tested, etc.
9935 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9936 SelectionDAG &DAG) {
9937 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9938 ArrayRef<int> Mask = SVOp->getMask();
9939 SDValue V1 = Op.getOperand(0);
9940 SDValue V2 = Op.getOperand(1);
9941 MVT VT = Op.getSimpleValueType();
9942 int NumElements = VT.getVectorNumElements();
9945 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9947 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9948 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9949 if (V1IsUndef && V2IsUndef)
9950 return DAG.getUNDEF(VT);
9952 // When we create a shuffle node we put the UNDEF node to second operand,
9953 // but in some cases the first operand may be transformed to UNDEF.
9954 // In this case we should just commute the node.
9956 return DAG.getCommutedVectorShuffle(*SVOp);
9958 // Check for non-undef masks pointing at an undef vector and make the masks
9959 // undef as well. This makes it easier to match the shuffle based solely on
9963 if (M >= NumElements) {
9964 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
9965 for (int &M : NewMask)
9966 if (M >= NumElements)
9968 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
9971 // We actually see shuffles that are entirely re-arrangements of a set of
9972 // zero inputs. This mostly happens while decomposing complex shuffles into
9973 // simple ones. Directly lower these as a buildvector of zeros.
9974 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9976 return getZeroVector(VT, Subtarget, DAG, dl);
9978 // Try to collapse shuffles into using a vector type with fewer elements but
9979 // wider element types. We cap this to not form integers or floating point
9980 // elements wider than 64 bits, but it might be interesting to form i128
9981 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
9982 SmallVector<int, 16> WidenedMask;
9983 if (VT.getScalarSizeInBits() < 64 &&
9984 canWidenShuffleElements(Mask, WidenedMask)) {
9985 MVT NewEltVT = VT.isFloatingPoint()
9986 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
9987 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
9988 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9989 // Make sure that the new vector type is legal. For example, v2f64 isn't
9991 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9992 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9993 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9994 return DAG.getNode(ISD::BITCAST, dl, VT,
9995 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
9999 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10000 for (int M : SVOp->getMask())
10002 ++NumUndefElements;
10003 else if (M < NumElements)
10008 // Commute the shuffle as needed such that more elements come from V1 than
10009 // V2. This allows us to match the shuffle pattern strictly on how many
10010 // elements come from V1 without handling the symmetric cases.
10011 if (NumV2Elements > NumV1Elements)
10012 return DAG.getCommutedVectorShuffle(*SVOp);
10014 // When the number of V1 and V2 elements are the same, try to minimize the
10015 // number of uses of V2 in the low half of the vector. When that is tied,
10016 // ensure that the sum of indices for V1 is equal to or lower than the sum
10017 // indices for V2. When those are equal, try to ensure that the number of odd
10018 // indices for V1 is lower than the number of odd indices for V2.
10019 if (NumV1Elements == NumV2Elements) {
10020 int LowV1Elements = 0, LowV2Elements = 0;
10021 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10022 if (M >= NumElements)
10026 if (LowV2Elements > LowV1Elements) {
10027 return DAG.getCommutedVectorShuffle(*SVOp);
10028 } else if (LowV2Elements == LowV1Elements) {
10029 int SumV1Indices = 0, SumV2Indices = 0;
10030 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10031 if (SVOp->getMask()[i] >= NumElements)
10033 else if (SVOp->getMask()[i] >= 0)
10035 if (SumV2Indices < SumV1Indices) {
10036 return DAG.getCommutedVectorShuffle(*SVOp);
10037 } else if (SumV2Indices == SumV1Indices) {
10038 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10039 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10040 if (SVOp->getMask()[i] >= NumElements)
10041 NumV2OddIndices += i % 2;
10042 else if (SVOp->getMask()[i] >= 0)
10043 NumV1OddIndices += i % 2;
10044 if (NumV2OddIndices < NumV1OddIndices)
10045 return DAG.getCommutedVectorShuffle(*SVOp);
10050 // For each vector width, delegate to a specialized lowering routine.
10051 if (VT.getSizeInBits() == 128)
10052 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10054 if (VT.getSizeInBits() == 256)
10055 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10057 // Force AVX-512 vectors to be scalarized for now.
10058 // FIXME: Implement AVX-512 support!
10059 if (VT.getSizeInBits() == 512)
10060 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10062 llvm_unreachable("Unimplemented!");
10065 // This function assumes its argument is a BUILD_VECTOR of constants or
10066 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10068 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10069 unsigned &MaskValue) {
10071 unsigned NumElems = BuildVector->getNumOperands();
10072 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10073 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10074 unsigned NumElemsInLane = NumElems / NumLanes;
10076 // Blend for v16i16 should be symetric for the both lanes.
10077 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10078 SDValue EltCond = BuildVector->getOperand(i);
10079 SDValue SndLaneEltCond =
10080 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10082 int Lane1Cond = -1, Lane2Cond = -1;
10083 if (isa<ConstantSDNode>(EltCond))
10084 Lane1Cond = !isZero(EltCond);
10085 if (isa<ConstantSDNode>(SndLaneEltCond))
10086 Lane2Cond = !isZero(SndLaneEltCond);
10088 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10089 // Lane1Cond != 0, means we want the first argument.
10090 // Lane1Cond == 0, means we want the second argument.
10091 // The encoding of this argument is 0 for the first argument, 1
10092 // for the second. Therefore, invert the condition.
10093 MaskValue |= !Lane1Cond << i;
10094 else if (Lane1Cond < 0)
10095 MaskValue |= !Lane2Cond << i;
10102 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10103 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10104 const X86Subtarget *Subtarget,
10105 SelectionDAG &DAG) {
10106 SDValue Cond = Op.getOperand(0);
10107 SDValue LHS = Op.getOperand(1);
10108 SDValue RHS = Op.getOperand(2);
10110 MVT VT = Op.getSimpleValueType();
10112 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10114 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10116 // Only non-legal VSELECTs reach this lowering, convert those into generic
10117 // shuffles and re-use the shuffle lowering path for blends.
10118 SmallVector<int, 32> Mask;
10119 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10120 SDValue CondElt = CondBV->getOperand(i);
10122 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10124 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10127 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10128 // A vselect where all conditions and data are constants can be optimized into
10129 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10130 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10131 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10132 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10135 // Try to lower this to a blend-style vector shuffle. This can handle all
10136 // constant condition cases.
10137 SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG);
10138 if (BlendOp.getNode())
10141 // Variable blends are only legal from SSE4.1 onward.
10142 if (!Subtarget->hasSSE41())
10145 // Only some types will be legal on some subtargets. If we can emit a legal
10146 // VSELECT-matching blend, return Op, and but if we need to expand, return
10148 switch (Op.getSimpleValueType().SimpleTy) {
10150 // Most of the vector types have blends past SSE4.1.
10154 // The byte blends for AVX vectors were introduced only in AVX2.
10155 if (Subtarget->hasAVX2())
10162 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10163 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10166 // FIXME: We should custom lower this by fixing the condition and using i8
10172 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10173 MVT VT = Op.getSimpleValueType();
10176 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10179 if (VT.getSizeInBits() == 8) {
10180 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10181 Op.getOperand(0), Op.getOperand(1));
10182 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10183 DAG.getValueType(VT));
10184 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10187 if (VT.getSizeInBits() == 16) {
10188 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10189 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10191 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10192 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10193 DAG.getNode(ISD::BITCAST, dl,
10196 Op.getOperand(1)));
10197 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10198 Op.getOperand(0), Op.getOperand(1));
10199 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10200 DAG.getValueType(VT));
10201 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10204 if (VT == MVT::f32) {
10205 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10206 // the result back to FR32 register. It's only worth matching if the
10207 // result has a single use which is a store or a bitcast to i32. And in
10208 // the case of a store, it's not worth it if the index is a constant 0,
10209 // because a MOVSSmr can be used instead, which is smaller and faster.
10210 if (!Op.hasOneUse())
10212 SDNode *User = *Op.getNode()->use_begin();
10213 if ((User->getOpcode() != ISD::STORE ||
10214 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10215 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10216 (User->getOpcode() != ISD::BITCAST ||
10217 User->getValueType(0) != MVT::i32))
10219 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10220 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10223 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10226 if (VT == MVT::i32 || VT == MVT::i64) {
10227 // ExtractPS/pextrq works with constant index.
10228 if (isa<ConstantSDNode>(Op.getOperand(1)))
10234 /// Extract one bit from mask vector, like v16i1 or v8i1.
10235 /// AVX-512 feature.
10237 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10238 SDValue Vec = Op.getOperand(0);
10240 MVT VecVT = Vec.getSimpleValueType();
10241 SDValue Idx = Op.getOperand(1);
10242 MVT EltVT = Op.getSimpleValueType();
10244 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10245 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10246 "Unexpected vector type in ExtractBitFromMaskVector");
10248 // variable index can't be handled in mask registers,
10249 // extend vector to VR512
10250 if (!isa<ConstantSDNode>(Idx)) {
10251 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10252 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10253 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10254 ExtVT.getVectorElementType(), Ext, Idx);
10255 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10258 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10259 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10260 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10261 rc = getRegClassFor(MVT::v16i1);
10262 unsigned MaxSift = rc->getSize()*8 - 1;
10263 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10264 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10265 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10266 DAG.getConstant(MaxSift, MVT::i8));
10267 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10268 DAG.getIntPtrConstant(0));
10272 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10273 SelectionDAG &DAG) const {
10275 SDValue Vec = Op.getOperand(0);
10276 MVT VecVT = Vec.getSimpleValueType();
10277 SDValue Idx = Op.getOperand(1);
10279 if (Op.getSimpleValueType() == MVT::i1)
10280 return ExtractBitFromMaskVector(Op, DAG);
10282 if (!isa<ConstantSDNode>(Idx)) {
10283 if (VecVT.is512BitVector() ||
10284 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10285 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10288 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10289 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10290 MaskEltVT.getSizeInBits());
10292 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10293 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10294 getZeroVector(MaskVT, Subtarget, DAG, dl),
10295 Idx, DAG.getConstant(0, getPointerTy()));
10296 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10297 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10298 Perm, DAG.getConstant(0, getPointerTy()));
10303 // If this is a 256-bit vector result, first extract the 128-bit vector and
10304 // then extract the element from the 128-bit vector.
10305 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10307 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10308 // Get the 128-bit vector.
10309 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10310 MVT EltVT = VecVT.getVectorElementType();
10312 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10314 //if (IdxVal >= NumElems/2)
10315 // IdxVal -= NumElems/2;
10316 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10317 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10318 DAG.getConstant(IdxVal, MVT::i32));
10321 assert(VecVT.is128BitVector() && "Unexpected vector length");
10323 if (Subtarget->hasSSE41()) {
10324 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10329 MVT VT = Op.getSimpleValueType();
10330 // TODO: handle v16i8.
10331 if (VT.getSizeInBits() == 16) {
10332 SDValue Vec = Op.getOperand(0);
10333 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10335 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10336 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10337 DAG.getNode(ISD::BITCAST, dl,
10339 Op.getOperand(1)));
10340 // Transform it so it match pextrw which produces a 32-bit result.
10341 MVT EltVT = MVT::i32;
10342 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10343 Op.getOperand(0), Op.getOperand(1));
10344 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10345 DAG.getValueType(VT));
10346 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10349 if (VT.getSizeInBits() == 32) {
10350 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10354 // SHUFPS the element to the lowest double word, then movss.
10355 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10356 MVT VVT = Op.getOperand(0).getSimpleValueType();
10357 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10358 DAG.getUNDEF(VVT), Mask);
10359 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10360 DAG.getIntPtrConstant(0));
10363 if (VT.getSizeInBits() == 64) {
10364 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10365 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10366 // to match extract_elt for f64.
10367 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10371 // UNPCKHPD the element to the lowest double word, then movsd.
10372 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10373 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10374 int Mask[2] = { 1, -1 };
10375 MVT VVT = Op.getOperand(0).getSimpleValueType();
10376 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10377 DAG.getUNDEF(VVT), Mask);
10378 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10379 DAG.getIntPtrConstant(0));
10385 /// Insert one bit to mask vector, like v16i1 or v8i1.
10386 /// AVX-512 feature.
10388 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10390 SDValue Vec = Op.getOperand(0);
10391 SDValue Elt = Op.getOperand(1);
10392 SDValue Idx = Op.getOperand(2);
10393 MVT VecVT = Vec.getSimpleValueType();
10395 if (!isa<ConstantSDNode>(Idx)) {
10396 // Non constant index. Extend source and destination,
10397 // insert element and then truncate the result.
10398 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10399 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10400 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10401 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10402 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10403 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10406 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10407 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10408 if (Vec.getOpcode() == ISD::UNDEF)
10409 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10410 DAG.getConstant(IdxVal, MVT::i8));
10411 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10412 unsigned MaxSift = rc->getSize()*8 - 1;
10413 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10414 DAG.getConstant(MaxSift, MVT::i8));
10415 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10416 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10417 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10420 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10421 SelectionDAG &DAG) const {
10422 MVT VT = Op.getSimpleValueType();
10423 MVT EltVT = VT.getVectorElementType();
10425 if (EltVT == MVT::i1)
10426 return InsertBitToMaskVector(Op, DAG);
10429 SDValue N0 = Op.getOperand(0);
10430 SDValue N1 = Op.getOperand(1);
10431 SDValue N2 = Op.getOperand(2);
10432 if (!isa<ConstantSDNode>(N2))
10434 auto *N2C = cast<ConstantSDNode>(N2);
10435 unsigned IdxVal = N2C->getZExtValue();
10437 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10438 // into that, and then insert the subvector back into the result.
10439 if (VT.is256BitVector() || VT.is512BitVector()) {
10440 // Get the desired 128-bit vector half.
10441 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10443 // Insert the element into the desired half.
10444 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10445 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10447 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10448 DAG.getConstant(IdxIn128, MVT::i32));
10450 // Insert the changed part back to the 256-bit vector
10451 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10453 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10455 if (Subtarget->hasSSE41()) {
10456 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10458 if (VT == MVT::v8i16) {
10459 Opc = X86ISD::PINSRW;
10461 assert(VT == MVT::v16i8);
10462 Opc = X86ISD::PINSRB;
10465 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10467 if (N1.getValueType() != MVT::i32)
10468 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10469 if (N2.getValueType() != MVT::i32)
10470 N2 = DAG.getIntPtrConstant(IdxVal);
10471 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10474 if (EltVT == MVT::f32) {
10475 // Bits [7:6] of the constant are the source select. This will always be
10476 // zero here. The DAG Combiner may combine an extract_elt index into
10478 // bits. For example (insert (extract, 3), 2) could be matched by
10480 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10481 // Bits [5:4] of the constant are the destination select. This is the
10482 // value of the incoming immediate.
10483 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10484 // combine either bitwise AND or insert of float 0.0 to set these bits.
10485 N2 = DAG.getIntPtrConstant(IdxVal << 4);
10486 // Create this as a scalar to vector..
10487 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10488 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10491 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10492 // PINSR* works with constant index.
10497 if (EltVT == MVT::i8)
10500 if (EltVT.getSizeInBits() == 16) {
10501 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10502 // as its second argument.
10503 if (N1.getValueType() != MVT::i32)
10504 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10505 if (N2.getValueType() != MVT::i32)
10506 N2 = DAG.getIntPtrConstant(IdxVal);
10507 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10512 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10514 MVT OpVT = Op.getSimpleValueType();
10516 // If this is a 256-bit vector result, first insert into a 128-bit
10517 // vector and then insert into the 256-bit vector.
10518 if (!OpVT.is128BitVector()) {
10519 // Insert into a 128-bit vector.
10520 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10521 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10522 OpVT.getVectorNumElements() / SizeFactor);
10524 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10526 // Insert the 128-bit vector.
10527 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10530 if (OpVT == MVT::v1i64 &&
10531 Op.getOperand(0).getValueType() == MVT::i64)
10532 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10534 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10535 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10536 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10537 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10540 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10541 // a simple subregister reference or explicit instructions to grab
10542 // upper bits of a vector.
10543 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10544 SelectionDAG &DAG) {
10546 SDValue In = Op.getOperand(0);
10547 SDValue Idx = Op.getOperand(1);
10548 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10549 MVT ResVT = Op.getSimpleValueType();
10550 MVT InVT = In.getSimpleValueType();
10552 if (Subtarget->hasFp256()) {
10553 if (ResVT.is128BitVector() &&
10554 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10555 isa<ConstantSDNode>(Idx)) {
10556 return Extract128BitVector(In, IdxVal, DAG, dl);
10558 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10559 isa<ConstantSDNode>(Idx)) {
10560 return Extract256BitVector(In, IdxVal, DAG, dl);
10566 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10567 // simple superregister reference or explicit instructions to insert
10568 // the upper bits of a vector.
10569 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10570 SelectionDAG &DAG) {
10571 if (!Subtarget->hasAVX())
10575 SDValue Vec = Op.getOperand(0);
10576 SDValue SubVec = Op.getOperand(1);
10577 SDValue Idx = Op.getOperand(2);
10579 if (!isa<ConstantSDNode>(Idx))
10582 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10583 MVT OpVT = Op.getSimpleValueType();
10584 MVT SubVecVT = SubVec.getSimpleValueType();
10586 // Fold two 16-byte subvector loads into one 32-byte load:
10587 // (insert_subvector (insert_subvector undef, (load addr), 0),
10588 // (load addr + 16), Elts/2)
10590 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10591 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10592 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10593 !Subtarget->isUnalignedMem32Slow()) {
10594 SDValue SubVec2 = Vec.getOperand(1);
10595 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10596 if (Idx2->getZExtValue() == 0) {
10597 SDValue Ops[] = { SubVec2, SubVec };
10598 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10605 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10606 SubVecVT.is128BitVector())
10607 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10609 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10610 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10615 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10616 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10617 // one of the above mentioned nodes. It has to be wrapped because otherwise
10618 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10619 // be used to form addressing mode. These wrapped nodes will be selected
10622 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10623 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10625 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10626 // global base reg.
10627 unsigned char OpFlag = 0;
10628 unsigned WrapperKind = X86ISD::Wrapper;
10629 CodeModel::Model M = DAG.getTarget().getCodeModel();
10631 if (Subtarget->isPICStyleRIPRel() &&
10632 (M == CodeModel::Small || M == CodeModel::Kernel))
10633 WrapperKind = X86ISD::WrapperRIP;
10634 else if (Subtarget->isPICStyleGOT())
10635 OpFlag = X86II::MO_GOTOFF;
10636 else if (Subtarget->isPICStyleStubPIC())
10637 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10639 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10640 CP->getAlignment(),
10641 CP->getOffset(), OpFlag);
10643 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10644 // With PIC, the address is actually $g + Offset.
10646 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10647 DAG.getNode(X86ISD::GlobalBaseReg,
10648 SDLoc(), getPointerTy()),
10655 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10656 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10658 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10659 // global base reg.
10660 unsigned char OpFlag = 0;
10661 unsigned WrapperKind = X86ISD::Wrapper;
10662 CodeModel::Model M = DAG.getTarget().getCodeModel();
10664 if (Subtarget->isPICStyleRIPRel() &&
10665 (M == CodeModel::Small || M == CodeModel::Kernel))
10666 WrapperKind = X86ISD::WrapperRIP;
10667 else if (Subtarget->isPICStyleGOT())
10668 OpFlag = X86II::MO_GOTOFF;
10669 else if (Subtarget->isPICStyleStubPIC())
10670 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10672 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10675 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10677 // With PIC, the address is actually $g + Offset.
10679 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10680 DAG.getNode(X86ISD::GlobalBaseReg,
10681 SDLoc(), getPointerTy()),
10688 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10689 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10691 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10692 // global base reg.
10693 unsigned char OpFlag = 0;
10694 unsigned WrapperKind = X86ISD::Wrapper;
10695 CodeModel::Model M = DAG.getTarget().getCodeModel();
10697 if (Subtarget->isPICStyleRIPRel() &&
10698 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10699 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10700 OpFlag = X86II::MO_GOTPCREL;
10701 WrapperKind = X86ISD::WrapperRIP;
10702 } else if (Subtarget->isPICStyleGOT()) {
10703 OpFlag = X86II::MO_GOT;
10704 } else if (Subtarget->isPICStyleStubPIC()) {
10705 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10706 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10707 OpFlag = X86II::MO_DARWIN_NONLAZY;
10710 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10713 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10715 // With PIC, the address is actually $g + Offset.
10716 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10717 !Subtarget->is64Bit()) {
10718 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10719 DAG.getNode(X86ISD::GlobalBaseReg,
10720 SDLoc(), getPointerTy()),
10724 // For symbols that require a load from a stub to get the address, emit the
10726 if (isGlobalStubReference(OpFlag))
10727 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10728 MachinePointerInfo::getGOT(), false, false, false, 0);
10734 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10735 // Create the TargetBlockAddressAddress node.
10736 unsigned char OpFlags =
10737 Subtarget->ClassifyBlockAddressReference();
10738 CodeModel::Model M = DAG.getTarget().getCodeModel();
10739 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10740 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10742 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10745 if (Subtarget->isPICStyleRIPRel() &&
10746 (M == CodeModel::Small || M == CodeModel::Kernel))
10747 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10749 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10751 // With PIC, the address is actually $g + Offset.
10752 if (isGlobalRelativeToPICBase(OpFlags)) {
10753 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10754 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10762 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10763 int64_t Offset, SelectionDAG &DAG) const {
10764 // Create the TargetGlobalAddress node, folding in the constant
10765 // offset if it is legal.
10766 unsigned char OpFlags =
10767 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10768 CodeModel::Model M = DAG.getTarget().getCodeModel();
10770 if (OpFlags == X86II::MO_NO_FLAG &&
10771 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10772 // A direct static reference to a global.
10773 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10776 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10779 if (Subtarget->isPICStyleRIPRel() &&
10780 (M == CodeModel::Small || M == CodeModel::Kernel))
10781 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10783 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10785 // With PIC, the address is actually $g + Offset.
10786 if (isGlobalRelativeToPICBase(OpFlags)) {
10787 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10788 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10792 // For globals that require a load from a stub to get the address, emit the
10794 if (isGlobalStubReference(OpFlags))
10795 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10796 MachinePointerInfo::getGOT(), false, false, false, 0);
10798 // If there was a non-zero offset that we didn't fold, create an explicit
10799 // addition for it.
10801 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10802 DAG.getConstant(Offset, getPointerTy()));
10808 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10809 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10810 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10811 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10815 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10816 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10817 unsigned char OperandFlags, bool LocalDynamic = false) {
10818 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10819 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10821 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10822 GA->getValueType(0),
10826 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10830 SDValue Ops[] = { Chain, TGA, *InFlag };
10831 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10833 SDValue Ops[] = { Chain, TGA };
10834 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10837 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10838 MFI->setAdjustsStack(true);
10839 MFI->setHasCalls(true);
10841 SDValue Flag = Chain.getValue(1);
10842 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10845 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10847 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10850 SDLoc dl(GA); // ? function entry point might be better
10851 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10852 DAG.getNode(X86ISD::GlobalBaseReg,
10853 SDLoc(), PtrVT), InFlag);
10854 InFlag = Chain.getValue(1);
10856 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10859 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10861 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10863 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10864 X86::RAX, X86II::MO_TLSGD);
10867 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10873 // Get the start address of the TLS block for this module.
10874 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10875 .getInfo<X86MachineFunctionInfo>();
10876 MFI->incNumLocalDynamicTLSAccesses();
10880 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10881 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10884 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10885 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10886 InFlag = Chain.getValue(1);
10887 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10888 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10891 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10895 unsigned char OperandFlags = X86II::MO_DTPOFF;
10896 unsigned WrapperKind = X86ISD::Wrapper;
10897 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10898 GA->getValueType(0),
10899 GA->getOffset(), OperandFlags);
10900 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10902 // Add x@dtpoff with the base.
10903 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10906 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10907 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10908 const EVT PtrVT, TLSModel::Model model,
10909 bool is64Bit, bool isPIC) {
10912 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10913 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10914 is64Bit ? 257 : 256));
10916 SDValue ThreadPointer =
10917 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10918 MachinePointerInfo(Ptr), false, false, false, 0);
10920 unsigned char OperandFlags = 0;
10921 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10923 unsigned WrapperKind = X86ISD::Wrapper;
10924 if (model == TLSModel::LocalExec) {
10925 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10926 } else if (model == TLSModel::InitialExec) {
10928 OperandFlags = X86II::MO_GOTTPOFF;
10929 WrapperKind = X86ISD::WrapperRIP;
10931 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10934 llvm_unreachable("Unexpected model");
10937 // emit "addl x@ntpoff,%eax" (local exec)
10938 // or "addl x@indntpoff,%eax" (initial exec)
10939 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10941 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10942 GA->getOffset(), OperandFlags);
10943 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10945 if (model == TLSModel::InitialExec) {
10946 if (isPIC && !is64Bit) {
10947 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10948 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10952 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10953 MachinePointerInfo::getGOT(), false, false, false, 0);
10956 // The address of the thread local variable is the add of the thread
10957 // pointer with the offset of the variable.
10958 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10962 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10964 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10965 const GlobalValue *GV = GA->getGlobal();
10967 if (Subtarget->isTargetELF()) {
10968 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10971 case TLSModel::GeneralDynamic:
10972 if (Subtarget->is64Bit())
10973 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10974 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10975 case TLSModel::LocalDynamic:
10976 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10977 Subtarget->is64Bit());
10978 case TLSModel::InitialExec:
10979 case TLSModel::LocalExec:
10980 return LowerToTLSExecModel(
10981 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10982 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10984 llvm_unreachable("Unknown TLS model.");
10987 if (Subtarget->isTargetDarwin()) {
10988 // Darwin only has one model of TLS. Lower to that.
10989 unsigned char OpFlag = 0;
10990 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10991 X86ISD::WrapperRIP : X86ISD::Wrapper;
10993 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10994 // global base reg.
10995 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10996 !Subtarget->is64Bit();
10998 OpFlag = X86II::MO_TLVP_PIC_BASE;
11000 OpFlag = X86II::MO_TLVP;
11002 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11003 GA->getValueType(0),
11004 GA->getOffset(), OpFlag);
11005 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11007 // With PIC32, the address is actually $g + Offset.
11009 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11010 DAG.getNode(X86ISD::GlobalBaseReg,
11011 SDLoc(), getPointerTy()),
11014 // Lowering the machine isd will make sure everything is in the right
11016 SDValue Chain = DAG.getEntryNode();
11017 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11018 SDValue Args[] = { Chain, Offset };
11019 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11021 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11022 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11023 MFI->setAdjustsStack(true);
11025 // And our return value (tls address) is in the standard call return value
11027 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11028 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11029 Chain.getValue(1));
11032 if (Subtarget->isTargetKnownWindowsMSVC() ||
11033 Subtarget->isTargetWindowsGNU()) {
11034 // Just use the implicit TLS architecture
11035 // Need to generate someting similar to:
11036 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11038 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11039 // mov rcx, qword [rdx+rcx*8]
11040 // mov eax, .tls$:tlsvar
11041 // [rax+rcx] contains the address
11042 // Windows 64bit: gs:0x58
11043 // Windows 32bit: fs:__tls_array
11046 SDValue Chain = DAG.getEntryNode();
11048 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11049 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11050 // use its literal value of 0x2C.
11051 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11052 ? Type::getInt8PtrTy(*DAG.getContext(),
11054 : Type::getInt32PtrTy(*DAG.getContext(),
11058 Subtarget->is64Bit()
11059 ? DAG.getIntPtrConstant(0x58)
11060 : (Subtarget->isTargetWindowsGNU()
11061 ? DAG.getIntPtrConstant(0x2C)
11062 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11064 SDValue ThreadPointer =
11065 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11066 MachinePointerInfo(Ptr), false, false, false, 0);
11068 // Load the _tls_index variable
11069 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11070 if (Subtarget->is64Bit())
11071 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11072 IDX, MachinePointerInfo(), MVT::i32,
11073 false, false, false, 0);
11075 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11076 false, false, false, 0);
11078 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11080 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11082 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11083 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11084 false, false, false, 0);
11086 // Get the offset of start of .tls section
11087 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11088 GA->getValueType(0),
11089 GA->getOffset(), X86II::MO_SECREL);
11090 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11092 // The address of the thread local variable is the add of the thread
11093 // pointer with the offset of the variable.
11094 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11097 llvm_unreachable("TLS not implemented for this target.");
11100 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11101 /// and take a 2 x i32 value to shift plus a shift amount.
11102 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11103 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11104 MVT VT = Op.getSimpleValueType();
11105 unsigned VTBits = VT.getSizeInBits();
11107 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11108 SDValue ShOpLo = Op.getOperand(0);
11109 SDValue ShOpHi = Op.getOperand(1);
11110 SDValue ShAmt = Op.getOperand(2);
11111 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11112 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11114 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11115 DAG.getConstant(VTBits - 1, MVT::i8));
11116 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11117 DAG.getConstant(VTBits - 1, MVT::i8))
11118 : DAG.getConstant(0, VT);
11120 SDValue Tmp2, Tmp3;
11121 if (Op.getOpcode() == ISD::SHL_PARTS) {
11122 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11123 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11125 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11126 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11129 // If the shift amount is larger or equal than the width of a part we can't
11130 // rely on the results of shld/shrd. Insert a test and select the appropriate
11131 // values for large shift amounts.
11132 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11133 DAG.getConstant(VTBits, MVT::i8));
11134 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11135 AndNode, DAG.getConstant(0, MVT::i8));
11138 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11139 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11140 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11142 if (Op.getOpcode() == ISD::SHL_PARTS) {
11143 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11144 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11146 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11147 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11150 SDValue Ops[2] = { Lo, Hi };
11151 return DAG.getMergeValues(Ops, dl);
11154 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11155 SelectionDAG &DAG) const {
11156 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11159 if (SrcVT.isVector()) {
11160 if (SrcVT.getVectorElementType() == MVT::i1) {
11161 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11162 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11163 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11164 Op.getOperand(0)));
11169 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11170 "Unknown SINT_TO_FP to lower!");
11172 // These are really Legal; return the operand so the caller accepts it as
11174 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11176 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11177 Subtarget->is64Bit()) {
11181 unsigned Size = SrcVT.getSizeInBits()/8;
11182 MachineFunction &MF = DAG.getMachineFunction();
11183 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11184 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11185 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11187 MachinePointerInfo::getFixedStack(SSFI),
11189 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11192 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11194 SelectionDAG &DAG) const {
11198 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11200 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11202 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11204 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11206 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11207 MachineMemOperand *MMO;
11209 int SSFI = FI->getIndex();
11211 DAG.getMachineFunction()
11212 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11213 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11215 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11216 StackSlot = StackSlot.getOperand(1);
11218 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11219 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11221 Tys, Ops, SrcVT, MMO);
11224 Chain = Result.getValue(1);
11225 SDValue InFlag = Result.getValue(2);
11227 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11228 // shouldn't be necessary except that RFP cannot be live across
11229 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11230 MachineFunction &MF = DAG.getMachineFunction();
11231 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11232 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11233 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11234 Tys = DAG.getVTList(MVT::Other);
11236 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11238 MachineMemOperand *MMO =
11239 DAG.getMachineFunction()
11240 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11241 MachineMemOperand::MOStore, SSFISize, SSFISize);
11243 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11244 Ops, Op.getValueType(), MMO);
11245 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11246 MachinePointerInfo::getFixedStack(SSFI),
11247 false, false, false, 0);
11253 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11254 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11255 SelectionDAG &DAG) const {
11256 // This algorithm is not obvious. Here it is what we're trying to output:
11259 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11260 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11262 haddpd %xmm0, %xmm0
11264 pshufd $0x4e, %xmm0, %xmm1
11270 LLVMContext *Context = DAG.getContext();
11272 // Build some magic constants.
11273 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11274 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11275 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11277 SmallVector<Constant*,2> CV1;
11279 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11280 APInt(64, 0x4330000000000000ULL))));
11282 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11283 APInt(64, 0x4530000000000000ULL))));
11284 Constant *C1 = ConstantVector::get(CV1);
11285 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11287 // Load the 64-bit value into an XMM register.
11288 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11290 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11291 MachinePointerInfo::getConstantPool(),
11292 false, false, false, 16);
11293 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11294 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11297 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11298 MachinePointerInfo::getConstantPool(),
11299 false, false, false, 16);
11300 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11301 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11304 if (Subtarget->hasSSE3()) {
11305 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11306 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11308 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11309 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11311 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11312 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11316 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11317 DAG.getIntPtrConstant(0));
11320 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11321 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11322 SelectionDAG &DAG) const {
11324 // FP constant to bias correct the final result.
11325 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11328 // Load the 32-bit value into an XMM register.
11329 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11332 // Zero out the upper parts of the register.
11333 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11335 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11336 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11337 DAG.getIntPtrConstant(0));
11339 // Or the load with the bias.
11340 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11341 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11342 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11343 MVT::v2f64, Load)),
11344 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11345 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11346 MVT::v2f64, Bias)));
11347 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11348 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11349 DAG.getIntPtrConstant(0));
11351 // Subtract the bias.
11352 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11354 // Handle final rounding.
11355 EVT DestVT = Op.getValueType();
11357 if (DestVT.bitsLT(MVT::f64))
11358 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11359 DAG.getIntPtrConstant(0));
11360 if (DestVT.bitsGT(MVT::f64))
11361 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11363 // Handle final rounding.
11367 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11368 const X86Subtarget &Subtarget) {
11369 // The algorithm is the following:
11370 // #ifdef __SSE4_1__
11371 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11372 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11373 // (uint4) 0x53000000, 0xaa);
11375 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11376 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11378 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11379 // return (float4) lo + fhi;
11382 SDValue V = Op->getOperand(0);
11383 EVT VecIntVT = V.getValueType();
11384 bool Is128 = VecIntVT == MVT::v4i32;
11385 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11386 // If we convert to something else than the supported type, e.g., to v4f64,
11388 if (VecFloatVT != Op->getValueType(0))
11391 unsigned NumElts = VecIntVT.getVectorNumElements();
11392 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11393 "Unsupported custom type");
11394 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11396 // In the #idef/#else code, we have in common:
11397 // - The vector of constants:
11403 // Create the splat vector for 0x4b000000.
11404 SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11405 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11406 CstLow, CstLow, CstLow, CstLow};
11407 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11408 makeArrayRef(&CstLowArray[0], NumElts));
11409 // Create the splat vector for 0x53000000.
11410 SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11411 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11412 CstHigh, CstHigh, CstHigh, CstHigh};
11413 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11414 makeArrayRef(&CstHighArray[0], NumElts));
11416 // Create the right shift.
11417 SDValue CstShift = DAG.getConstant(16, MVT::i32);
11418 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11419 CstShift, CstShift, CstShift, CstShift};
11420 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11421 makeArrayRef(&CstShiftArray[0], NumElts));
11422 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11425 if (Subtarget.hasSSE41()) {
11426 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11427 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11428 SDValue VecCstLowBitcast =
11429 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11430 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11431 // Low will be bitcasted right away, so do not bother bitcasting back to its
11433 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11434 VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11435 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11436 // (uint4) 0x53000000, 0xaa);
11437 SDValue VecCstHighBitcast =
11438 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11439 SDValue VecShiftBitcast =
11440 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11441 // High will be bitcasted right away, so do not bother bitcasting back to
11442 // its original type.
11443 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11444 VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11446 SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11447 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11448 CstMask, CstMask, CstMask);
11449 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11450 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11451 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11453 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11454 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11457 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11458 SDValue CstFAdd = DAG.getConstantFP(
11459 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11460 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11461 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11462 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11463 makeArrayRef(&CstFAddArray[0], NumElts));
11465 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11466 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11468 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11469 // return (float4) lo + fhi;
11470 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11471 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11474 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11475 SelectionDAG &DAG) const {
11476 SDValue N0 = Op.getOperand(0);
11477 MVT SVT = N0.getSimpleValueType();
11480 switch (SVT.SimpleTy) {
11482 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11487 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11488 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11489 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11493 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11495 llvm_unreachable(nullptr);
11498 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11499 SelectionDAG &DAG) const {
11500 SDValue N0 = Op.getOperand(0);
11503 if (Op.getValueType().isVector())
11504 return lowerUINT_TO_FP_vec(Op, DAG);
11506 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11507 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11508 // the optimization here.
11509 if (DAG.SignBitIsZero(N0))
11510 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11512 MVT SrcVT = N0.getSimpleValueType();
11513 MVT DstVT = Op.getSimpleValueType();
11514 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11515 return LowerUINT_TO_FP_i64(Op, DAG);
11516 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11517 return LowerUINT_TO_FP_i32(Op, DAG);
11518 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11521 // Make a 64-bit buffer, and use it to build an FILD.
11522 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11523 if (SrcVT == MVT::i32) {
11524 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11525 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11526 getPointerTy(), StackSlot, WordOff);
11527 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11528 StackSlot, MachinePointerInfo(),
11530 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11531 OffsetSlot, MachinePointerInfo(),
11533 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11537 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11538 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11539 StackSlot, MachinePointerInfo(),
11541 // For i64 source, we need to add the appropriate power of 2 if the input
11542 // was negative. This is the same as the optimization in
11543 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11544 // we must be careful to do the computation in x87 extended precision, not
11545 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11546 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11547 MachineMemOperand *MMO =
11548 DAG.getMachineFunction()
11549 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11550 MachineMemOperand::MOLoad, 8, 8);
11552 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11553 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11554 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11557 APInt FF(32, 0x5F800000ULL);
11559 // Check whether the sign bit is set.
11560 SDValue SignSet = DAG.getSetCC(dl,
11561 getSetCCResultType(*DAG.getContext(), MVT::i64),
11562 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11565 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11566 SDValue FudgePtr = DAG.getConstantPool(
11567 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11570 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11571 SDValue Zero = DAG.getIntPtrConstant(0);
11572 SDValue Four = DAG.getIntPtrConstant(4);
11573 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11575 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11577 // Load the value out, extending it from f32 to f80.
11578 // FIXME: Avoid the extend by constructing the right constant pool?
11579 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11580 FudgePtr, MachinePointerInfo::getConstantPool(),
11581 MVT::f32, false, false, false, 4);
11582 // Extend everything to 80 bits to force it to be done on x87.
11583 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11584 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11587 std::pair<SDValue,SDValue>
11588 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11589 bool IsSigned, bool IsReplace) const {
11592 EVT DstTy = Op.getValueType();
11594 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11595 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11599 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11600 DstTy.getSimpleVT() >= MVT::i16 &&
11601 "Unknown FP_TO_INT to lower!");
11603 // These are really Legal.
11604 if (DstTy == MVT::i32 &&
11605 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11606 return std::make_pair(SDValue(), SDValue());
11607 if (Subtarget->is64Bit() &&
11608 DstTy == MVT::i64 &&
11609 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11610 return std::make_pair(SDValue(), SDValue());
11612 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11613 // stack slot, or into the FTOL runtime function.
11614 MachineFunction &MF = DAG.getMachineFunction();
11615 unsigned MemSize = DstTy.getSizeInBits()/8;
11616 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11617 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11620 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11621 Opc = X86ISD::WIN_FTOL;
11623 switch (DstTy.getSimpleVT().SimpleTy) {
11624 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11625 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11626 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11627 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11630 SDValue Chain = DAG.getEntryNode();
11631 SDValue Value = Op.getOperand(0);
11632 EVT TheVT = Op.getOperand(0).getValueType();
11633 // FIXME This causes a redundant load/store if the SSE-class value is already
11634 // in memory, such as if it is on the callstack.
11635 if (isScalarFPTypeInSSEReg(TheVT)) {
11636 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11637 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11638 MachinePointerInfo::getFixedStack(SSFI),
11640 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11642 Chain, StackSlot, DAG.getValueType(TheVT)
11645 MachineMemOperand *MMO =
11646 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11647 MachineMemOperand::MOLoad, MemSize, MemSize);
11648 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11649 Chain = Value.getValue(1);
11650 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11651 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11654 MachineMemOperand *MMO =
11655 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11656 MachineMemOperand::MOStore, MemSize, MemSize);
11658 if (Opc != X86ISD::WIN_FTOL) {
11659 // Build the FP_TO_INT*_IN_MEM
11660 SDValue Ops[] = { Chain, Value, StackSlot };
11661 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11663 return std::make_pair(FIST, StackSlot);
11665 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11666 DAG.getVTList(MVT::Other, MVT::Glue),
11668 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11669 MVT::i32, ftol.getValue(1));
11670 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11671 MVT::i32, eax.getValue(2));
11672 SDValue Ops[] = { eax, edx };
11673 SDValue pair = IsReplace
11674 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11675 : DAG.getMergeValues(Ops, DL);
11676 return std::make_pair(pair, SDValue());
11680 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11681 const X86Subtarget *Subtarget) {
11682 MVT VT = Op->getSimpleValueType(0);
11683 SDValue In = Op->getOperand(0);
11684 MVT InVT = In.getSimpleValueType();
11687 // Optimize vectors in AVX mode:
11690 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11691 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11692 // Concat upper and lower parts.
11695 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11696 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11697 // Concat upper and lower parts.
11700 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11701 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11702 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11705 if (Subtarget->hasInt256())
11706 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11708 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11709 SDValue Undef = DAG.getUNDEF(InVT);
11710 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11711 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11712 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11714 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11715 VT.getVectorNumElements()/2);
11717 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11718 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11720 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11723 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11724 SelectionDAG &DAG) {
11725 MVT VT = Op->getSimpleValueType(0);
11726 SDValue In = Op->getOperand(0);
11727 MVT InVT = In.getSimpleValueType();
11729 unsigned int NumElts = VT.getVectorNumElements();
11730 if (NumElts != 8 && NumElts != 16)
11733 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11734 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11736 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11738 // Now we have only mask extension
11739 assert(InVT.getVectorElementType() == MVT::i1);
11740 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11741 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11742 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11743 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11744 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11745 MachinePointerInfo::getConstantPool(),
11746 false, false, false, Alignment);
11748 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11749 if (VT.is512BitVector())
11751 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11754 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11755 SelectionDAG &DAG) {
11756 if (Subtarget->hasFp256()) {
11757 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11765 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11766 SelectionDAG &DAG) {
11768 MVT VT = Op.getSimpleValueType();
11769 SDValue In = Op.getOperand(0);
11770 MVT SVT = In.getSimpleValueType();
11772 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11773 return LowerZERO_EXTEND_AVX512(Op, DAG);
11775 if (Subtarget->hasFp256()) {
11776 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11781 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11782 VT.getVectorNumElements() != SVT.getVectorNumElements());
11786 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11788 MVT VT = Op.getSimpleValueType();
11789 SDValue In = Op.getOperand(0);
11790 MVT InVT = In.getSimpleValueType();
11792 if (VT == MVT::i1) {
11793 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11794 "Invalid scalar TRUNCATE operation");
11795 if (InVT.getSizeInBits() >= 32)
11797 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11798 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11800 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11801 "Invalid TRUNCATE operation");
11803 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11804 if (VT.getVectorElementType().getSizeInBits() >=8)
11805 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11807 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11808 unsigned NumElts = InVT.getVectorNumElements();
11809 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11810 if (InVT.getSizeInBits() < 512) {
11811 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11812 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11816 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11817 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11818 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11819 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11820 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11821 MachinePointerInfo::getConstantPool(),
11822 false, false, false, Alignment);
11823 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11824 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11825 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11828 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11829 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11830 if (Subtarget->hasInt256()) {
11831 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11832 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11833 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11835 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11836 DAG.getIntPtrConstant(0));
11839 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11840 DAG.getIntPtrConstant(0));
11841 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11842 DAG.getIntPtrConstant(2));
11843 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11844 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11845 static const int ShufMask[] = {0, 2, 4, 6};
11846 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11849 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11850 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11851 if (Subtarget->hasInt256()) {
11852 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11854 SmallVector<SDValue,32> pshufbMask;
11855 for (unsigned i = 0; i < 2; ++i) {
11856 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11857 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11858 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11859 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11860 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11861 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11862 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11863 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11864 for (unsigned j = 0; j < 8; ++j)
11865 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11867 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11868 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11869 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11871 static const int ShufMask[] = {0, 2, -1, -1};
11872 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11874 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11875 DAG.getIntPtrConstant(0));
11876 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11879 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11880 DAG.getIntPtrConstant(0));
11882 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11883 DAG.getIntPtrConstant(4));
11885 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11886 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11888 // The PSHUFB mask:
11889 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11890 -1, -1, -1, -1, -1, -1, -1, -1};
11892 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11893 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11894 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11896 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11897 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11899 // The MOVLHPS Mask:
11900 static const int ShufMask2[] = {0, 1, 4, 5};
11901 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11902 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11905 // Handle truncation of V256 to V128 using shuffles.
11906 if (!VT.is128BitVector() || !InVT.is256BitVector())
11909 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11911 unsigned NumElems = VT.getVectorNumElements();
11912 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11914 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11915 // Prepare truncation shuffle mask
11916 for (unsigned i = 0; i != NumElems; ++i)
11917 MaskVec[i] = i * 2;
11918 SDValue V = DAG.getVectorShuffle(NVT, DL,
11919 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11920 DAG.getUNDEF(NVT), &MaskVec[0]);
11921 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11922 DAG.getIntPtrConstant(0));
11925 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11926 SelectionDAG &DAG) const {
11927 assert(!Op.getSimpleValueType().isVector());
11929 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11930 /*IsSigned=*/ true, /*IsReplace=*/ false);
11931 SDValue FIST = Vals.first, StackSlot = Vals.second;
11932 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11933 if (!FIST.getNode()) return Op;
11935 if (StackSlot.getNode())
11936 // Load the result.
11937 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11938 FIST, StackSlot, MachinePointerInfo(),
11939 false, false, false, 0);
11941 // The node is the result.
11945 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11946 SelectionDAG &DAG) const {
11947 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11948 /*IsSigned=*/ false, /*IsReplace=*/ false);
11949 SDValue FIST = Vals.first, StackSlot = Vals.second;
11950 assert(FIST.getNode() && "Unexpected failure");
11952 if (StackSlot.getNode())
11953 // Load the result.
11954 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11955 FIST, StackSlot, MachinePointerInfo(),
11956 false, false, false, 0);
11958 // The node is the result.
11962 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11964 MVT VT = Op.getSimpleValueType();
11965 SDValue In = Op.getOperand(0);
11966 MVT SVT = In.getSimpleValueType();
11968 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11970 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11971 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11972 In, DAG.getUNDEF(SVT)));
11975 /// The only differences between FABS and FNEG are the mask and the logic op.
11976 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
11977 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
11978 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
11979 "Wrong opcode for lowering FABS or FNEG.");
11981 bool IsFABS = (Op.getOpcode() == ISD::FABS);
11983 // If this is a FABS and it has an FNEG user, bail out to fold the combination
11984 // into an FNABS. We'll lower the FABS after that if it is still in use.
11986 for (SDNode *User : Op->uses())
11987 if (User->getOpcode() == ISD::FNEG)
11990 SDValue Op0 = Op.getOperand(0);
11991 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
11994 MVT VT = Op.getSimpleValueType();
11995 // Assume scalar op for initialization; update for vector if needed.
11996 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
11997 // generate a 16-byte vector constant and logic op even for the scalar case.
11998 // Using a 16-byte mask allows folding the load of the mask with
11999 // the logic op, so it can save (~4 bytes) on code size.
12001 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12002 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12003 // decide if we should generate a 16-byte constant mask when we only need 4 or
12004 // 8 bytes for the scalar case.
12005 if (VT.isVector()) {
12006 EltVT = VT.getVectorElementType();
12007 NumElts = VT.getVectorNumElements();
12010 unsigned EltBits = EltVT.getSizeInBits();
12011 LLVMContext *Context = DAG.getContext();
12012 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12014 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12015 Constant *C = ConstantInt::get(*Context, MaskElt);
12016 C = ConstantVector::getSplat(NumElts, C);
12017 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12018 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12019 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12020 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12021 MachinePointerInfo::getConstantPool(),
12022 false, false, false, Alignment);
12024 if (VT.isVector()) {
12025 // For a vector, cast operands to a vector type, perform the logic op,
12026 // and cast the result back to the original value type.
12027 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12028 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12029 SDValue Operand = IsFNABS ?
12030 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12031 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12032 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12033 return DAG.getNode(ISD::BITCAST, dl, VT,
12034 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12037 // If not vector, then scalar.
12038 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12039 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12040 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12043 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12044 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12045 LLVMContext *Context = DAG.getContext();
12046 SDValue Op0 = Op.getOperand(0);
12047 SDValue Op1 = Op.getOperand(1);
12049 MVT VT = Op.getSimpleValueType();
12050 MVT SrcVT = Op1.getSimpleValueType();
12052 // If second operand is smaller, extend it first.
12053 if (SrcVT.bitsLT(VT)) {
12054 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12057 // And if it is bigger, shrink it first.
12058 if (SrcVT.bitsGT(VT)) {
12059 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12063 // At this point the operands and the result should have the same
12064 // type, and that won't be f80 since that is not custom lowered.
12066 const fltSemantics &Sem =
12067 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12068 const unsigned SizeInBits = VT.getSizeInBits();
12070 SmallVector<Constant *, 4> CV(
12071 VT == MVT::f64 ? 2 : 4,
12072 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12074 // First, clear all bits but the sign bit from the second operand (sign).
12075 CV[0] = ConstantFP::get(*Context,
12076 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12077 Constant *C = ConstantVector::get(CV);
12078 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12079 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12080 MachinePointerInfo::getConstantPool(),
12081 false, false, false, 16);
12082 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12084 // Next, clear the sign bit from the first operand (magnitude).
12085 // If it's a constant, we can clear it here.
12086 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12087 APFloat APF = Op0CN->getValueAPF();
12088 // If the magnitude is a positive zero, the sign bit alone is enough.
12089 if (APF.isPosZero())
12092 CV[0] = ConstantFP::get(*Context, APF);
12094 CV[0] = ConstantFP::get(
12096 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12098 C = ConstantVector::get(CV);
12099 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12100 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12101 MachinePointerInfo::getConstantPool(),
12102 false, false, false, 16);
12103 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12104 if (!isa<ConstantFPSDNode>(Op0))
12105 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12107 // OR the magnitude value with the sign bit.
12108 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12111 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12112 SDValue N0 = Op.getOperand(0);
12114 MVT VT = Op.getSimpleValueType();
12116 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12117 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12118 DAG.getConstant(1, VT));
12119 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12122 // Check whether an OR'd tree is PTEST-able.
12123 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12124 SelectionDAG &DAG) {
12125 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12127 if (!Subtarget->hasSSE41())
12130 if (!Op->hasOneUse())
12133 SDNode *N = Op.getNode();
12136 SmallVector<SDValue, 8> Opnds;
12137 DenseMap<SDValue, unsigned> VecInMap;
12138 SmallVector<SDValue, 8> VecIns;
12139 EVT VT = MVT::Other;
12141 // Recognize a special case where a vector is casted into wide integer to
12143 Opnds.push_back(N->getOperand(0));
12144 Opnds.push_back(N->getOperand(1));
12146 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12147 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12148 // BFS traverse all OR'd operands.
12149 if (I->getOpcode() == ISD::OR) {
12150 Opnds.push_back(I->getOperand(0));
12151 Opnds.push_back(I->getOperand(1));
12152 // Re-evaluate the number of nodes to be traversed.
12153 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12157 // Quit if a non-EXTRACT_VECTOR_ELT
12158 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12161 // Quit if without a constant index.
12162 SDValue Idx = I->getOperand(1);
12163 if (!isa<ConstantSDNode>(Idx))
12166 SDValue ExtractedFromVec = I->getOperand(0);
12167 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12168 if (M == VecInMap.end()) {
12169 VT = ExtractedFromVec.getValueType();
12170 // Quit if not 128/256-bit vector.
12171 if (!VT.is128BitVector() && !VT.is256BitVector())
12173 // Quit if not the same type.
12174 if (VecInMap.begin() != VecInMap.end() &&
12175 VT != VecInMap.begin()->first.getValueType())
12177 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12178 VecIns.push_back(ExtractedFromVec);
12180 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12183 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12184 "Not extracted from 128-/256-bit vector.");
12186 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12188 for (DenseMap<SDValue, unsigned>::const_iterator
12189 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12190 // Quit if not all elements are used.
12191 if (I->second != FullMask)
12195 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12197 // Cast all vectors into TestVT for PTEST.
12198 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12199 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12201 // If more than one full vectors are evaluated, OR them first before PTEST.
12202 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12203 // Each iteration will OR 2 nodes and append the result until there is only
12204 // 1 node left, i.e. the final OR'd value of all vectors.
12205 SDValue LHS = VecIns[Slot];
12206 SDValue RHS = VecIns[Slot + 1];
12207 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12210 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12211 VecIns.back(), VecIns.back());
12214 /// \brief return true if \c Op has a use that doesn't just read flags.
12215 static bool hasNonFlagsUse(SDValue Op) {
12216 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12218 SDNode *User = *UI;
12219 unsigned UOpNo = UI.getOperandNo();
12220 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12221 // Look pass truncate.
12222 UOpNo = User->use_begin().getOperandNo();
12223 User = *User->use_begin();
12226 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12227 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12233 /// Emit nodes that will be selected as "test Op0,Op0", or something
12235 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12236 SelectionDAG &DAG) const {
12237 if (Op.getValueType() == MVT::i1) {
12238 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12239 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12240 DAG.getConstant(0, MVT::i8));
12242 // CF and OF aren't always set the way we want. Determine which
12243 // of these we need.
12244 bool NeedCF = false;
12245 bool NeedOF = false;
12248 case X86::COND_A: case X86::COND_AE:
12249 case X86::COND_B: case X86::COND_BE:
12252 case X86::COND_G: case X86::COND_GE:
12253 case X86::COND_L: case X86::COND_LE:
12254 case X86::COND_O: case X86::COND_NO: {
12255 // Check if we really need to set the
12256 // Overflow flag. If NoSignedWrap is present
12257 // that is not actually needed.
12258 switch (Op->getOpcode()) {
12263 const BinaryWithFlagsSDNode *BinNode =
12264 cast<BinaryWithFlagsSDNode>(Op.getNode());
12265 if (BinNode->hasNoSignedWrap())
12275 // See if we can use the EFLAGS value from the operand instead of
12276 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12277 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12278 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12279 // Emit a CMP with 0, which is the TEST pattern.
12280 //if (Op.getValueType() == MVT::i1)
12281 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12282 // DAG.getConstant(0, MVT::i1));
12283 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12284 DAG.getConstant(0, Op.getValueType()));
12286 unsigned Opcode = 0;
12287 unsigned NumOperands = 0;
12289 // Truncate operations may prevent the merge of the SETCC instruction
12290 // and the arithmetic instruction before it. Attempt to truncate the operands
12291 // of the arithmetic instruction and use a reduced bit-width instruction.
12292 bool NeedTruncation = false;
12293 SDValue ArithOp = Op;
12294 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12295 SDValue Arith = Op->getOperand(0);
12296 // Both the trunc and the arithmetic op need to have one user each.
12297 if (Arith->hasOneUse())
12298 switch (Arith.getOpcode()) {
12305 NeedTruncation = true;
12311 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12312 // which may be the result of a CAST. We use the variable 'Op', which is the
12313 // non-casted variable when we check for possible users.
12314 switch (ArithOp.getOpcode()) {
12316 // Due to an isel shortcoming, be conservative if this add is likely to be
12317 // selected as part of a load-modify-store instruction. When the root node
12318 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12319 // uses of other nodes in the match, such as the ADD in this case. This
12320 // leads to the ADD being left around and reselected, with the result being
12321 // two adds in the output. Alas, even if none our users are stores, that
12322 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12323 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12324 // climbing the DAG back to the root, and it doesn't seem to be worth the
12326 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12327 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12328 if (UI->getOpcode() != ISD::CopyToReg &&
12329 UI->getOpcode() != ISD::SETCC &&
12330 UI->getOpcode() != ISD::STORE)
12333 if (ConstantSDNode *C =
12334 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12335 // An add of one will be selected as an INC.
12336 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12337 Opcode = X86ISD::INC;
12342 // An add of negative one (subtract of one) will be selected as a DEC.
12343 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12344 Opcode = X86ISD::DEC;
12350 // Otherwise use a regular EFLAGS-setting add.
12351 Opcode = X86ISD::ADD;
12356 // If we have a constant logical shift that's only used in a comparison
12357 // against zero turn it into an equivalent AND. This allows turning it into
12358 // a TEST instruction later.
12359 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12360 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12361 EVT VT = Op.getValueType();
12362 unsigned BitWidth = VT.getSizeInBits();
12363 unsigned ShAmt = Op->getConstantOperandVal(1);
12364 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12366 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12367 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12368 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12369 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12371 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12372 DAG.getConstant(Mask, VT));
12373 DAG.ReplaceAllUsesWith(Op, New);
12379 // If the primary and result isn't used, don't bother using X86ISD::AND,
12380 // because a TEST instruction will be better.
12381 if (!hasNonFlagsUse(Op))
12387 // Due to the ISEL shortcoming noted above, be conservative if this op is
12388 // likely to be selected as part of a load-modify-store instruction.
12389 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12390 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12391 if (UI->getOpcode() == ISD::STORE)
12394 // Otherwise use a regular EFLAGS-setting instruction.
12395 switch (ArithOp.getOpcode()) {
12396 default: llvm_unreachable("unexpected operator!");
12397 case ISD::SUB: Opcode = X86ISD::SUB; break;
12398 case ISD::XOR: Opcode = X86ISD::XOR; break;
12399 case ISD::AND: Opcode = X86ISD::AND; break;
12401 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12402 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12403 if (EFLAGS.getNode())
12406 Opcode = X86ISD::OR;
12420 return SDValue(Op.getNode(), 1);
12426 // If we found that truncation is beneficial, perform the truncation and
12428 if (NeedTruncation) {
12429 EVT VT = Op.getValueType();
12430 SDValue WideVal = Op->getOperand(0);
12431 EVT WideVT = WideVal.getValueType();
12432 unsigned ConvertedOp = 0;
12433 // Use a target machine opcode to prevent further DAGCombine
12434 // optimizations that may separate the arithmetic operations
12435 // from the setcc node.
12436 switch (WideVal.getOpcode()) {
12438 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12439 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12440 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12441 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12442 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12446 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12447 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12448 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12449 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12450 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12456 // Emit a CMP with 0, which is the TEST pattern.
12457 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12458 DAG.getConstant(0, Op.getValueType()));
12460 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12461 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12463 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12464 DAG.ReplaceAllUsesWith(Op, New);
12465 return SDValue(New.getNode(), 1);
12468 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12470 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12471 SDLoc dl, SelectionDAG &DAG) const {
12472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12473 if (C->getAPIntValue() == 0)
12474 return EmitTest(Op0, X86CC, dl, DAG);
12476 if (Op0.getValueType() == MVT::i1)
12477 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12480 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12481 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12482 // Do the comparison at i32 if it's smaller, besides the Atom case.
12483 // This avoids subregister aliasing issues. Keep the smaller reference
12484 // if we're optimizing for size, however, as that'll allow better folding
12485 // of memory operations.
12486 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12487 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12488 Attribute::MinSize) &&
12489 !Subtarget->isAtom()) {
12490 unsigned ExtendOp =
12491 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12492 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12493 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12495 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12496 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12497 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12499 return SDValue(Sub.getNode(), 1);
12501 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12504 /// Convert a comparison if required by the subtarget.
12505 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12506 SelectionDAG &DAG) const {
12507 // If the subtarget does not support the FUCOMI instruction, floating-point
12508 // comparisons have to be converted.
12509 if (Subtarget->hasCMov() ||
12510 Cmp.getOpcode() != X86ISD::CMP ||
12511 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12512 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12515 // The instruction selector will select an FUCOM instruction instead of
12516 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12517 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12518 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12520 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12521 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12522 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12523 DAG.getConstant(8, MVT::i8));
12524 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12525 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12528 /// The minimum architected relative accuracy is 2^-12. We need one
12529 /// Newton-Raphson step to have a good float result (24 bits of precision).
12530 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12531 DAGCombinerInfo &DCI,
12532 unsigned &RefinementSteps,
12533 bool &UseOneConstNR) const {
12534 // FIXME: We should use instruction latency models to calculate the cost of
12535 // each potential sequence, but this is very hard to do reliably because
12536 // at least Intel's Core* chips have variable timing based on the number of
12537 // significant digits in the divisor and/or sqrt operand.
12538 if (!Subtarget->useSqrtEst())
12541 EVT VT = Op.getValueType();
12543 // SSE1 has rsqrtss and rsqrtps.
12544 // TODO: Add support for AVX512 (v16f32).
12545 // It is likely not profitable to do this for f64 because a double-precision
12546 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12547 // instructions: convert to single, rsqrtss, convert back to double, refine
12548 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12549 // along with FMA, this could be a throughput win.
12550 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12551 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12552 RefinementSteps = 1;
12553 UseOneConstNR = false;
12554 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12559 /// The minimum architected relative accuracy is 2^-12. We need one
12560 /// Newton-Raphson step to have a good float result (24 bits of precision).
12561 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12562 DAGCombinerInfo &DCI,
12563 unsigned &RefinementSteps) const {
12564 // FIXME: We should use instruction latency models to calculate the cost of
12565 // each potential sequence, but this is very hard to do reliably because
12566 // at least Intel's Core* chips have variable timing based on the number of
12567 // significant digits in the divisor.
12568 if (!Subtarget->useReciprocalEst())
12571 EVT VT = Op.getValueType();
12573 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12574 // TODO: Add support for AVX512 (v16f32).
12575 // It is likely not profitable to do this for f64 because a double-precision
12576 // reciprocal estimate with refinement on x86 prior to FMA requires
12577 // 15 instructions: convert to single, rcpss, convert back to double, refine
12578 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12579 // along with FMA, this could be a throughput win.
12580 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12581 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12582 RefinementSteps = ReciprocalEstimateRefinementSteps;
12583 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12588 static bool isAllOnes(SDValue V) {
12589 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12590 return C && C->isAllOnesValue();
12593 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12594 /// if it's possible.
12595 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12596 SDLoc dl, SelectionDAG &DAG) const {
12597 SDValue Op0 = And.getOperand(0);
12598 SDValue Op1 = And.getOperand(1);
12599 if (Op0.getOpcode() == ISD::TRUNCATE)
12600 Op0 = Op0.getOperand(0);
12601 if (Op1.getOpcode() == ISD::TRUNCATE)
12602 Op1 = Op1.getOperand(0);
12605 if (Op1.getOpcode() == ISD::SHL)
12606 std::swap(Op0, Op1);
12607 if (Op0.getOpcode() == ISD::SHL) {
12608 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12609 if (And00C->getZExtValue() == 1) {
12610 // If we looked past a truncate, check that it's only truncating away
12612 unsigned BitWidth = Op0.getValueSizeInBits();
12613 unsigned AndBitWidth = And.getValueSizeInBits();
12614 if (BitWidth > AndBitWidth) {
12616 DAG.computeKnownBits(Op0, Zeros, Ones);
12617 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12621 RHS = Op0.getOperand(1);
12623 } else if (Op1.getOpcode() == ISD::Constant) {
12624 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12625 uint64_t AndRHSVal = AndRHS->getZExtValue();
12626 SDValue AndLHS = Op0;
12628 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12629 LHS = AndLHS.getOperand(0);
12630 RHS = AndLHS.getOperand(1);
12633 // Use BT if the immediate can't be encoded in a TEST instruction.
12634 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12636 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12640 if (LHS.getNode()) {
12641 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12642 // instruction. Since the shift amount is in-range-or-undefined, we know
12643 // that doing a bittest on the i32 value is ok. We extend to i32 because
12644 // the encoding for the i16 version is larger than the i32 version.
12645 // Also promote i16 to i32 for performance / code size reason.
12646 if (LHS.getValueType() == MVT::i8 ||
12647 LHS.getValueType() == MVT::i16)
12648 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12650 // If the operand types disagree, extend the shift amount to match. Since
12651 // BT ignores high bits (like shifts) we can use anyextend.
12652 if (LHS.getValueType() != RHS.getValueType())
12653 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12655 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12656 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12657 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12658 DAG.getConstant(Cond, MVT::i8), BT);
12664 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12666 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12671 // SSE Condition code mapping:
12680 switch (SetCCOpcode) {
12681 default: llvm_unreachable("Unexpected SETCC condition");
12683 case ISD::SETEQ: SSECC = 0; break;
12685 case ISD::SETGT: Swap = true; // Fallthrough
12687 case ISD::SETOLT: SSECC = 1; break;
12689 case ISD::SETGE: Swap = true; // Fallthrough
12691 case ISD::SETOLE: SSECC = 2; break;
12692 case ISD::SETUO: SSECC = 3; break;
12694 case ISD::SETNE: SSECC = 4; break;
12695 case ISD::SETULE: Swap = true; // Fallthrough
12696 case ISD::SETUGE: SSECC = 5; break;
12697 case ISD::SETULT: Swap = true; // Fallthrough
12698 case ISD::SETUGT: SSECC = 6; break;
12699 case ISD::SETO: SSECC = 7; break;
12701 case ISD::SETONE: SSECC = 8; break;
12704 std::swap(Op0, Op1);
12709 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12710 // ones, and then concatenate the result back.
12711 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12712 MVT VT = Op.getSimpleValueType();
12714 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12715 "Unsupported value type for operation");
12717 unsigned NumElems = VT.getVectorNumElements();
12719 SDValue CC = Op.getOperand(2);
12721 // Extract the LHS vectors
12722 SDValue LHS = Op.getOperand(0);
12723 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12724 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12726 // Extract the RHS vectors
12727 SDValue RHS = Op.getOperand(1);
12728 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12729 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12731 // Issue the operation on the smaller types and concatenate the result back
12732 MVT EltVT = VT.getVectorElementType();
12733 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12734 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12735 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12736 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12739 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12740 const X86Subtarget *Subtarget) {
12741 SDValue Op0 = Op.getOperand(0);
12742 SDValue Op1 = Op.getOperand(1);
12743 SDValue CC = Op.getOperand(2);
12744 MVT VT = Op.getSimpleValueType();
12747 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12748 Op.getValueType().getScalarType() == MVT::i1 &&
12749 "Cannot set masked compare for this operation");
12751 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12753 bool Unsigned = false;
12756 switch (SetCCOpcode) {
12757 default: llvm_unreachable("Unexpected SETCC condition");
12758 case ISD::SETNE: SSECC = 4; break;
12759 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12760 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12761 case ISD::SETLT: Swap = true; //fall-through
12762 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12763 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12764 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12765 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12766 case ISD::SETULE: Unsigned = true; //fall-through
12767 case ISD::SETLE: SSECC = 2; break;
12771 std::swap(Op0, Op1);
12773 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12774 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12775 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12776 DAG.getConstant(SSECC, MVT::i8));
12779 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12780 /// operand \p Op1. If non-trivial (for example because it's not constant)
12781 /// return an empty value.
12782 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12784 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12788 MVT VT = Op1.getSimpleValueType();
12789 MVT EVT = VT.getVectorElementType();
12790 unsigned n = VT.getVectorNumElements();
12791 SmallVector<SDValue, 8> ULTOp1;
12793 for (unsigned i = 0; i < n; ++i) {
12794 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12795 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12798 // Avoid underflow.
12799 APInt Val = Elt->getAPIntValue();
12803 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12806 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12809 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12810 SelectionDAG &DAG) {
12811 SDValue Op0 = Op.getOperand(0);
12812 SDValue Op1 = Op.getOperand(1);
12813 SDValue CC = Op.getOperand(2);
12814 MVT VT = Op.getSimpleValueType();
12815 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12816 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12821 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12822 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12825 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12826 unsigned Opc = X86ISD::CMPP;
12827 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12828 assert(VT.getVectorNumElements() <= 16);
12829 Opc = X86ISD::CMPM;
12831 // In the two special cases we can't handle, emit two comparisons.
12834 unsigned CombineOpc;
12835 if (SetCCOpcode == ISD::SETUEQ) {
12836 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12838 assert(SetCCOpcode == ISD::SETONE);
12839 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12842 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12843 DAG.getConstant(CC0, MVT::i8));
12844 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12845 DAG.getConstant(CC1, MVT::i8));
12846 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12848 // Handle all other FP comparisons here.
12849 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12850 DAG.getConstant(SSECC, MVT::i8));
12853 // Break 256-bit integer vector compare into smaller ones.
12854 if (VT.is256BitVector() && !Subtarget->hasInt256())
12855 return Lower256IntVSETCC(Op, DAG);
12857 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12858 EVT OpVT = Op1.getValueType();
12859 if (Subtarget->hasAVX512()) {
12860 if (Op1.getValueType().is512BitVector() ||
12861 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12862 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12863 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12865 // In AVX-512 architecture setcc returns mask with i1 elements,
12866 // But there is no compare instruction for i8 and i16 elements in KNL.
12867 // We are not talking about 512-bit operands in this case, these
12868 // types are illegal.
12870 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12871 OpVT.getVectorElementType().getSizeInBits() >= 8))
12872 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12873 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12876 // We are handling one of the integer comparisons here. Since SSE only has
12877 // GT and EQ comparisons for integer, swapping operands and multiple
12878 // operations may be required for some comparisons.
12880 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12881 bool Subus = false;
12883 switch (SetCCOpcode) {
12884 default: llvm_unreachable("Unexpected SETCC condition");
12885 case ISD::SETNE: Invert = true;
12886 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12887 case ISD::SETLT: Swap = true;
12888 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12889 case ISD::SETGE: Swap = true;
12890 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12891 Invert = true; break;
12892 case ISD::SETULT: Swap = true;
12893 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12894 FlipSigns = true; break;
12895 case ISD::SETUGE: Swap = true;
12896 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12897 FlipSigns = true; Invert = true; break;
12900 // Special case: Use min/max operations for SETULE/SETUGE
12901 MVT VET = VT.getVectorElementType();
12903 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12904 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12907 switch (SetCCOpcode) {
12909 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12910 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12913 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12916 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12917 if (!MinMax && hasSubus) {
12918 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12920 // t = psubus Op0, Op1
12921 // pcmpeq t, <0..0>
12922 switch (SetCCOpcode) {
12924 case ISD::SETULT: {
12925 // If the comparison is against a constant we can turn this into a
12926 // setule. With psubus, setule does not require a swap. This is
12927 // beneficial because the constant in the register is no longer
12928 // destructed as the destination so it can be hoisted out of a loop.
12929 // Only do this pre-AVX since vpcmp* is no longer destructive.
12930 if (Subtarget->hasAVX())
12932 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12933 if (ULEOp1.getNode()) {
12935 Subus = true; Invert = false; Swap = false;
12939 // Psubus is better than flip-sign because it requires no inversion.
12940 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12941 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12945 Opc = X86ISD::SUBUS;
12951 std::swap(Op0, Op1);
12953 // Check that the operation in question is available (most are plain SSE2,
12954 // but PCMPGTQ and PCMPEQQ have different requirements).
12955 if (VT == MVT::v2i64) {
12956 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12957 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12959 // First cast everything to the right type.
12960 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12961 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12963 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12964 // bits of the inputs before performing those operations. The lower
12965 // compare is always unsigned.
12968 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12970 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12971 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12972 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12973 Sign, Zero, Sign, Zero);
12975 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12976 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12978 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12979 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12980 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12982 // Create masks for only the low parts/high parts of the 64 bit integers.
12983 static const int MaskHi[] = { 1, 1, 3, 3 };
12984 static const int MaskLo[] = { 0, 0, 2, 2 };
12985 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12986 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12987 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12989 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12990 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12993 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12995 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12998 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12999 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13000 // pcmpeqd + pshufd + pand.
13001 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13003 // First cast everything to the right type.
13004 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13005 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13008 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13010 // Make sure the lower and upper halves are both all-ones.
13011 static const int Mask[] = { 1, 0, 3, 2 };
13012 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13013 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13016 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13018 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13022 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13023 // bits of the inputs before performing those operations.
13025 EVT EltVT = VT.getVectorElementType();
13026 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13027 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13028 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13031 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13033 // If the logical-not of the result is required, perform that now.
13035 Result = DAG.getNOT(dl, Result, VT);
13038 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13041 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13042 getZeroVector(VT, Subtarget, DAG, dl));
13047 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13049 MVT VT = Op.getSimpleValueType();
13051 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13053 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13054 && "SetCC type must be 8-bit or 1-bit integer");
13055 SDValue Op0 = Op.getOperand(0);
13056 SDValue Op1 = Op.getOperand(1);
13058 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13060 // Optimize to BT if possible.
13061 // Lower (X & (1 << N)) == 0 to BT(X, N).
13062 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13063 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13064 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13065 Op1.getOpcode() == ISD::Constant &&
13066 cast<ConstantSDNode>(Op1)->isNullValue() &&
13067 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13068 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13069 if (NewSetCC.getNode()) {
13071 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13076 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13078 if (Op1.getOpcode() == ISD::Constant &&
13079 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13080 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13081 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13083 // If the input is a setcc, then reuse the input setcc or use a new one with
13084 // the inverted condition.
13085 if (Op0.getOpcode() == X86ISD::SETCC) {
13086 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13087 bool Invert = (CC == ISD::SETNE) ^
13088 cast<ConstantSDNode>(Op1)->isNullValue();
13092 CCode = X86::GetOppositeBranchCondition(CCode);
13093 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13094 DAG.getConstant(CCode, MVT::i8),
13095 Op0.getOperand(1));
13097 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13101 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13102 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13103 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13105 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13106 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13109 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13110 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13111 if (X86CC == X86::COND_INVALID)
13114 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13115 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13116 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13117 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13119 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13123 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13124 static bool isX86LogicalCmp(SDValue Op) {
13125 unsigned Opc = Op.getNode()->getOpcode();
13126 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13127 Opc == X86ISD::SAHF)
13129 if (Op.getResNo() == 1 &&
13130 (Opc == X86ISD::ADD ||
13131 Opc == X86ISD::SUB ||
13132 Opc == X86ISD::ADC ||
13133 Opc == X86ISD::SBB ||
13134 Opc == X86ISD::SMUL ||
13135 Opc == X86ISD::UMUL ||
13136 Opc == X86ISD::INC ||
13137 Opc == X86ISD::DEC ||
13138 Opc == X86ISD::OR ||
13139 Opc == X86ISD::XOR ||
13140 Opc == X86ISD::AND))
13143 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13149 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13150 if (V.getOpcode() != ISD::TRUNCATE)
13153 SDValue VOp0 = V.getOperand(0);
13154 unsigned InBits = VOp0.getValueSizeInBits();
13155 unsigned Bits = V.getValueSizeInBits();
13156 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13159 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13160 bool addTest = true;
13161 SDValue Cond = Op.getOperand(0);
13162 SDValue Op1 = Op.getOperand(1);
13163 SDValue Op2 = Op.getOperand(2);
13165 EVT VT = Op1.getValueType();
13168 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13169 // are available. Otherwise fp cmovs get lowered into a less efficient branch
13170 // sequence later on.
13171 if (Cond.getOpcode() == ISD::SETCC &&
13172 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13173 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13174 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13175 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13176 int SSECC = translateX86FSETCC(
13177 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13180 if (Subtarget->hasAVX512()) {
13181 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13182 DAG.getConstant(SSECC, MVT::i8));
13183 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13185 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13186 DAG.getConstant(SSECC, MVT::i8));
13187 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13188 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13189 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13193 if (Cond.getOpcode() == ISD::SETCC) {
13194 SDValue NewCond = LowerSETCC(Cond, DAG);
13195 if (NewCond.getNode())
13199 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13200 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13201 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13202 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13203 if (Cond.getOpcode() == X86ISD::SETCC &&
13204 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13205 isZero(Cond.getOperand(1).getOperand(1))) {
13206 SDValue Cmp = Cond.getOperand(1);
13208 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13210 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13211 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13212 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13214 SDValue CmpOp0 = Cmp.getOperand(0);
13215 // Apply further optimizations for special cases
13216 // (select (x != 0), -1, 0) -> neg & sbb
13217 // (select (x == 0), 0, -1) -> neg & sbb
13218 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13219 if (YC->isNullValue() &&
13220 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13221 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13222 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13223 DAG.getConstant(0, CmpOp0.getValueType()),
13225 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13226 DAG.getConstant(X86::COND_B, MVT::i8),
13227 SDValue(Neg.getNode(), 1));
13231 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13232 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13233 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13235 SDValue Res = // Res = 0 or -1.
13236 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13237 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13239 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13240 Res = DAG.getNOT(DL, Res, Res.getValueType());
13242 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13243 if (!N2C || !N2C->isNullValue())
13244 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13249 // Look past (and (setcc_carry (cmp ...)), 1).
13250 if (Cond.getOpcode() == ISD::AND &&
13251 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13252 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13253 if (C && C->getAPIntValue() == 1)
13254 Cond = Cond.getOperand(0);
13257 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13258 // setting operand in place of the X86ISD::SETCC.
13259 unsigned CondOpcode = Cond.getOpcode();
13260 if (CondOpcode == X86ISD::SETCC ||
13261 CondOpcode == X86ISD::SETCC_CARRY) {
13262 CC = Cond.getOperand(0);
13264 SDValue Cmp = Cond.getOperand(1);
13265 unsigned Opc = Cmp.getOpcode();
13266 MVT VT = Op.getSimpleValueType();
13268 bool IllegalFPCMov = false;
13269 if (VT.isFloatingPoint() && !VT.isVector() &&
13270 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13271 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13273 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13274 Opc == X86ISD::BT) { // FIXME
13278 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13279 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13280 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13281 Cond.getOperand(0).getValueType() != MVT::i8)) {
13282 SDValue LHS = Cond.getOperand(0);
13283 SDValue RHS = Cond.getOperand(1);
13284 unsigned X86Opcode;
13287 switch (CondOpcode) {
13288 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13289 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13290 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13291 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13292 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13293 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13294 default: llvm_unreachable("unexpected overflowing operator");
13296 if (CondOpcode == ISD::UMULO)
13297 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13300 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13302 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13304 if (CondOpcode == ISD::UMULO)
13305 Cond = X86Op.getValue(2);
13307 Cond = X86Op.getValue(1);
13309 CC = DAG.getConstant(X86Cond, MVT::i8);
13314 // Look pass the truncate if the high bits are known zero.
13315 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13316 Cond = Cond.getOperand(0);
13318 // We know the result of AND is compared against zero. Try to match
13320 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13321 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13322 if (NewSetCC.getNode()) {
13323 CC = NewSetCC.getOperand(0);
13324 Cond = NewSetCC.getOperand(1);
13331 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13332 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13335 // a < b ? -1 : 0 -> RES = ~setcc_carry
13336 // a < b ? 0 : -1 -> RES = setcc_carry
13337 // a >= b ? -1 : 0 -> RES = setcc_carry
13338 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13339 if (Cond.getOpcode() == X86ISD::SUB) {
13340 Cond = ConvertCmpIfNecessary(Cond, DAG);
13341 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13343 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13344 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13345 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13346 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13347 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13348 return DAG.getNOT(DL, Res, Res.getValueType());
13353 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13354 // widen the cmov and push the truncate through. This avoids introducing a new
13355 // branch during isel and doesn't add any extensions.
13356 if (Op.getValueType() == MVT::i8 &&
13357 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13358 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13359 if (T1.getValueType() == T2.getValueType() &&
13360 // Blacklist CopyFromReg to avoid partial register stalls.
13361 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13362 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13363 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13364 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13368 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13369 // condition is true.
13370 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13371 SDValue Ops[] = { Op2, Op1, CC, Cond };
13372 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13375 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13376 SelectionDAG &DAG) {
13377 MVT VT = Op->getSimpleValueType(0);
13378 SDValue In = Op->getOperand(0);
13379 MVT InVT = In.getSimpleValueType();
13380 MVT VTElt = VT.getVectorElementType();
13381 MVT InVTElt = InVT.getVectorElementType();
13385 if ((InVTElt == MVT::i1) &&
13386 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13387 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13389 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13390 VTElt.getSizeInBits() <= 16)) ||
13392 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13393 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13395 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13396 VTElt.getSizeInBits() >= 32))))
13397 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13399 unsigned int NumElts = VT.getVectorNumElements();
13401 if (NumElts != 8 && NumElts != 16)
13404 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13405 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13406 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13407 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13411 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13413 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13414 Constant *C = ConstantInt::get(*DAG.getContext(),
13415 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13417 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13418 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13419 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13420 MachinePointerInfo::getConstantPool(),
13421 false, false, false, Alignment);
13422 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13423 if (VT.is512BitVector())
13425 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13428 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13429 SelectionDAG &DAG) {
13430 MVT VT = Op->getSimpleValueType(0);
13431 SDValue In = Op->getOperand(0);
13432 MVT InVT = In.getSimpleValueType();
13435 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13436 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13438 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13439 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13440 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13443 if (Subtarget->hasInt256())
13444 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13446 // Optimize vectors in AVX mode
13447 // Sign extend v8i16 to v8i32 and
13450 // Divide input vector into two parts
13451 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13452 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13453 // concat the vectors to original VT
13455 unsigned NumElems = InVT.getVectorNumElements();
13456 SDValue Undef = DAG.getUNDEF(InVT);
13458 SmallVector<int,8> ShufMask1(NumElems, -1);
13459 for (unsigned i = 0; i != NumElems/2; ++i)
13462 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13464 SmallVector<int,8> ShufMask2(NumElems, -1);
13465 for (unsigned i = 0; i != NumElems/2; ++i)
13466 ShufMask2[i] = i + NumElems/2;
13468 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13470 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13471 VT.getVectorNumElements()/2);
13473 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13474 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13476 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13479 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13480 // may emit an illegal shuffle but the expansion is still better than scalar
13481 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13482 // we'll emit a shuffle and a arithmetic shift.
13483 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13484 // TODO: It is possible to support ZExt by zeroing the undef values during
13485 // the shuffle phase or after the shuffle.
13486 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13487 SelectionDAG &DAG) {
13488 MVT RegVT = Op.getSimpleValueType();
13489 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13490 assert(RegVT.isInteger() &&
13491 "We only custom lower integer vector sext loads.");
13493 // Nothing useful we can do without SSE2 shuffles.
13494 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13496 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13498 EVT MemVT = Ld->getMemoryVT();
13499 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13500 unsigned RegSz = RegVT.getSizeInBits();
13502 ISD::LoadExtType Ext = Ld->getExtensionType();
13504 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13505 && "Only anyext and sext are currently implemented.");
13506 assert(MemVT != RegVT && "Cannot extend to the same type");
13507 assert(MemVT.isVector() && "Must load a vector from memory");
13509 unsigned NumElems = RegVT.getVectorNumElements();
13510 unsigned MemSz = MemVT.getSizeInBits();
13511 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13513 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13514 // The only way in which we have a legal 256-bit vector result but not the
13515 // integer 256-bit operations needed to directly lower a sextload is if we
13516 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13517 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13518 // correctly legalized. We do this late to allow the canonical form of
13519 // sextload to persist throughout the rest of the DAG combiner -- it wants
13520 // to fold together any extensions it can, and so will fuse a sign_extend
13521 // of an sextload into a sextload targeting a wider value.
13523 if (MemSz == 128) {
13524 // Just switch this to a normal load.
13525 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13526 "it must be a legal 128-bit vector "
13528 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13529 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13530 Ld->isInvariant(), Ld->getAlignment());
13532 assert(MemSz < 128 &&
13533 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13534 // Do an sext load to a 128-bit vector type. We want to use the same
13535 // number of elements, but elements half as wide. This will end up being
13536 // recursively lowered by this routine, but will succeed as we definitely
13537 // have all the necessary features if we're using AVX1.
13539 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13540 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13542 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13543 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13544 Ld->isNonTemporal(), Ld->isInvariant(),
13545 Ld->getAlignment());
13548 // Replace chain users with the new chain.
13549 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13550 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13552 // Finally, do a normal sign-extend to the desired register.
13553 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13556 // All sizes must be a power of two.
13557 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13558 "Non-power-of-two elements are not custom lowered!");
13560 // Attempt to load the original value using scalar loads.
13561 // Find the largest scalar type that divides the total loaded size.
13562 MVT SclrLoadTy = MVT::i8;
13563 for (MVT Tp : MVT::integer_valuetypes()) {
13564 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13569 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13570 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13572 SclrLoadTy = MVT::f64;
13574 // Calculate the number of scalar loads that we need to perform
13575 // in order to load our vector from memory.
13576 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13578 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13579 "Can only lower sext loads with a single scalar load!");
13581 unsigned loadRegZize = RegSz;
13582 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13585 // Represent our vector as a sequence of elements which are the
13586 // largest scalar that we can load.
13587 EVT LoadUnitVecVT = EVT::getVectorVT(
13588 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13590 // Represent the data using the same element type that is stored in
13591 // memory. In practice, we ''widen'' MemVT.
13593 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13594 loadRegZize / MemVT.getScalarType().getSizeInBits());
13596 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13597 "Invalid vector type");
13599 // We can't shuffle using an illegal type.
13600 assert(TLI.isTypeLegal(WideVecVT) &&
13601 "We only lower types that form legal widened vector types");
13603 SmallVector<SDValue, 8> Chains;
13604 SDValue Ptr = Ld->getBasePtr();
13605 SDValue Increment =
13606 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13607 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13609 for (unsigned i = 0; i < NumLoads; ++i) {
13610 // Perform a single load.
13611 SDValue ScalarLoad =
13612 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13613 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13614 Ld->getAlignment());
13615 Chains.push_back(ScalarLoad.getValue(1));
13616 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13617 // another round of DAGCombining.
13619 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13621 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13622 ScalarLoad, DAG.getIntPtrConstant(i));
13624 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13627 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13629 // Bitcast the loaded value to a vector of the original element type, in
13630 // the size of the target vector type.
13631 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13632 unsigned SizeRatio = RegSz / MemSz;
13634 if (Ext == ISD::SEXTLOAD) {
13635 // If we have SSE4.1, we can directly emit a VSEXT node.
13636 if (Subtarget->hasSSE41()) {
13637 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13638 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13642 // Otherwise we'll shuffle the small elements in the high bits of the
13643 // larger type and perform an arithmetic shift. If the shift is not legal
13644 // it's better to scalarize.
13645 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13646 "We can't implement a sext load without an arithmetic right shift!");
13648 // Redistribute the loaded elements into the different locations.
13649 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13650 for (unsigned i = 0; i != NumElems; ++i)
13651 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13653 SDValue Shuff = DAG.getVectorShuffle(
13654 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13656 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13658 // Build the arithmetic shift.
13659 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13660 MemVT.getVectorElementType().getSizeInBits();
13662 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13664 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13668 // Redistribute the loaded elements into the different locations.
13669 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13670 for (unsigned i = 0; i != NumElems; ++i)
13671 ShuffleVec[i * SizeRatio] = i;
13673 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13674 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13676 // Bitcast to the requested type.
13677 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13678 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13682 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13683 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13684 // from the AND / OR.
13685 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13686 Opc = Op.getOpcode();
13687 if (Opc != ISD::OR && Opc != ISD::AND)
13689 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13690 Op.getOperand(0).hasOneUse() &&
13691 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13692 Op.getOperand(1).hasOneUse());
13695 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13696 // 1 and that the SETCC node has a single use.
13697 static bool isXor1OfSetCC(SDValue Op) {
13698 if (Op.getOpcode() != ISD::XOR)
13700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13701 if (N1C && N1C->getAPIntValue() == 1) {
13702 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13703 Op.getOperand(0).hasOneUse();
13708 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13709 bool addTest = true;
13710 SDValue Chain = Op.getOperand(0);
13711 SDValue Cond = Op.getOperand(1);
13712 SDValue Dest = Op.getOperand(2);
13715 bool Inverted = false;
13717 if (Cond.getOpcode() == ISD::SETCC) {
13718 // Check for setcc([su]{add,sub,mul}o == 0).
13719 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13720 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13721 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13722 Cond.getOperand(0).getResNo() == 1 &&
13723 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13724 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13725 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13726 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13727 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13728 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13730 Cond = Cond.getOperand(0);
13732 SDValue NewCond = LowerSETCC(Cond, DAG);
13733 if (NewCond.getNode())
13738 // FIXME: LowerXALUO doesn't handle these!!
13739 else if (Cond.getOpcode() == X86ISD::ADD ||
13740 Cond.getOpcode() == X86ISD::SUB ||
13741 Cond.getOpcode() == X86ISD::SMUL ||
13742 Cond.getOpcode() == X86ISD::UMUL)
13743 Cond = LowerXALUO(Cond, DAG);
13746 // Look pass (and (setcc_carry (cmp ...)), 1).
13747 if (Cond.getOpcode() == ISD::AND &&
13748 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13749 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13750 if (C && C->getAPIntValue() == 1)
13751 Cond = Cond.getOperand(0);
13754 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13755 // setting operand in place of the X86ISD::SETCC.
13756 unsigned CondOpcode = Cond.getOpcode();
13757 if (CondOpcode == X86ISD::SETCC ||
13758 CondOpcode == X86ISD::SETCC_CARRY) {
13759 CC = Cond.getOperand(0);
13761 SDValue Cmp = Cond.getOperand(1);
13762 unsigned Opc = Cmp.getOpcode();
13763 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13764 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13768 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13772 // These can only come from an arithmetic instruction with overflow,
13773 // e.g. SADDO, UADDO.
13774 Cond = Cond.getNode()->getOperand(1);
13780 CondOpcode = Cond.getOpcode();
13781 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13782 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13783 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13784 Cond.getOperand(0).getValueType() != MVT::i8)) {
13785 SDValue LHS = Cond.getOperand(0);
13786 SDValue RHS = Cond.getOperand(1);
13787 unsigned X86Opcode;
13790 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13791 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13793 switch (CondOpcode) {
13794 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13796 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13798 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13801 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13802 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13804 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13806 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13809 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13810 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13811 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13812 default: llvm_unreachable("unexpected overflowing operator");
13815 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13816 if (CondOpcode == ISD::UMULO)
13817 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13820 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13822 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13824 if (CondOpcode == ISD::UMULO)
13825 Cond = X86Op.getValue(2);
13827 Cond = X86Op.getValue(1);
13829 CC = DAG.getConstant(X86Cond, MVT::i8);
13833 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13834 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13835 if (CondOpc == ISD::OR) {
13836 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13837 // two branches instead of an explicit OR instruction with a
13839 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13840 isX86LogicalCmp(Cmp)) {
13841 CC = Cond.getOperand(0).getOperand(0);
13842 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13843 Chain, Dest, CC, Cmp);
13844 CC = Cond.getOperand(1).getOperand(0);
13848 } else { // ISD::AND
13849 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13850 // two branches instead of an explicit AND instruction with a
13851 // separate test. However, we only do this if this block doesn't
13852 // have a fall-through edge, because this requires an explicit
13853 // jmp when the condition is false.
13854 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13855 isX86LogicalCmp(Cmp) &&
13856 Op.getNode()->hasOneUse()) {
13857 X86::CondCode CCode =
13858 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13859 CCode = X86::GetOppositeBranchCondition(CCode);
13860 CC = DAG.getConstant(CCode, MVT::i8);
13861 SDNode *User = *Op.getNode()->use_begin();
13862 // Look for an unconditional branch following this conditional branch.
13863 // We need this because we need to reverse the successors in order
13864 // to implement FCMP_OEQ.
13865 if (User->getOpcode() == ISD::BR) {
13866 SDValue FalseBB = User->getOperand(1);
13868 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13869 assert(NewBR == User);
13873 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13874 Chain, Dest, CC, Cmp);
13875 X86::CondCode CCode =
13876 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13877 CCode = X86::GetOppositeBranchCondition(CCode);
13878 CC = DAG.getConstant(CCode, MVT::i8);
13884 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13885 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13886 // It should be transformed during dag combiner except when the condition
13887 // is set by a arithmetics with overflow node.
13888 X86::CondCode CCode =
13889 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13890 CCode = X86::GetOppositeBranchCondition(CCode);
13891 CC = DAG.getConstant(CCode, MVT::i8);
13892 Cond = Cond.getOperand(0).getOperand(1);
13894 } else if (Cond.getOpcode() == ISD::SETCC &&
13895 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13896 // For FCMP_OEQ, we can emit
13897 // two branches instead of an explicit AND instruction with a
13898 // separate test. However, we only do this if this block doesn't
13899 // have a fall-through edge, because this requires an explicit
13900 // jmp when the condition is false.
13901 if (Op.getNode()->hasOneUse()) {
13902 SDNode *User = *Op.getNode()->use_begin();
13903 // Look for an unconditional branch following this conditional branch.
13904 // We need this because we need to reverse the successors in order
13905 // to implement FCMP_OEQ.
13906 if (User->getOpcode() == ISD::BR) {
13907 SDValue FalseBB = User->getOperand(1);
13909 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13910 assert(NewBR == User);
13914 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13915 Cond.getOperand(0), Cond.getOperand(1));
13916 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13917 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13918 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13919 Chain, Dest, CC, Cmp);
13920 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13925 } else if (Cond.getOpcode() == ISD::SETCC &&
13926 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13927 // For FCMP_UNE, we can emit
13928 // two branches instead of an explicit AND instruction with a
13929 // separate test. However, we only do this if this block doesn't
13930 // have a fall-through edge, because this requires an explicit
13931 // jmp when the condition is false.
13932 if (Op.getNode()->hasOneUse()) {
13933 SDNode *User = *Op.getNode()->use_begin();
13934 // Look for an unconditional branch following this conditional branch.
13935 // We need this because we need to reverse the successors in order
13936 // to implement FCMP_UNE.
13937 if (User->getOpcode() == ISD::BR) {
13938 SDValue FalseBB = User->getOperand(1);
13940 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13941 assert(NewBR == User);
13944 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13945 Cond.getOperand(0), Cond.getOperand(1));
13946 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13947 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13948 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13949 Chain, Dest, CC, Cmp);
13950 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13960 // Look pass the truncate if the high bits are known zero.
13961 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13962 Cond = Cond.getOperand(0);
13964 // We know the result of AND is compared against zero. Try to match
13966 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13967 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13968 if (NewSetCC.getNode()) {
13969 CC = NewSetCC.getOperand(0);
13970 Cond = NewSetCC.getOperand(1);
13977 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13978 CC = DAG.getConstant(X86Cond, MVT::i8);
13979 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13981 Cond = ConvertCmpIfNecessary(Cond, DAG);
13982 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13983 Chain, Dest, CC, Cond);
13986 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13987 // Calls to _alloca are needed to probe the stack when allocating more than 4k
13988 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13989 // that the guard pages used by the OS virtual memory manager are allocated in
13990 // correct sequence.
13992 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13993 SelectionDAG &DAG) const {
13994 MachineFunction &MF = DAG.getMachineFunction();
13995 bool SplitStack = MF.shouldSplitStack();
13996 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14002 SDNode* Node = Op.getNode();
14004 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14005 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14006 " not tell us which reg is the stack pointer!");
14007 EVT VT = Node->getValueType(0);
14008 SDValue Tmp1 = SDValue(Node, 0);
14009 SDValue Tmp2 = SDValue(Node, 1);
14010 SDValue Tmp3 = Node->getOperand(2);
14011 SDValue Chain = Tmp1.getOperand(0);
14013 // Chain the dynamic stack allocation so that it doesn't modify the stack
14014 // pointer when other instructions are using the stack.
14015 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14018 SDValue Size = Tmp2.getOperand(1);
14019 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14020 Chain = SP.getValue(1);
14021 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14022 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14023 unsigned StackAlign = TFI.getStackAlignment();
14024 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14025 if (Align > StackAlign)
14026 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14027 DAG.getConstant(-(uint64_t)Align, VT));
14028 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14030 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14031 DAG.getIntPtrConstant(0, true), SDValue(),
14034 SDValue Ops[2] = { Tmp1, Tmp2 };
14035 return DAG.getMergeValues(Ops, dl);
14039 SDValue Chain = Op.getOperand(0);
14040 SDValue Size = Op.getOperand(1);
14041 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14042 EVT VT = Op.getNode()->getValueType(0);
14044 bool Is64Bit = Subtarget->is64Bit();
14045 EVT SPTy = getPointerTy();
14048 MachineRegisterInfo &MRI = MF.getRegInfo();
14051 // The 64 bit implementation of segmented stacks needs to clobber both r10
14052 // r11. This makes it impossible to use it along with nested parameters.
14053 const Function *F = MF.getFunction();
14055 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14057 if (I->hasNestAttr())
14058 report_fatal_error("Cannot use segmented stacks with functions that "
14059 "have nested arguments.");
14062 const TargetRegisterClass *AddrRegClass =
14063 getRegClassFor(getPointerTy());
14064 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14065 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14066 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14067 DAG.getRegister(Vreg, SPTy));
14068 SDValue Ops1[2] = { Value, Chain };
14069 return DAG.getMergeValues(Ops1, dl);
14072 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14074 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14075 Flag = Chain.getValue(1);
14076 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14078 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14080 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14081 unsigned SPReg = RegInfo->getStackRegister();
14082 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14083 Chain = SP.getValue(1);
14086 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14087 DAG.getConstant(-(uint64_t)Align, VT));
14088 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14091 SDValue Ops1[2] = { SP, Chain };
14092 return DAG.getMergeValues(Ops1, dl);
14096 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14097 MachineFunction &MF = DAG.getMachineFunction();
14098 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14100 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14103 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14104 // vastart just stores the address of the VarArgsFrameIndex slot into the
14105 // memory location argument.
14106 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14108 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14109 MachinePointerInfo(SV), false, false, 0);
14113 // gp_offset (0 - 6 * 8)
14114 // fp_offset (48 - 48 + 8 * 16)
14115 // overflow_arg_area (point to parameters coming in memory).
14117 SmallVector<SDValue, 8> MemOps;
14118 SDValue FIN = Op.getOperand(1);
14120 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14121 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14123 FIN, MachinePointerInfo(SV), false, false, 0);
14124 MemOps.push_back(Store);
14127 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14128 FIN, DAG.getIntPtrConstant(4));
14129 Store = DAG.getStore(Op.getOperand(0), DL,
14130 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14132 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14133 MemOps.push_back(Store);
14135 // Store ptr to overflow_arg_area
14136 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14137 FIN, DAG.getIntPtrConstant(4));
14138 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14140 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14141 MachinePointerInfo(SV, 8),
14143 MemOps.push_back(Store);
14145 // Store ptr to reg_save_area.
14146 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14147 FIN, DAG.getIntPtrConstant(8));
14148 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14150 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14151 MachinePointerInfo(SV, 16), false, false, 0);
14152 MemOps.push_back(Store);
14153 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14156 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14157 assert(Subtarget->is64Bit() &&
14158 "LowerVAARG only handles 64-bit va_arg!");
14159 assert((Subtarget->isTargetLinux() ||
14160 Subtarget->isTargetDarwin()) &&
14161 "Unhandled target in LowerVAARG");
14162 assert(Op.getNode()->getNumOperands() == 4);
14163 SDValue Chain = Op.getOperand(0);
14164 SDValue SrcPtr = Op.getOperand(1);
14165 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14166 unsigned Align = Op.getConstantOperandVal(3);
14169 EVT ArgVT = Op.getNode()->getValueType(0);
14170 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14171 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14174 // Decide which area this value should be read from.
14175 // TODO: Implement the AMD64 ABI in its entirety. This simple
14176 // selection mechanism works only for the basic types.
14177 if (ArgVT == MVT::f80) {
14178 llvm_unreachable("va_arg for f80 not yet implemented");
14179 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14180 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14181 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14182 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14184 llvm_unreachable("Unhandled argument type in LowerVAARG");
14187 if (ArgMode == 2) {
14188 // Sanity Check: Make sure using fp_offset makes sense.
14189 assert(!DAG.getTarget().Options.UseSoftFloat &&
14190 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14191 Attribute::NoImplicitFloat)) &&
14192 Subtarget->hasSSE1());
14195 // Insert VAARG_64 node into the DAG
14196 // VAARG_64 returns two values: Variable Argument Address, Chain
14197 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14198 DAG.getConstant(ArgMode, MVT::i8),
14199 DAG.getConstant(Align, MVT::i32)};
14200 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14201 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14202 VTs, InstOps, MVT::i64,
14203 MachinePointerInfo(SV),
14205 /*Volatile=*/false,
14207 /*WriteMem=*/true);
14208 Chain = VAARG.getValue(1);
14210 // Load the next argument and return it
14211 return DAG.getLoad(ArgVT, dl,
14214 MachinePointerInfo(),
14215 false, false, false, 0);
14218 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14219 SelectionDAG &DAG) {
14220 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14221 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14222 SDValue Chain = Op.getOperand(0);
14223 SDValue DstPtr = Op.getOperand(1);
14224 SDValue SrcPtr = Op.getOperand(2);
14225 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14226 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14229 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14230 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14232 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14235 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14236 // amount is a constant. Takes immediate version of shift as input.
14237 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14238 SDValue SrcOp, uint64_t ShiftAmt,
14239 SelectionDAG &DAG) {
14240 MVT ElementType = VT.getVectorElementType();
14242 // Fold this packed shift into its first operand if ShiftAmt is 0.
14246 // Check for ShiftAmt >= element width
14247 if (ShiftAmt >= ElementType.getSizeInBits()) {
14248 if (Opc == X86ISD::VSRAI)
14249 ShiftAmt = ElementType.getSizeInBits() - 1;
14251 return DAG.getConstant(0, VT);
14254 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14255 && "Unknown target vector shift-by-constant node");
14257 // Fold this packed vector shift into a build vector if SrcOp is a
14258 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14259 if (VT == SrcOp.getSimpleValueType() &&
14260 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14261 SmallVector<SDValue, 8> Elts;
14262 unsigned NumElts = SrcOp->getNumOperands();
14263 ConstantSDNode *ND;
14266 default: llvm_unreachable(nullptr);
14267 case X86ISD::VSHLI:
14268 for (unsigned i=0; i!=NumElts; ++i) {
14269 SDValue CurrentOp = SrcOp->getOperand(i);
14270 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14271 Elts.push_back(CurrentOp);
14274 ND = cast<ConstantSDNode>(CurrentOp);
14275 const APInt &C = ND->getAPIntValue();
14276 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14279 case X86ISD::VSRLI:
14280 for (unsigned i=0; i!=NumElts; ++i) {
14281 SDValue CurrentOp = SrcOp->getOperand(i);
14282 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14283 Elts.push_back(CurrentOp);
14286 ND = cast<ConstantSDNode>(CurrentOp);
14287 const APInt &C = ND->getAPIntValue();
14288 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14291 case X86ISD::VSRAI:
14292 for (unsigned i=0; i!=NumElts; ++i) {
14293 SDValue CurrentOp = SrcOp->getOperand(i);
14294 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14295 Elts.push_back(CurrentOp);
14298 ND = cast<ConstantSDNode>(CurrentOp);
14299 const APInt &C = ND->getAPIntValue();
14300 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14305 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14308 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14311 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14312 // may or may not be a constant. Takes immediate version of shift as input.
14313 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14314 SDValue SrcOp, SDValue ShAmt,
14315 SelectionDAG &DAG) {
14316 MVT SVT = ShAmt.getSimpleValueType();
14317 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14319 // Catch shift-by-constant.
14320 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14321 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14322 CShAmt->getZExtValue(), DAG);
14324 // Change opcode to non-immediate version
14326 default: llvm_unreachable("Unknown target vector shift node");
14327 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14328 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14329 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14332 const X86Subtarget &Subtarget =
14333 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14334 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14335 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14336 // Let the shuffle legalizer expand this shift amount node.
14337 SDValue Op0 = ShAmt.getOperand(0);
14338 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14339 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14341 // Need to build a vector containing shift amount.
14342 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14343 SmallVector<SDValue, 4> ShOps;
14344 ShOps.push_back(ShAmt);
14345 if (SVT == MVT::i32) {
14346 ShOps.push_back(DAG.getConstant(0, SVT));
14347 ShOps.push_back(DAG.getUNDEF(SVT));
14349 ShOps.push_back(DAG.getUNDEF(SVT));
14351 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14352 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14355 // The return type has to be a 128-bit type with the same element
14356 // type as the input type.
14357 MVT EltVT = VT.getVectorElementType();
14358 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14360 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14361 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14364 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14365 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14366 /// necessary casting for \p Mask when lowering masking intrinsics.
14367 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14368 SDValue PreservedSrc,
14369 const X86Subtarget *Subtarget,
14370 SelectionDAG &DAG) {
14371 EVT VT = Op.getValueType();
14372 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14373 MVT::i1, VT.getVectorNumElements());
14374 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14375 Mask.getValueType().getSizeInBits());
14378 assert(MaskVT.isSimple() && "invalid mask type");
14380 if (isAllOnes(Mask))
14383 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14384 // are extracted by EXTRACT_SUBVECTOR.
14385 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14386 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14387 DAG.getIntPtrConstant(0));
14389 switch (Op.getOpcode()) {
14391 case X86ISD::PCMPEQM:
14392 case X86ISD::PCMPGTM:
14394 case X86ISD::CMPMU:
14395 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14397 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14398 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14399 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14402 /// \brief Creates an SDNode for a predicated scalar operation.
14403 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14404 /// The mask is comming as MVT::i8 and it should be truncated
14405 /// to MVT::i1 while lowering masking intrinsics.
14406 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14407 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14408 /// a scalar instruction.
14409 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14410 SDValue PreservedSrc,
14411 const X86Subtarget *Subtarget,
14412 SelectionDAG &DAG) {
14413 if (isAllOnes(Mask))
14416 EVT VT = Op.getValueType();
14418 // The mask should be of type MVT::i1
14419 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14421 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14422 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14423 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14426 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14427 SelectionDAG &DAG) {
14429 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14430 EVT VT = Op.getValueType();
14431 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14433 switch(IntrData->Type) {
14434 case INTR_TYPE_1OP:
14435 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14436 case INTR_TYPE_2OP:
14437 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14439 case INTR_TYPE_3OP:
14440 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14441 Op.getOperand(2), Op.getOperand(3));
14442 case INTR_TYPE_1OP_MASK_RM: {
14443 SDValue Src = Op.getOperand(1);
14444 SDValue Src0 = Op.getOperand(2);
14445 SDValue Mask = Op.getOperand(3);
14446 SDValue RoundingMode = Op.getOperand(4);
14447 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14449 Mask, Src0, Subtarget, DAG);
14451 case INTR_TYPE_SCALAR_MASK_RM: {
14452 SDValue Src1 = Op.getOperand(1);
14453 SDValue Src2 = Op.getOperand(2);
14454 SDValue Src0 = Op.getOperand(3);
14455 SDValue Mask = Op.getOperand(4);
14456 // There are 2 kinds of intrinsics in this group:
14457 // (1) With supress-all-exceptions (sae) - 6 operands
14458 // (2) With rounding mode and sae - 7 operands.
14459 if (Op.getNumOperands() == 6) {
14460 SDValue Sae = Op.getOperand(5);
14461 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14463 Mask, Src0, Subtarget, DAG);
14465 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14466 SDValue RoundingMode = Op.getOperand(5);
14467 SDValue Sae = Op.getOperand(6);
14468 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14469 RoundingMode, Sae),
14470 Mask, Src0, Subtarget, DAG);
14472 case INTR_TYPE_2OP_MASK: {
14473 SDValue Src1 = Op.getOperand(1);
14474 SDValue Src2 = Op.getOperand(2);
14475 SDValue PassThru = Op.getOperand(3);
14476 SDValue Mask = Op.getOperand(4);
14477 // We specify 2 possible opcodes for intrinsics with rounding modes.
14478 // First, we check if the intrinsic may have non-default rounding mode,
14479 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14480 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14481 if (IntrWithRoundingModeOpcode != 0) {
14482 SDValue Rnd = Op.getOperand(5);
14483 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14484 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14485 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14486 dl, Op.getValueType(),
14488 Mask, PassThru, Subtarget, DAG);
14491 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14493 Mask, PassThru, Subtarget, DAG);
14495 case FMA_OP_MASK: {
14496 SDValue Src1 = Op.getOperand(1);
14497 SDValue Src2 = Op.getOperand(2);
14498 SDValue Src3 = Op.getOperand(3);
14499 SDValue Mask = Op.getOperand(4);
14500 // We specify 2 possible opcodes for intrinsics with rounding modes.
14501 // First, we check if the intrinsic may have non-default rounding mode,
14502 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14503 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14504 if (IntrWithRoundingModeOpcode != 0) {
14505 SDValue Rnd = Op.getOperand(5);
14506 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14507 X86::STATIC_ROUNDING::CUR_DIRECTION)
14508 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14509 dl, Op.getValueType(),
14510 Src1, Src2, Src3, Rnd),
14511 Mask, Src1, Subtarget, DAG);
14513 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14514 dl, Op.getValueType(),
14516 Mask, Src1, Subtarget, DAG);
14519 case CMP_MASK_CC: {
14520 // Comparison intrinsics with masks.
14521 // Example of transformation:
14522 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14523 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14525 // (v8i1 (insert_subvector undef,
14526 // (v2i1 (and (PCMPEQM %a, %b),
14527 // (extract_subvector
14528 // (v8i1 (bitcast %mask)), 0))), 0))))
14529 EVT VT = Op.getOperand(1).getValueType();
14530 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14531 VT.getVectorNumElements());
14532 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14533 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14534 Mask.getValueType().getSizeInBits());
14536 if (IntrData->Type == CMP_MASK_CC) {
14537 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14538 Op.getOperand(2), Op.getOperand(3));
14540 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14541 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14544 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14545 DAG.getTargetConstant(0, MaskVT),
14547 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14548 DAG.getUNDEF(BitcastVT), CmpMask,
14549 DAG.getIntPtrConstant(0));
14550 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14552 case COMI: { // Comparison intrinsics
14553 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14554 SDValue LHS = Op.getOperand(1);
14555 SDValue RHS = Op.getOperand(2);
14556 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14557 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14558 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14559 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14560 DAG.getConstant(X86CC, MVT::i8), Cond);
14561 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14564 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14565 Op.getOperand(1), Op.getOperand(2), DAG);
14567 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14568 Op.getSimpleValueType(),
14570 Op.getOperand(2), DAG),
14571 Op.getOperand(4), Op.getOperand(3), Subtarget,
14573 case COMPRESS_EXPAND_IN_REG: {
14574 SDValue Mask = Op.getOperand(3);
14575 SDValue DataToCompress = Op.getOperand(1);
14576 SDValue PassThru = Op.getOperand(2);
14577 if (isAllOnes(Mask)) // return data as is
14578 return Op.getOperand(1);
14579 EVT VT = Op.getValueType();
14580 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14581 VT.getVectorNumElements());
14582 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14583 Mask.getValueType().getSizeInBits());
14585 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14586 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14587 DAG.getIntPtrConstant(0));
14589 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14593 SDValue Mask = Op.getOperand(3);
14594 EVT VT = Op.getValueType();
14595 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14596 VT.getVectorNumElements());
14597 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14598 Mask.getValueType().getSizeInBits());
14600 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14601 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14602 DAG.getIntPtrConstant(0));
14603 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14612 default: return SDValue(); // Don't custom lower most intrinsics.
14614 case Intrinsic::x86_avx512_mask_valign_q_512:
14615 case Intrinsic::x86_avx512_mask_valign_d_512:
14616 // Vector source operands are swapped.
14617 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14618 Op.getValueType(), Op.getOperand(2),
14621 Op.getOperand(5), Op.getOperand(4),
14624 // ptest and testp intrinsics. The intrinsic these come from are designed to
14625 // return an integer value, not just an instruction so lower it to the ptest
14626 // or testp pattern and a setcc for the result.
14627 case Intrinsic::x86_sse41_ptestz:
14628 case Intrinsic::x86_sse41_ptestc:
14629 case Intrinsic::x86_sse41_ptestnzc:
14630 case Intrinsic::x86_avx_ptestz_256:
14631 case Intrinsic::x86_avx_ptestc_256:
14632 case Intrinsic::x86_avx_ptestnzc_256:
14633 case Intrinsic::x86_avx_vtestz_ps:
14634 case Intrinsic::x86_avx_vtestc_ps:
14635 case Intrinsic::x86_avx_vtestnzc_ps:
14636 case Intrinsic::x86_avx_vtestz_pd:
14637 case Intrinsic::x86_avx_vtestc_pd:
14638 case Intrinsic::x86_avx_vtestnzc_pd:
14639 case Intrinsic::x86_avx_vtestz_ps_256:
14640 case Intrinsic::x86_avx_vtestc_ps_256:
14641 case Intrinsic::x86_avx_vtestnzc_ps_256:
14642 case Intrinsic::x86_avx_vtestz_pd_256:
14643 case Intrinsic::x86_avx_vtestc_pd_256:
14644 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14645 bool IsTestPacked = false;
14648 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14649 case Intrinsic::x86_avx_vtestz_ps:
14650 case Intrinsic::x86_avx_vtestz_pd:
14651 case Intrinsic::x86_avx_vtestz_ps_256:
14652 case Intrinsic::x86_avx_vtestz_pd_256:
14653 IsTestPacked = true; // Fallthrough
14654 case Intrinsic::x86_sse41_ptestz:
14655 case Intrinsic::x86_avx_ptestz_256:
14657 X86CC = X86::COND_E;
14659 case Intrinsic::x86_avx_vtestc_ps:
14660 case Intrinsic::x86_avx_vtestc_pd:
14661 case Intrinsic::x86_avx_vtestc_ps_256:
14662 case Intrinsic::x86_avx_vtestc_pd_256:
14663 IsTestPacked = true; // Fallthrough
14664 case Intrinsic::x86_sse41_ptestc:
14665 case Intrinsic::x86_avx_ptestc_256:
14667 X86CC = X86::COND_B;
14669 case Intrinsic::x86_avx_vtestnzc_ps:
14670 case Intrinsic::x86_avx_vtestnzc_pd:
14671 case Intrinsic::x86_avx_vtestnzc_ps_256:
14672 case Intrinsic::x86_avx_vtestnzc_pd_256:
14673 IsTestPacked = true; // Fallthrough
14674 case Intrinsic::x86_sse41_ptestnzc:
14675 case Intrinsic::x86_avx_ptestnzc_256:
14677 X86CC = X86::COND_A;
14681 SDValue LHS = Op.getOperand(1);
14682 SDValue RHS = Op.getOperand(2);
14683 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14684 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14685 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14686 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14687 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14689 case Intrinsic::x86_avx512_kortestz_w:
14690 case Intrinsic::x86_avx512_kortestc_w: {
14691 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14692 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14693 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14694 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14695 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14696 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14697 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14700 case Intrinsic::x86_sse42_pcmpistria128:
14701 case Intrinsic::x86_sse42_pcmpestria128:
14702 case Intrinsic::x86_sse42_pcmpistric128:
14703 case Intrinsic::x86_sse42_pcmpestric128:
14704 case Intrinsic::x86_sse42_pcmpistrio128:
14705 case Intrinsic::x86_sse42_pcmpestrio128:
14706 case Intrinsic::x86_sse42_pcmpistris128:
14707 case Intrinsic::x86_sse42_pcmpestris128:
14708 case Intrinsic::x86_sse42_pcmpistriz128:
14709 case Intrinsic::x86_sse42_pcmpestriz128: {
14713 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14714 case Intrinsic::x86_sse42_pcmpistria128:
14715 Opcode = X86ISD::PCMPISTRI;
14716 X86CC = X86::COND_A;
14718 case Intrinsic::x86_sse42_pcmpestria128:
14719 Opcode = X86ISD::PCMPESTRI;
14720 X86CC = X86::COND_A;
14722 case Intrinsic::x86_sse42_pcmpistric128:
14723 Opcode = X86ISD::PCMPISTRI;
14724 X86CC = X86::COND_B;
14726 case Intrinsic::x86_sse42_pcmpestric128:
14727 Opcode = X86ISD::PCMPESTRI;
14728 X86CC = X86::COND_B;
14730 case Intrinsic::x86_sse42_pcmpistrio128:
14731 Opcode = X86ISD::PCMPISTRI;
14732 X86CC = X86::COND_O;
14734 case Intrinsic::x86_sse42_pcmpestrio128:
14735 Opcode = X86ISD::PCMPESTRI;
14736 X86CC = X86::COND_O;
14738 case Intrinsic::x86_sse42_pcmpistris128:
14739 Opcode = X86ISD::PCMPISTRI;
14740 X86CC = X86::COND_S;
14742 case Intrinsic::x86_sse42_pcmpestris128:
14743 Opcode = X86ISD::PCMPESTRI;
14744 X86CC = X86::COND_S;
14746 case Intrinsic::x86_sse42_pcmpistriz128:
14747 Opcode = X86ISD::PCMPISTRI;
14748 X86CC = X86::COND_E;
14750 case Intrinsic::x86_sse42_pcmpestriz128:
14751 Opcode = X86ISD::PCMPESTRI;
14752 X86CC = X86::COND_E;
14755 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14756 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14757 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14758 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14759 DAG.getConstant(X86CC, MVT::i8),
14760 SDValue(PCMP.getNode(), 1));
14761 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14764 case Intrinsic::x86_sse42_pcmpistri128:
14765 case Intrinsic::x86_sse42_pcmpestri128: {
14767 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14768 Opcode = X86ISD::PCMPISTRI;
14770 Opcode = X86ISD::PCMPESTRI;
14772 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14773 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14774 return DAG.getNode(Opcode, dl, VTs, NewOps);
14779 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14780 SDValue Src, SDValue Mask, SDValue Base,
14781 SDValue Index, SDValue ScaleOp, SDValue Chain,
14782 const X86Subtarget * Subtarget) {
14784 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14785 assert(C && "Invalid scale type");
14786 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14787 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14788 Index.getSimpleValueType().getVectorNumElements());
14790 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14792 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14794 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14795 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14796 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14797 SDValue Segment = DAG.getRegister(0, MVT::i32);
14798 if (Src.getOpcode() == ISD::UNDEF)
14799 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14800 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14801 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14802 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14803 return DAG.getMergeValues(RetOps, dl);
14806 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14807 SDValue Src, SDValue Mask, SDValue Base,
14808 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14810 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14811 assert(C && "Invalid scale type");
14812 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14813 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14814 SDValue Segment = DAG.getRegister(0, MVT::i32);
14815 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14816 Index.getSimpleValueType().getVectorNumElements());
14818 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14820 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14822 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14823 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14824 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14825 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14826 return SDValue(Res, 1);
14829 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14830 SDValue Mask, SDValue Base, SDValue Index,
14831 SDValue ScaleOp, SDValue Chain) {
14833 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14834 assert(C && "Invalid scale type");
14835 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14836 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14837 SDValue Segment = DAG.getRegister(0, MVT::i32);
14839 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14841 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14843 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14845 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14846 //SDVTList VTs = DAG.getVTList(MVT::Other);
14847 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14848 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14849 return SDValue(Res, 0);
14852 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14853 // read performance monitor counters (x86_rdpmc).
14854 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14855 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14856 SmallVectorImpl<SDValue> &Results) {
14857 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14858 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14861 // The ECX register is used to select the index of the performance counter
14863 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14865 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14867 // Reads the content of a 64-bit performance counter and returns it in the
14868 // registers EDX:EAX.
14869 if (Subtarget->is64Bit()) {
14870 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14871 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14874 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14875 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14878 Chain = HI.getValue(1);
14880 if (Subtarget->is64Bit()) {
14881 // The EAX register is loaded with the low-order 32 bits. The EDX register
14882 // is loaded with the supported high-order bits of the counter.
14883 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14884 DAG.getConstant(32, MVT::i8));
14885 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14886 Results.push_back(Chain);
14890 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14891 SDValue Ops[] = { LO, HI };
14892 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14893 Results.push_back(Pair);
14894 Results.push_back(Chain);
14897 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14898 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14899 // also used to custom lower READCYCLECOUNTER nodes.
14900 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14901 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14902 SmallVectorImpl<SDValue> &Results) {
14903 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14904 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14907 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14908 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14909 // and the EAX register is loaded with the low-order 32 bits.
14910 if (Subtarget->is64Bit()) {
14911 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14912 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14915 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14916 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14919 SDValue Chain = HI.getValue(1);
14921 if (Opcode == X86ISD::RDTSCP_DAG) {
14922 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14924 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14925 // the ECX register. Add 'ecx' explicitly to the chain.
14926 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14928 // Explicitly store the content of ECX at the location passed in input
14929 // to the 'rdtscp' intrinsic.
14930 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14931 MachinePointerInfo(), false, false, 0);
14934 if (Subtarget->is64Bit()) {
14935 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14936 // the EAX register is loaded with the low-order 32 bits.
14937 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14938 DAG.getConstant(32, MVT::i8));
14939 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14940 Results.push_back(Chain);
14944 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14945 SDValue Ops[] = { LO, HI };
14946 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14947 Results.push_back(Pair);
14948 Results.push_back(Chain);
14951 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14952 SelectionDAG &DAG) {
14953 SmallVector<SDValue, 2> Results;
14955 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14957 return DAG.getMergeValues(Results, DL);
14961 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14962 SelectionDAG &DAG) {
14963 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14965 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
14970 switch(IntrData->Type) {
14972 llvm_unreachable("Unknown Intrinsic Type");
14976 // Emit the node with the right value type.
14977 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14978 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
14980 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14981 // Otherwise return the value from Rand, which is always 0, casted to i32.
14982 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14983 DAG.getConstant(1, Op->getValueType(1)),
14984 DAG.getConstant(X86::COND_B, MVT::i32),
14985 SDValue(Result.getNode(), 1) };
14986 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14987 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14990 // Return { result, isValid, chain }.
14991 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14992 SDValue(Result.getNode(), 2));
14995 //gather(v1, mask, index, base, scale);
14996 SDValue Chain = Op.getOperand(0);
14997 SDValue Src = Op.getOperand(2);
14998 SDValue Base = Op.getOperand(3);
14999 SDValue Index = Op.getOperand(4);
15000 SDValue Mask = Op.getOperand(5);
15001 SDValue Scale = Op.getOperand(6);
15002 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15006 //scatter(base, mask, index, v1, scale);
15007 SDValue Chain = Op.getOperand(0);
15008 SDValue Base = Op.getOperand(2);
15009 SDValue Mask = Op.getOperand(3);
15010 SDValue Index = Op.getOperand(4);
15011 SDValue Src = Op.getOperand(5);
15012 SDValue Scale = Op.getOperand(6);
15013 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15016 SDValue Hint = Op.getOperand(6);
15018 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15019 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15020 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15021 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15022 SDValue Chain = Op.getOperand(0);
15023 SDValue Mask = Op.getOperand(2);
15024 SDValue Index = Op.getOperand(3);
15025 SDValue Base = Op.getOperand(4);
15026 SDValue Scale = Op.getOperand(5);
15027 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15029 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15031 SmallVector<SDValue, 2> Results;
15032 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15033 return DAG.getMergeValues(Results, dl);
15035 // Read Performance Monitoring Counters.
15037 SmallVector<SDValue, 2> Results;
15038 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15039 return DAG.getMergeValues(Results, dl);
15041 // XTEST intrinsics.
15043 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15044 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15045 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15046 DAG.getConstant(X86::COND_NE, MVT::i8),
15048 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15049 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15050 Ret, SDValue(InTrans.getNode(), 1));
15054 SmallVector<SDValue, 2> Results;
15055 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15056 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15057 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15058 DAG.getConstant(-1, MVT::i8));
15059 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15060 Op.getOperand(4), GenCF.getValue(1));
15061 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15062 Op.getOperand(5), MachinePointerInfo(),
15064 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15065 DAG.getConstant(X86::COND_B, MVT::i8),
15067 Results.push_back(SetCC);
15068 Results.push_back(Store);
15069 return DAG.getMergeValues(Results, dl);
15071 case COMPRESS_TO_MEM: {
15073 SDValue Mask = Op.getOperand(4);
15074 SDValue DataToCompress = Op.getOperand(3);
15075 SDValue Addr = Op.getOperand(2);
15076 SDValue Chain = Op.getOperand(0);
15078 if (isAllOnes(Mask)) // return just a store
15079 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15080 MachinePointerInfo(), false, false, 0);
15082 EVT VT = DataToCompress.getValueType();
15083 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15084 VT.getVectorNumElements());
15085 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15086 Mask.getValueType().getSizeInBits());
15087 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15088 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15089 DAG.getIntPtrConstant(0));
15091 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15092 DataToCompress, DAG.getUNDEF(VT));
15093 return DAG.getStore(Chain, dl, Compressed, Addr,
15094 MachinePointerInfo(), false, false, 0);
15096 case EXPAND_FROM_MEM: {
15098 SDValue Mask = Op.getOperand(4);
15099 SDValue PathThru = Op.getOperand(3);
15100 SDValue Addr = Op.getOperand(2);
15101 SDValue Chain = Op.getOperand(0);
15102 EVT VT = Op.getValueType();
15104 if (isAllOnes(Mask)) // return just a load
15105 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15107 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15108 VT.getVectorNumElements());
15109 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15110 Mask.getValueType().getSizeInBits());
15111 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15112 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15113 DAG.getIntPtrConstant(0));
15115 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15116 false, false, false, 0);
15118 SDValue Results[] = {
15119 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15121 return DAG.getMergeValues(Results, dl);
15126 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15127 SelectionDAG &DAG) const {
15128 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15129 MFI->setReturnAddressIsTaken(true);
15131 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15134 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15136 EVT PtrVT = getPointerTy();
15139 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15140 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15141 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15142 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15143 DAG.getNode(ISD::ADD, dl, PtrVT,
15144 FrameAddr, Offset),
15145 MachinePointerInfo(), false, false, false, 0);
15148 // Just load the return address.
15149 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15150 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15151 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15154 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15155 MachineFunction &MF = DAG.getMachineFunction();
15156 MachineFrameInfo *MFI = MF.getFrameInfo();
15157 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15158 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15159 EVT VT = Op.getValueType();
15161 MFI->setFrameAddressIsTaken(true);
15163 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15164 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15165 // is not possible to crawl up the stack without looking at the unwind codes
15167 int FrameAddrIndex = FuncInfo->getFAIndex();
15168 if (!FrameAddrIndex) {
15169 // Set up a frame object for the return address.
15170 unsigned SlotSize = RegInfo->getSlotSize();
15171 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15172 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15173 FuncInfo->setFAIndex(FrameAddrIndex);
15175 return DAG.getFrameIndex(FrameAddrIndex, VT);
15178 unsigned FrameReg =
15179 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15180 SDLoc dl(Op); // FIXME probably not meaningful
15181 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15182 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15183 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15184 "Invalid Frame Register!");
15185 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15187 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15188 MachinePointerInfo(),
15189 false, false, false, 0);
15193 // FIXME? Maybe this could be a TableGen attribute on some registers and
15194 // this table could be generated automatically from RegInfo.
15195 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15197 unsigned Reg = StringSwitch<unsigned>(RegName)
15198 .Case("esp", X86::ESP)
15199 .Case("rsp", X86::RSP)
15203 report_fatal_error("Invalid register name global variable");
15206 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15207 SelectionDAG &DAG) const {
15208 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15209 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15212 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15213 SDValue Chain = Op.getOperand(0);
15214 SDValue Offset = Op.getOperand(1);
15215 SDValue Handler = Op.getOperand(2);
15218 EVT PtrVT = getPointerTy();
15219 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15220 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15221 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15222 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15223 "Invalid Frame Register!");
15224 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15225 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15227 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15228 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15229 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15230 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15232 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15234 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15235 DAG.getRegister(StoreAddrReg, PtrVT));
15238 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15239 SelectionDAG &DAG) const {
15241 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15242 DAG.getVTList(MVT::i32, MVT::Other),
15243 Op.getOperand(0), Op.getOperand(1));
15246 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15247 SelectionDAG &DAG) const {
15249 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15250 Op.getOperand(0), Op.getOperand(1));
15253 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15254 return Op.getOperand(0);
15257 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15258 SelectionDAG &DAG) const {
15259 SDValue Root = Op.getOperand(0);
15260 SDValue Trmp = Op.getOperand(1); // trampoline
15261 SDValue FPtr = Op.getOperand(2); // nested function
15262 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15265 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15266 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15268 if (Subtarget->is64Bit()) {
15269 SDValue OutChains[6];
15271 // Large code-model.
15272 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15273 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15275 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15276 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15278 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15280 // Load the pointer to the nested function into R11.
15281 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15282 SDValue Addr = Trmp;
15283 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15284 Addr, MachinePointerInfo(TrmpAddr),
15287 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15288 DAG.getConstant(2, MVT::i64));
15289 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15290 MachinePointerInfo(TrmpAddr, 2),
15293 // Load the 'nest' parameter value into R10.
15294 // R10 is specified in X86CallingConv.td
15295 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15296 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15297 DAG.getConstant(10, MVT::i64));
15298 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15299 Addr, MachinePointerInfo(TrmpAddr, 10),
15302 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15303 DAG.getConstant(12, MVT::i64));
15304 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15305 MachinePointerInfo(TrmpAddr, 12),
15308 // Jump to the nested function.
15309 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15310 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15311 DAG.getConstant(20, MVT::i64));
15312 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15313 Addr, MachinePointerInfo(TrmpAddr, 20),
15316 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15317 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15318 DAG.getConstant(22, MVT::i64));
15319 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15320 MachinePointerInfo(TrmpAddr, 22),
15323 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15325 const Function *Func =
15326 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15327 CallingConv::ID CC = Func->getCallingConv();
15332 llvm_unreachable("Unsupported calling convention");
15333 case CallingConv::C:
15334 case CallingConv::X86_StdCall: {
15335 // Pass 'nest' parameter in ECX.
15336 // Must be kept in sync with X86CallingConv.td
15337 NestReg = X86::ECX;
15339 // Check that ECX wasn't needed by an 'inreg' parameter.
15340 FunctionType *FTy = Func->getFunctionType();
15341 const AttributeSet &Attrs = Func->getAttributes();
15343 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15344 unsigned InRegCount = 0;
15347 for (FunctionType::param_iterator I = FTy->param_begin(),
15348 E = FTy->param_end(); I != E; ++I, ++Idx)
15349 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15350 // FIXME: should only count parameters that are lowered to integers.
15351 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15353 if (InRegCount > 2) {
15354 report_fatal_error("Nest register in use - reduce number of inreg"
15360 case CallingConv::X86_FastCall:
15361 case CallingConv::X86_ThisCall:
15362 case CallingConv::Fast:
15363 // Pass 'nest' parameter in EAX.
15364 // Must be kept in sync with X86CallingConv.td
15365 NestReg = X86::EAX;
15369 SDValue OutChains[4];
15370 SDValue Addr, Disp;
15372 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15373 DAG.getConstant(10, MVT::i32));
15374 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15376 // This is storing the opcode for MOV32ri.
15377 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15378 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15379 OutChains[0] = DAG.getStore(Root, dl,
15380 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15381 Trmp, MachinePointerInfo(TrmpAddr),
15384 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15385 DAG.getConstant(1, MVT::i32));
15386 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15387 MachinePointerInfo(TrmpAddr, 1),
15390 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15391 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15392 DAG.getConstant(5, MVT::i32));
15393 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15394 MachinePointerInfo(TrmpAddr, 5),
15397 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15398 DAG.getConstant(6, MVT::i32));
15399 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15400 MachinePointerInfo(TrmpAddr, 6),
15403 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15407 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15408 SelectionDAG &DAG) const {
15410 The rounding mode is in bits 11:10 of FPSR, and has the following
15412 00 Round to nearest
15417 FLT_ROUNDS, on the other hand, expects the following:
15424 To perform the conversion, we do:
15425 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15428 MachineFunction &MF = DAG.getMachineFunction();
15429 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15430 unsigned StackAlignment = TFI.getStackAlignment();
15431 MVT VT = Op.getSimpleValueType();
15434 // Save FP Control Word to stack slot
15435 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15436 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15438 MachineMemOperand *MMO =
15439 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15440 MachineMemOperand::MOStore, 2, 2);
15442 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15443 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15444 DAG.getVTList(MVT::Other),
15445 Ops, MVT::i16, MMO);
15447 // Load FP Control Word from stack slot
15448 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15449 MachinePointerInfo(), false, false, false, 0);
15451 // Transform as necessary
15453 DAG.getNode(ISD::SRL, DL, MVT::i16,
15454 DAG.getNode(ISD::AND, DL, MVT::i16,
15455 CWD, DAG.getConstant(0x800, MVT::i16)),
15456 DAG.getConstant(11, MVT::i8));
15458 DAG.getNode(ISD::SRL, DL, MVT::i16,
15459 DAG.getNode(ISD::AND, DL, MVT::i16,
15460 CWD, DAG.getConstant(0x400, MVT::i16)),
15461 DAG.getConstant(9, MVT::i8));
15464 DAG.getNode(ISD::AND, DL, MVT::i16,
15465 DAG.getNode(ISD::ADD, DL, MVT::i16,
15466 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15467 DAG.getConstant(1, MVT::i16)),
15468 DAG.getConstant(3, MVT::i16));
15470 return DAG.getNode((VT.getSizeInBits() < 16 ?
15471 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15474 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15475 MVT VT = Op.getSimpleValueType();
15477 unsigned NumBits = VT.getSizeInBits();
15480 Op = Op.getOperand(0);
15481 if (VT == MVT::i8) {
15482 // Zero extend to i32 since there is not an i8 bsr.
15484 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15487 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15488 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15489 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15491 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15494 DAG.getConstant(NumBits+NumBits-1, OpVT),
15495 DAG.getConstant(X86::COND_E, MVT::i8),
15498 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15500 // Finally xor with NumBits-1.
15501 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15504 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15508 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15509 MVT VT = Op.getSimpleValueType();
15511 unsigned NumBits = VT.getSizeInBits();
15514 Op = Op.getOperand(0);
15515 if (VT == MVT::i8) {
15516 // Zero extend to i32 since there is not an i8 bsr.
15518 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15521 // Issue a bsr (scan bits in reverse).
15522 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15523 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15525 // And xor with NumBits-1.
15526 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15529 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15533 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15534 MVT VT = Op.getSimpleValueType();
15535 unsigned NumBits = VT.getSizeInBits();
15537 Op = Op.getOperand(0);
15539 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15540 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15541 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15543 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15546 DAG.getConstant(NumBits, VT),
15547 DAG.getConstant(X86::COND_E, MVT::i8),
15550 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15553 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15554 // ones, and then concatenate the result back.
15555 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15556 MVT VT = Op.getSimpleValueType();
15558 assert(VT.is256BitVector() && VT.isInteger() &&
15559 "Unsupported value type for operation");
15561 unsigned NumElems = VT.getVectorNumElements();
15564 // Extract the LHS vectors
15565 SDValue LHS = Op.getOperand(0);
15566 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15567 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15569 // Extract the RHS vectors
15570 SDValue RHS = Op.getOperand(1);
15571 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15572 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15574 MVT EltVT = VT.getVectorElementType();
15575 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15577 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15578 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15579 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15582 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15583 assert(Op.getSimpleValueType().is256BitVector() &&
15584 Op.getSimpleValueType().isInteger() &&
15585 "Only handle AVX 256-bit vector integer operation");
15586 return Lower256IntArith(Op, DAG);
15589 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15590 assert(Op.getSimpleValueType().is256BitVector() &&
15591 Op.getSimpleValueType().isInteger() &&
15592 "Only handle AVX 256-bit vector integer operation");
15593 return Lower256IntArith(Op, DAG);
15596 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15597 SelectionDAG &DAG) {
15599 MVT VT = Op.getSimpleValueType();
15601 // Decompose 256-bit ops into smaller 128-bit ops.
15602 if (VT.is256BitVector() && !Subtarget->hasInt256())
15603 return Lower256IntArith(Op, DAG);
15605 SDValue A = Op.getOperand(0);
15606 SDValue B = Op.getOperand(1);
15608 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15609 if (VT == MVT::v4i32) {
15610 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15611 "Should not custom lower when pmuldq is available!");
15613 // Extract the odd parts.
15614 static const int UnpackMask[] = { 1, -1, 3, -1 };
15615 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15616 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15618 // Multiply the even parts.
15619 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15620 // Now multiply odd parts.
15621 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15623 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15624 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15626 // Merge the two vectors back together with a shuffle. This expands into 2
15628 static const int ShufMask[] = { 0, 4, 2, 6 };
15629 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15632 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15633 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15635 // Ahi = psrlqi(a, 32);
15636 // Bhi = psrlqi(b, 32);
15638 // AloBlo = pmuludq(a, b);
15639 // AloBhi = pmuludq(a, Bhi);
15640 // AhiBlo = pmuludq(Ahi, b);
15642 // AloBhi = psllqi(AloBhi, 32);
15643 // AhiBlo = psllqi(AhiBlo, 32);
15644 // return AloBlo + AloBhi + AhiBlo;
15646 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15647 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15649 // Bit cast to 32-bit vectors for MULUDQ
15650 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15651 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15652 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15653 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15654 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15655 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15657 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15658 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15659 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15661 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15662 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15664 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15665 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15668 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15669 assert(Subtarget->isTargetWin64() && "Unexpected target");
15670 EVT VT = Op.getValueType();
15671 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15672 "Unexpected return type for lowering");
15676 switch (Op->getOpcode()) {
15677 default: llvm_unreachable("Unexpected request for libcall!");
15678 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15679 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15680 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15681 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15682 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15683 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15687 SDValue InChain = DAG.getEntryNode();
15689 TargetLowering::ArgListTy Args;
15690 TargetLowering::ArgListEntry Entry;
15691 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15692 EVT ArgVT = Op->getOperand(i).getValueType();
15693 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15694 "Unexpected argument type for lowering");
15695 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15696 Entry.Node = StackPtr;
15697 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15699 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15700 Entry.Ty = PointerType::get(ArgTy,0);
15701 Entry.isSExt = false;
15702 Entry.isZExt = false;
15703 Args.push_back(Entry);
15706 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15709 TargetLowering::CallLoweringInfo CLI(DAG);
15710 CLI.setDebugLoc(dl).setChain(InChain)
15711 .setCallee(getLibcallCallingConv(LC),
15712 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15713 Callee, std::move(Args), 0)
15714 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15716 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15717 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15720 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15721 SelectionDAG &DAG) {
15722 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15723 EVT VT = Op0.getValueType();
15726 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15727 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15729 // PMULxD operations multiply each even value (starting at 0) of LHS with
15730 // the related value of RHS and produce a widen result.
15731 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15732 // => <2 x i64> <ae|cg>
15734 // In other word, to have all the results, we need to perform two PMULxD:
15735 // 1. one with the even values.
15736 // 2. one with the odd values.
15737 // To achieve #2, with need to place the odd values at an even position.
15739 // Place the odd value at an even position (basically, shift all values 1
15740 // step to the left):
15741 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15742 // <a|b|c|d> => <b|undef|d|undef>
15743 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15744 // <e|f|g|h> => <f|undef|h|undef>
15745 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15747 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15749 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15750 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15752 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15753 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15754 // => <2 x i64> <ae|cg>
15755 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15756 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15757 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15758 // => <2 x i64> <bf|dh>
15759 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15760 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15762 // Shuffle it back into the right order.
15763 SDValue Highs, Lows;
15764 if (VT == MVT::v8i32) {
15765 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15766 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15767 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15768 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15770 const int HighMask[] = {1, 5, 3, 7};
15771 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15772 const int LowMask[] = {0, 4, 2, 6};
15773 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15776 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15777 // unsigned multiply.
15778 if (IsSigned && !Subtarget->hasSSE41()) {
15780 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15781 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15782 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15783 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15784 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15786 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15787 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15790 // The first result of MUL_LOHI is actually the low value, followed by the
15792 SDValue Ops[] = {Lows, Highs};
15793 return DAG.getMergeValues(Ops, dl);
15796 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15797 const X86Subtarget *Subtarget) {
15798 MVT VT = Op.getSimpleValueType();
15800 SDValue R = Op.getOperand(0);
15801 SDValue Amt = Op.getOperand(1);
15803 // Optimize shl/srl/sra with constant shift amount.
15804 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15805 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15806 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15808 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15809 (Subtarget->hasInt256() &&
15810 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15811 (Subtarget->hasAVX512() &&
15812 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15813 if (Op.getOpcode() == ISD::SHL)
15814 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15816 if (Op.getOpcode() == ISD::SRL)
15817 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15819 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15820 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15824 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15825 unsigned NumElts = VT.getVectorNumElements();
15826 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15828 if (Op.getOpcode() == ISD::SHL) {
15829 // Make a large shift.
15830 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15832 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15833 // Zero out the rightmost bits.
15834 SmallVector<SDValue, 32> V(
15835 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15836 return DAG.getNode(ISD::AND, dl, VT, SHL,
15837 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15839 if (Op.getOpcode() == ISD::SRL) {
15840 // Make a large shift.
15841 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15843 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15844 // Zero out the leftmost bits.
15845 SmallVector<SDValue, 32> V(
15846 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15847 return DAG.getNode(ISD::AND, dl, VT, SRL,
15848 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15850 if (Op.getOpcode() == ISD::SRA) {
15851 if (ShiftAmt == 7) {
15852 // R s>> 7 === R s< 0
15853 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15854 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15857 // R s>> a === ((R u>> a) ^ m) - m
15858 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15859 SmallVector<SDValue, 32> V(NumElts,
15860 DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15861 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15862 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15863 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15866 llvm_unreachable("Unknown shift opcode.");
15871 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15872 if (!Subtarget->is64Bit() &&
15873 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15874 Amt.getOpcode() == ISD::BITCAST &&
15875 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15876 Amt = Amt.getOperand(0);
15877 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15878 VT.getVectorNumElements();
15879 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15880 uint64_t ShiftAmt = 0;
15881 for (unsigned i = 0; i != Ratio; ++i) {
15882 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15886 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15888 // Check remaining shift amounts.
15889 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15890 uint64_t ShAmt = 0;
15891 for (unsigned j = 0; j != Ratio; ++j) {
15892 ConstantSDNode *C =
15893 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15897 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15899 if (ShAmt != ShiftAmt)
15902 switch (Op.getOpcode()) {
15904 llvm_unreachable("Unknown shift opcode!");
15906 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15909 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15912 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15920 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15921 const X86Subtarget* Subtarget) {
15922 MVT VT = Op.getSimpleValueType();
15924 SDValue R = Op.getOperand(0);
15925 SDValue Amt = Op.getOperand(1);
15927 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15928 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15929 (Subtarget->hasInt256() &&
15930 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15931 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15932 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15934 EVT EltVT = VT.getVectorElementType();
15936 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
15937 // Check if this build_vector node is doing a splat.
15938 // If so, then set BaseShAmt equal to the splat value.
15939 BaseShAmt = BV->getSplatValue();
15940 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
15941 BaseShAmt = SDValue();
15943 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15944 Amt = Amt.getOperand(0);
15946 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
15947 if (SVN && SVN->isSplat()) {
15948 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
15949 SDValue InVec = Amt.getOperand(0);
15950 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15951 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
15952 "Unexpected shuffle index found!");
15953 BaseShAmt = InVec.getOperand(SplatIdx);
15954 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15955 if (ConstantSDNode *C =
15956 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15957 if (C->getZExtValue() == SplatIdx)
15958 BaseShAmt = InVec.getOperand(1);
15963 // Avoid introducing an extract element from a shuffle.
15964 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
15965 DAG.getIntPtrConstant(SplatIdx));
15969 if (BaseShAmt.getNode()) {
15970 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
15971 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
15972 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
15973 else if (EltVT.bitsLT(MVT::i32))
15974 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15976 switch (Op.getOpcode()) {
15978 llvm_unreachable("Unknown shift opcode!");
15980 switch (VT.SimpleTy) {
15981 default: return SDValue();
15990 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15993 switch (VT.SimpleTy) {
15994 default: return SDValue();
16001 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16004 switch (VT.SimpleTy) {
16005 default: return SDValue();
16014 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16020 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16021 if (!Subtarget->is64Bit() &&
16022 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16023 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16024 Amt.getOpcode() == ISD::BITCAST &&
16025 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16026 Amt = Amt.getOperand(0);
16027 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16028 VT.getVectorNumElements();
16029 std::vector<SDValue> Vals(Ratio);
16030 for (unsigned i = 0; i != Ratio; ++i)
16031 Vals[i] = Amt.getOperand(i);
16032 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16033 for (unsigned j = 0; j != Ratio; ++j)
16034 if (Vals[j] != Amt.getOperand(i + j))
16037 switch (Op.getOpcode()) {
16039 llvm_unreachable("Unknown shift opcode!");
16041 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16043 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16045 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16052 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16053 SelectionDAG &DAG) {
16054 MVT VT = Op.getSimpleValueType();
16056 SDValue R = Op.getOperand(0);
16057 SDValue Amt = Op.getOperand(1);
16060 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16061 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16063 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16067 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16071 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16073 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16074 if (Subtarget->hasInt256()) {
16075 if (Op.getOpcode() == ISD::SRL &&
16076 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16077 VT == MVT::v4i64 || VT == MVT::v8i32))
16079 if (Op.getOpcode() == ISD::SHL &&
16080 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16081 VT == MVT::v4i64 || VT == MVT::v8i32))
16083 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16087 // If possible, lower this packed shift into a vector multiply instead of
16088 // expanding it into a sequence of scalar shifts.
16089 // Do this only if the vector shift count is a constant build_vector.
16090 if (Op.getOpcode() == ISD::SHL &&
16091 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16092 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16093 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16094 SmallVector<SDValue, 8> Elts;
16095 EVT SVT = VT.getScalarType();
16096 unsigned SVTBits = SVT.getSizeInBits();
16097 const APInt &One = APInt(SVTBits, 1);
16098 unsigned NumElems = VT.getVectorNumElements();
16100 for (unsigned i=0; i !=NumElems; ++i) {
16101 SDValue Op = Amt->getOperand(i);
16102 if (Op->getOpcode() == ISD::UNDEF) {
16103 Elts.push_back(Op);
16107 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16108 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16109 uint64_t ShAmt = C.getZExtValue();
16110 if (ShAmt >= SVTBits) {
16111 Elts.push_back(DAG.getUNDEF(SVT));
16114 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16116 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16117 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16120 // Lower SHL with variable shift amount.
16121 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16122 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16124 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16125 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16126 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16127 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16130 // If possible, lower this shift as a sequence of two shifts by
16131 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16133 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16135 // Could be rewritten as:
16136 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16138 // The advantage is that the two shifts from the example would be
16139 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16140 // the vector shift into four scalar shifts plus four pairs of vector
16142 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16143 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16144 unsigned TargetOpcode = X86ISD::MOVSS;
16145 bool CanBeSimplified;
16146 // The splat value for the first packed shift (the 'X' from the example).
16147 SDValue Amt1 = Amt->getOperand(0);
16148 // The splat value for the second packed shift (the 'Y' from the example).
16149 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16150 Amt->getOperand(2);
16152 // See if it is possible to replace this node with a sequence of
16153 // two shifts followed by a MOVSS/MOVSD
16154 if (VT == MVT::v4i32) {
16155 // Check if it is legal to use a MOVSS.
16156 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16157 Amt2 == Amt->getOperand(3);
16158 if (!CanBeSimplified) {
16159 // Otherwise, check if we can still simplify this node using a MOVSD.
16160 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16161 Amt->getOperand(2) == Amt->getOperand(3);
16162 TargetOpcode = X86ISD::MOVSD;
16163 Amt2 = Amt->getOperand(2);
16166 // Do similar checks for the case where the machine value type
16168 CanBeSimplified = Amt1 == Amt->getOperand(1);
16169 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16170 CanBeSimplified = Amt2 == Amt->getOperand(i);
16172 if (!CanBeSimplified) {
16173 TargetOpcode = X86ISD::MOVSD;
16174 CanBeSimplified = true;
16175 Amt2 = Amt->getOperand(4);
16176 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16177 CanBeSimplified = Amt1 == Amt->getOperand(i);
16178 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16179 CanBeSimplified = Amt2 == Amt->getOperand(j);
16183 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16184 isa<ConstantSDNode>(Amt2)) {
16185 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16186 EVT CastVT = MVT::v4i32;
16188 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16189 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16191 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16192 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16193 if (TargetOpcode == X86ISD::MOVSD)
16194 CastVT = MVT::v2i64;
16195 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16196 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16197 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16199 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16203 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16204 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16207 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16208 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16210 // Turn 'a' into a mask suitable for VSELECT
16211 SDValue VSelM = DAG.getConstant(0x80, VT);
16212 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16213 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16215 SDValue CM1 = DAG.getConstant(0x0f, VT);
16216 SDValue CM2 = DAG.getConstant(0x3f, VT);
16218 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16219 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16220 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16221 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16222 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16225 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16226 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16227 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16229 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16230 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16231 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16232 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16233 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16236 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16237 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16238 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16240 // return VSELECT(r, r+r, a);
16241 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16242 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16246 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16247 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16248 // solution better.
16249 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16250 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16252 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16253 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16254 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16255 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16256 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16259 // Decompose 256-bit shifts into smaller 128-bit shifts.
16260 if (VT.is256BitVector()) {
16261 unsigned NumElems = VT.getVectorNumElements();
16262 MVT EltVT = VT.getVectorElementType();
16263 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16265 // Extract the two vectors
16266 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16267 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16269 // Recreate the shift amount vectors
16270 SDValue Amt1, Amt2;
16271 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16272 // Constant shift amount
16273 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16274 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16275 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16277 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16278 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16280 // Variable shift amount
16281 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16282 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16285 // Issue new vector shifts for the smaller types
16286 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16287 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16289 // Concatenate the result back
16290 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16296 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16297 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16298 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16299 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16300 // has only one use.
16301 SDNode *N = Op.getNode();
16302 SDValue LHS = N->getOperand(0);
16303 SDValue RHS = N->getOperand(1);
16304 unsigned BaseOp = 0;
16307 switch (Op.getOpcode()) {
16308 default: llvm_unreachable("Unknown ovf instruction!");
16310 // A subtract of one will be selected as a INC. Note that INC doesn't
16311 // set CF, so we can't do this for UADDO.
16312 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16314 BaseOp = X86ISD::INC;
16315 Cond = X86::COND_O;
16318 BaseOp = X86ISD::ADD;
16319 Cond = X86::COND_O;
16322 BaseOp = X86ISD::ADD;
16323 Cond = X86::COND_B;
16326 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16327 // set CF, so we can't do this for USUBO.
16328 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16330 BaseOp = X86ISD::DEC;
16331 Cond = X86::COND_O;
16334 BaseOp = X86ISD::SUB;
16335 Cond = X86::COND_O;
16338 BaseOp = X86ISD::SUB;
16339 Cond = X86::COND_B;
16342 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16343 Cond = X86::COND_O;
16345 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16346 if (N->getValueType(0) == MVT::i8) {
16347 BaseOp = X86ISD::UMUL8;
16348 Cond = X86::COND_O;
16351 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16353 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16356 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16357 DAG.getConstant(X86::COND_O, MVT::i32),
16358 SDValue(Sum.getNode(), 2));
16360 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16364 // Also sets EFLAGS.
16365 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16366 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16369 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16370 DAG.getConstant(Cond, MVT::i32),
16371 SDValue(Sum.getNode(), 1));
16373 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16376 /// Returns true if the operand type is exactly twice the native width, and
16377 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16378 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16379 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16380 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16381 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16384 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16385 else if (OpWidth == 128)
16386 return Subtarget->hasCmpxchg16b();
16391 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16392 return needsCmpXchgNb(SI->getValueOperand()->getType());
16395 // Note: this turns large loads into lock cmpxchg8b/16b.
16396 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16397 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16398 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16399 return needsCmpXchgNb(PTy->getElementType());
16402 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16403 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16404 const Type *MemType = AI->getType();
16406 // If the operand is too big, we must see if cmpxchg8/16b is available
16407 // and default to library calls otherwise.
16408 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16409 return needsCmpXchgNb(MemType);
16411 AtomicRMWInst::BinOp Op = AI->getOperation();
16414 llvm_unreachable("Unknown atomic operation");
16415 case AtomicRMWInst::Xchg:
16416 case AtomicRMWInst::Add:
16417 case AtomicRMWInst::Sub:
16418 // It's better to use xadd, xsub or xchg for these in all cases.
16420 case AtomicRMWInst::Or:
16421 case AtomicRMWInst::And:
16422 case AtomicRMWInst::Xor:
16423 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16424 // prefix to a normal instruction for these operations.
16425 return !AI->use_empty();
16426 case AtomicRMWInst::Nand:
16427 case AtomicRMWInst::Max:
16428 case AtomicRMWInst::Min:
16429 case AtomicRMWInst::UMax:
16430 case AtomicRMWInst::UMin:
16431 // These always require a non-trivial set of data operations on x86. We must
16432 // use a cmpxchg loop.
16437 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16438 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16439 // no-sse2). There isn't any reason to disable it if the target processor
16441 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16445 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16446 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16447 const Type *MemType = AI->getType();
16448 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16449 // there is no benefit in turning such RMWs into loads, and it is actually
16450 // harmful as it introduces a mfence.
16451 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16454 auto Builder = IRBuilder<>(AI);
16455 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16456 auto SynchScope = AI->getSynchScope();
16457 // We must restrict the ordering to avoid generating loads with Release or
16458 // ReleaseAcquire orderings.
16459 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16460 auto Ptr = AI->getPointerOperand();
16462 // Before the load we need a fence. Here is an example lifted from
16463 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16466 // x.store(1, relaxed);
16467 // r1 = y.fetch_add(0, release);
16469 // y.fetch_add(42, acquire);
16470 // r2 = x.load(relaxed);
16471 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16472 // lowered to just a load without a fence. A mfence flushes the store buffer,
16473 // making the optimization clearly correct.
16474 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16475 // otherwise, we might be able to be more agressive on relaxed idempotent
16476 // rmw. In practice, they do not look useful, so we don't try to be
16477 // especially clever.
16478 if (SynchScope == SingleThread) {
16479 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16480 // the IR level, so we must wrap it in an intrinsic.
16482 } else if (hasMFENCE(*Subtarget)) {
16483 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16484 Intrinsic::x86_sse2_mfence);
16485 Builder.CreateCall(MFence);
16487 // FIXME: it might make sense to use a locked operation here but on a
16488 // different cache-line to prevent cache-line bouncing. In practice it
16489 // is probably a small win, and x86 processors without mfence are rare
16490 // enough that we do not bother.
16494 // Finally we can emit the atomic load.
16495 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16496 AI->getType()->getPrimitiveSizeInBits());
16497 Loaded->setAtomic(Order, SynchScope);
16498 AI->replaceAllUsesWith(Loaded);
16499 AI->eraseFromParent();
16503 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16504 SelectionDAG &DAG) {
16506 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16507 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16508 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16509 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16511 // The only fence that needs an instruction is a sequentially-consistent
16512 // cross-thread fence.
16513 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16514 if (hasMFENCE(*Subtarget))
16515 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16517 SDValue Chain = Op.getOperand(0);
16518 SDValue Zero = DAG.getConstant(0, MVT::i32);
16520 DAG.getRegister(X86::ESP, MVT::i32), // Base
16521 DAG.getTargetConstant(1, MVT::i8), // Scale
16522 DAG.getRegister(0, MVT::i32), // Index
16523 DAG.getTargetConstant(0, MVT::i32), // Disp
16524 DAG.getRegister(0, MVT::i32), // Segment.
16528 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16529 return SDValue(Res, 0);
16532 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16533 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16536 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16537 SelectionDAG &DAG) {
16538 MVT T = Op.getSimpleValueType();
16542 switch(T.SimpleTy) {
16543 default: llvm_unreachable("Invalid value type!");
16544 case MVT::i8: Reg = X86::AL; size = 1; break;
16545 case MVT::i16: Reg = X86::AX; size = 2; break;
16546 case MVT::i32: Reg = X86::EAX; size = 4; break;
16548 assert(Subtarget->is64Bit() && "Node not type legal!");
16549 Reg = X86::RAX; size = 8;
16552 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16553 Op.getOperand(2), SDValue());
16554 SDValue Ops[] = { cpIn.getValue(0),
16557 DAG.getTargetConstant(size, MVT::i8),
16558 cpIn.getValue(1) };
16559 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16560 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16561 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16565 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16566 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16567 MVT::i32, cpOut.getValue(2));
16568 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16569 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16571 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16572 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16573 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16577 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16578 SelectionDAG &DAG) {
16579 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16580 MVT DstVT = Op.getSimpleValueType();
16582 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16583 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16584 if (DstVT != MVT::f64)
16585 // This conversion needs to be expanded.
16588 SDValue InVec = Op->getOperand(0);
16590 unsigned NumElts = SrcVT.getVectorNumElements();
16591 EVT SVT = SrcVT.getVectorElementType();
16593 // Widen the vector in input in the case of MVT::v2i32.
16594 // Example: from MVT::v2i32 to MVT::v4i32.
16595 SmallVector<SDValue, 16> Elts;
16596 for (unsigned i = 0, e = NumElts; i != e; ++i)
16597 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16598 DAG.getIntPtrConstant(i)));
16600 // Explicitly mark the extra elements as Undef.
16601 Elts.append(NumElts, DAG.getUNDEF(SVT));
16603 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16604 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16605 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16606 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16607 DAG.getIntPtrConstant(0));
16610 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16611 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16612 assert((DstVT == MVT::i64 ||
16613 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16614 "Unexpected custom BITCAST");
16615 // i64 <=> MMX conversions are Legal.
16616 if (SrcVT==MVT::i64 && DstVT.isVector())
16618 if (DstVT==MVT::i64 && SrcVT.isVector())
16620 // MMX <=> MMX conversions are Legal.
16621 if (SrcVT.isVector() && DstVT.isVector())
16623 // All other conversions need to be expanded.
16627 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16628 SelectionDAG &DAG) {
16629 SDNode *Node = Op.getNode();
16632 Op = Op.getOperand(0);
16633 EVT VT = Op.getValueType();
16634 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16635 "CTPOP lowering only implemented for 128/256-bit wide vector types");
16637 unsigned NumElts = VT.getVectorNumElements();
16638 EVT EltVT = VT.getVectorElementType();
16639 unsigned Len = EltVT.getSizeInBits();
16641 // This is the vectorized version of the "best" algorithm from
16642 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16643 // with a minor tweak to use a series of adds + shifts instead of vector
16644 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16646 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16647 // v8i32 => Always profitable
16649 // FIXME: There a couple of possible improvements:
16651 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16652 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16654 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16655 "CTPOP not implemented for this vector element type.");
16657 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16658 // extra legalization.
16659 bool NeedsBitcast = EltVT == MVT::i32;
16660 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16662 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16663 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16664 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16666 // v = v - ((v >> 1) & 0x55555555...)
16667 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16668 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16669 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16671 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16673 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16674 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16676 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16678 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16679 if (VT != And.getValueType())
16680 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16681 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16683 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16684 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16685 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16686 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16687 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16689 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16690 if (NeedsBitcast) {
16691 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16692 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16693 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16696 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16697 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16698 if (VT != AndRHS.getValueType()) {
16699 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16700 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16702 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16704 // v = (v + (v >> 4)) & 0x0F0F0F0F...
16705 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16706 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16707 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16708 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16710 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16711 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16712 if (NeedsBitcast) {
16713 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16714 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16716 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16717 if (VT != And.getValueType())
16718 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16720 // The algorithm mentioned above uses:
16721 // v = (v * 0x01010101...) >> (Len - 8)
16723 // Change it to use vector adds + vector shifts which yield faster results on
16724 // Haswell than using vector integer multiplication.
16726 // For i32 elements:
16727 // v = v + (v >> 8)
16728 // v = v + (v >> 16)
16730 // For i64 elements:
16731 // v = v + (v >> 8)
16732 // v = v + (v >> 16)
16733 // v = v + (v >> 32)
16736 SmallVector<SDValue, 8> Csts;
16737 for (unsigned i = 8; i <= Len/2; i *= 2) {
16738 Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16739 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16740 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16741 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16745 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16746 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16747 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16748 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16749 if (NeedsBitcast) {
16750 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16751 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16753 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16754 if (VT != And.getValueType())
16755 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16760 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16761 SDNode *Node = Op.getNode();
16763 EVT T = Node->getValueType(0);
16764 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16765 DAG.getConstant(0, T), Node->getOperand(2));
16766 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16767 cast<AtomicSDNode>(Node)->getMemoryVT(),
16768 Node->getOperand(0),
16769 Node->getOperand(1), negOp,
16770 cast<AtomicSDNode>(Node)->getMemOperand(),
16771 cast<AtomicSDNode>(Node)->getOrdering(),
16772 cast<AtomicSDNode>(Node)->getSynchScope());
16775 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16776 SDNode *Node = Op.getNode();
16778 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16780 // Convert seq_cst store -> xchg
16781 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16782 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16783 // (The only way to get a 16-byte store is cmpxchg16b)
16784 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16785 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16786 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16787 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16788 cast<AtomicSDNode>(Node)->getMemoryVT(),
16789 Node->getOperand(0),
16790 Node->getOperand(1), Node->getOperand(2),
16791 cast<AtomicSDNode>(Node)->getMemOperand(),
16792 cast<AtomicSDNode>(Node)->getOrdering(),
16793 cast<AtomicSDNode>(Node)->getSynchScope());
16794 return Swap.getValue(1);
16796 // Other atomic stores have a simple pattern.
16800 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16801 EVT VT = Op.getNode()->getSimpleValueType(0);
16803 // Let legalize expand this if it isn't a legal type yet.
16804 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16807 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16810 bool ExtraOp = false;
16811 switch (Op.getOpcode()) {
16812 default: llvm_unreachable("Invalid code");
16813 case ISD::ADDC: Opc = X86ISD::ADD; break;
16814 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16815 case ISD::SUBC: Opc = X86ISD::SUB; break;
16816 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16820 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16822 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16823 Op.getOperand(1), Op.getOperand(2));
16826 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16827 SelectionDAG &DAG) {
16828 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16830 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16831 // which returns the values as { float, float } (in XMM0) or
16832 // { double, double } (which is returned in XMM0, XMM1).
16834 SDValue Arg = Op.getOperand(0);
16835 EVT ArgVT = Arg.getValueType();
16836 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16838 TargetLowering::ArgListTy Args;
16839 TargetLowering::ArgListEntry Entry;
16843 Entry.isSExt = false;
16844 Entry.isZExt = false;
16845 Args.push_back(Entry);
16847 bool isF64 = ArgVT == MVT::f64;
16848 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16849 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16850 // the results are returned via SRet in memory.
16851 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16852 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16853 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16855 Type *RetTy = isF64
16856 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16857 : (Type*)VectorType::get(ArgTy, 4);
16859 TargetLowering::CallLoweringInfo CLI(DAG);
16860 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16861 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16863 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16866 // Returned in xmm0 and xmm1.
16867 return CallResult.first;
16869 // Returned in bits 0:31 and 32:64 xmm0.
16870 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16871 CallResult.first, DAG.getIntPtrConstant(0));
16872 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16873 CallResult.first, DAG.getIntPtrConstant(1));
16874 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16875 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16878 /// LowerOperation - Provide custom lowering hooks for some operations.
16880 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16881 switch (Op.getOpcode()) {
16882 default: llvm_unreachable("Should not custom lower this!");
16883 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16884 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16885 return LowerCMP_SWAP(Op, Subtarget, DAG);
16886 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
16887 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16888 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16889 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16890 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16891 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
16892 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16893 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16894 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16895 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16896 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16897 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16898 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16899 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16900 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16901 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16902 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16903 case ISD::SHL_PARTS:
16904 case ISD::SRA_PARTS:
16905 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16906 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16907 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16908 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16909 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16910 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16911 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16912 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16913 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16914 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16915 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16917 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
16918 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16919 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16920 case ISD::SETCC: return LowerSETCC(Op, DAG);
16921 case ISD::SELECT: return LowerSELECT(Op, DAG);
16922 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16923 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16924 case ISD::VASTART: return LowerVASTART(Op, DAG);
16925 case ISD::VAARG: return LowerVAARG(Op, DAG);
16926 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16927 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
16928 case ISD::INTRINSIC_VOID:
16929 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16930 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16931 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16932 case ISD::FRAME_TO_ARGS_OFFSET:
16933 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16934 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16935 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16936 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16937 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16938 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16939 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16940 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16941 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16942 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16943 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16944 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16945 case ISD::UMUL_LOHI:
16946 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16949 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16955 case ISD::UMULO: return LowerXALUO(Op, DAG);
16956 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16957 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16961 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16962 case ISD::ADD: return LowerADD(Op, DAG);
16963 case ISD::SUB: return LowerSUB(Op, DAG);
16964 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16968 /// ReplaceNodeResults - Replace a node with an illegal result type
16969 /// with a new node built out of custom code.
16970 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16971 SmallVectorImpl<SDValue>&Results,
16972 SelectionDAG &DAG) const {
16974 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16975 switch (N->getOpcode()) {
16977 llvm_unreachable("Do not know how to custom type legalize this operation!");
16978 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
16979 case X86ISD::FMINC:
16981 case X86ISD::FMAXC:
16982 case X86ISD::FMAX: {
16983 EVT VT = N->getValueType(0);
16984 if (VT != MVT::v2f32)
16985 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
16986 SDValue UNDEF = DAG.getUNDEF(VT);
16987 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16988 N->getOperand(0), UNDEF);
16989 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16990 N->getOperand(1), UNDEF);
16991 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
16994 case ISD::SIGN_EXTEND_INREG:
16999 // We don't want to expand or promote these.
17006 case ISD::UDIVREM: {
17007 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17008 Results.push_back(V);
17011 case ISD::FP_TO_SINT:
17012 case ISD::FP_TO_UINT: {
17013 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17015 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17018 std::pair<SDValue,SDValue> Vals =
17019 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17020 SDValue FIST = Vals.first, StackSlot = Vals.second;
17021 if (FIST.getNode()) {
17022 EVT VT = N->getValueType(0);
17023 // Return a load from the stack slot.
17024 if (StackSlot.getNode())
17025 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17026 MachinePointerInfo(),
17027 false, false, false, 0));
17029 Results.push_back(FIST);
17033 case ISD::UINT_TO_FP: {
17034 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17035 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17036 N->getValueType(0) != MVT::v2f32)
17038 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17040 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17042 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17043 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17044 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17045 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17046 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17047 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17050 case ISD::FP_ROUND: {
17051 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17053 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17054 Results.push_back(V);
17057 case ISD::INTRINSIC_W_CHAIN: {
17058 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17060 default : llvm_unreachable("Do not know how to custom type "
17061 "legalize this intrinsic operation!");
17062 case Intrinsic::x86_rdtsc:
17063 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17065 case Intrinsic::x86_rdtscp:
17066 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17068 case Intrinsic::x86_rdpmc:
17069 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17072 case ISD::READCYCLECOUNTER: {
17073 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17076 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17077 EVT T = N->getValueType(0);
17078 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17079 bool Regs64bit = T == MVT::i128;
17080 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17081 SDValue cpInL, cpInH;
17082 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17083 DAG.getConstant(0, HalfT));
17084 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17085 DAG.getConstant(1, HalfT));
17086 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17087 Regs64bit ? X86::RAX : X86::EAX,
17089 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17090 Regs64bit ? X86::RDX : X86::EDX,
17091 cpInH, cpInL.getValue(1));
17092 SDValue swapInL, swapInH;
17093 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17094 DAG.getConstant(0, HalfT));
17095 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17096 DAG.getConstant(1, HalfT));
17097 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17098 Regs64bit ? X86::RBX : X86::EBX,
17099 swapInL, cpInH.getValue(1));
17100 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17101 Regs64bit ? X86::RCX : X86::ECX,
17102 swapInH, swapInL.getValue(1));
17103 SDValue Ops[] = { swapInH.getValue(0),
17105 swapInH.getValue(1) };
17106 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17107 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17108 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17109 X86ISD::LCMPXCHG8_DAG;
17110 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17111 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17112 Regs64bit ? X86::RAX : X86::EAX,
17113 HalfT, Result.getValue(1));
17114 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17115 Regs64bit ? X86::RDX : X86::EDX,
17116 HalfT, cpOutL.getValue(2));
17117 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17119 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17120 MVT::i32, cpOutH.getValue(2));
17122 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17123 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17124 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17126 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17127 Results.push_back(Success);
17128 Results.push_back(EFLAGS.getValue(1));
17131 case ISD::ATOMIC_SWAP:
17132 case ISD::ATOMIC_LOAD_ADD:
17133 case ISD::ATOMIC_LOAD_SUB:
17134 case ISD::ATOMIC_LOAD_AND:
17135 case ISD::ATOMIC_LOAD_OR:
17136 case ISD::ATOMIC_LOAD_XOR:
17137 case ISD::ATOMIC_LOAD_NAND:
17138 case ISD::ATOMIC_LOAD_MIN:
17139 case ISD::ATOMIC_LOAD_MAX:
17140 case ISD::ATOMIC_LOAD_UMIN:
17141 case ISD::ATOMIC_LOAD_UMAX:
17142 case ISD::ATOMIC_LOAD: {
17143 // Delegate to generic TypeLegalization. Situations we can really handle
17144 // should have already been dealt with by AtomicExpandPass.cpp.
17147 case ISD::BITCAST: {
17148 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17149 EVT DstVT = N->getValueType(0);
17150 EVT SrcVT = N->getOperand(0)->getValueType(0);
17152 if (SrcVT != MVT::f64 ||
17153 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17156 unsigned NumElts = DstVT.getVectorNumElements();
17157 EVT SVT = DstVT.getVectorElementType();
17158 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17159 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17160 MVT::v2f64, N->getOperand(0));
17161 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17163 if (ExperimentalVectorWideningLegalization) {
17164 // If we are legalizing vectors by widening, we already have the desired
17165 // legal vector type, just return it.
17166 Results.push_back(ToVecInt);
17170 SmallVector<SDValue, 8> Elts;
17171 for (unsigned i = 0, e = NumElts; i != e; ++i)
17172 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17173 ToVecInt, DAG.getIntPtrConstant(i)));
17175 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17180 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17182 default: return nullptr;
17183 case X86ISD::BSF: return "X86ISD::BSF";
17184 case X86ISD::BSR: return "X86ISD::BSR";
17185 case X86ISD::SHLD: return "X86ISD::SHLD";
17186 case X86ISD::SHRD: return "X86ISD::SHRD";
17187 case X86ISD::FAND: return "X86ISD::FAND";
17188 case X86ISD::FANDN: return "X86ISD::FANDN";
17189 case X86ISD::FOR: return "X86ISD::FOR";
17190 case X86ISD::FXOR: return "X86ISD::FXOR";
17191 case X86ISD::FSRL: return "X86ISD::FSRL";
17192 case X86ISD::FILD: return "X86ISD::FILD";
17193 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17194 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17195 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17196 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17197 case X86ISD::FLD: return "X86ISD::FLD";
17198 case X86ISD::FST: return "X86ISD::FST";
17199 case X86ISD::CALL: return "X86ISD::CALL";
17200 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17201 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17202 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17203 case X86ISD::BT: return "X86ISD::BT";
17204 case X86ISD::CMP: return "X86ISD::CMP";
17205 case X86ISD::COMI: return "X86ISD::COMI";
17206 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17207 case X86ISD::CMPM: return "X86ISD::CMPM";
17208 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17209 case X86ISD::SETCC: return "X86ISD::SETCC";
17210 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17211 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17212 case X86ISD::CMOV: return "X86ISD::CMOV";
17213 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17214 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17215 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17216 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17217 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17218 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17219 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17220 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17221 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17222 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17223 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17224 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17225 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17226 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17227 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17228 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17229 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17230 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17231 case X86ISD::HADD: return "X86ISD::HADD";
17232 case X86ISD::HSUB: return "X86ISD::HSUB";
17233 case X86ISD::FHADD: return "X86ISD::FHADD";
17234 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17235 case X86ISD::UMAX: return "X86ISD::UMAX";
17236 case X86ISD::UMIN: return "X86ISD::UMIN";
17237 case X86ISD::SMAX: return "X86ISD::SMAX";
17238 case X86ISD::SMIN: return "X86ISD::SMIN";
17239 case X86ISD::FMAX: return "X86ISD::FMAX";
17240 case X86ISD::FMIN: return "X86ISD::FMIN";
17241 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17242 case X86ISD::FMINC: return "X86ISD::FMINC";
17243 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17244 case X86ISD::FRCP: return "X86ISD::FRCP";
17245 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17246 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17247 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17248 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17249 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17250 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17251 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17252 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17253 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17254 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17255 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17256 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17257 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17258 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17259 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17260 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17261 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17262 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17263 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17264 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17265 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17266 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17267 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17268 case X86ISD::VSHL: return "X86ISD::VSHL";
17269 case X86ISD::VSRL: return "X86ISD::VSRL";
17270 case X86ISD::VSRA: return "X86ISD::VSRA";
17271 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17272 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17273 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17274 case X86ISD::CMPP: return "X86ISD::CMPP";
17275 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17276 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17277 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17278 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17279 case X86ISD::ADD: return "X86ISD::ADD";
17280 case X86ISD::SUB: return "X86ISD::SUB";
17281 case X86ISD::ADC: return "X86ISD::ADC";
17282 case X86ISD::SBB: return "X86ISD::SBB";
17283 case X86ISD::SMUL: return "X86ISD::SMUL";
17284 case X86ISD::UMUL: return "X86ISD::UMUL";
17285 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17286 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17287 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17288 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17289 case X86ISD::INC: return "X86ISD::INC";
17290 case X86ISD::DEC: return "X86ISD::DEC";
17291 case X86ISD::OR: return "X86ISD::OR";
17292 case X86ISD::XOR: return "X86ISD::XOR";
17293 case X86ISD::AND: return "X86ISD::AND";
17294 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17295 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17296 case X86ISD::PTEST: return "X86ISD::PTEST";
17297 case X86ISD::TESTP: return "X86ISD::TESTP";
17298 case X86ISD::TESTM: return "X86ISD::TESTM";
17299 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17300 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17301 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17302 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17303 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17304 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17305 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17306 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17307 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17308 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17309 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17310 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17311 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17312 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17313 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17314 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17315 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17316 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17317 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17318 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17319 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17320 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17321 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17322 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17323 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17324 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17325 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17326 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17327 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17328 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17329 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17330 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17331 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17332 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17333 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17334 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17335 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17336 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17337 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17338 case X86ISD::SAHF: return "X86ISD::SAHF";
17339 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17340 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17341 case X86ISD::FMADD: return "X86ISD::FMADD";
17342 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17343 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17344 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17345 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17346 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17347 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17348 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17349 case X86ISD::XTEST: return "X86ISD::XTEST";
17350 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17351 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17352 case X86ISD::SELECT: return "X86ISD::SELECT";
17353 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17354 case X86ISD::RCP28: return "X86ISD::RCP28";
17355 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17356 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17357 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17358 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17359 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17363 // isLegalAddressingMode - Return true if the addressing mode represented
17364 // by AM is legal for this target, for a load/store of the specified type.
17365 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17367 // X86 supports extremely general addressing modes.
17368 CodeModel::Model M = getTargetMachine().getCodeModel();
17369 Reloc::Model R = getTargetMachine().getRelocationModel();
17371 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17372 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17377 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17379 // If a reference to this global requires an extra load, we can't fold it.
17380 if (isGlobalStubReference(GVFlags))
17383 // If BaseGV requires a register for the PIC base, we cannot also have a
17384 // BaseReg specified.
17385 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17388 // If lower 4G is not available, then we must use rip-relative addressing.
17389 if ((M != CodeModel::Small || R != Reloc::Static) &&
17390 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17394 switch (AM.Scale) {
17400 // These scales always work.
17405 // These scales are formed with basereg+scalereg. Only accept if there is
17410 default: // Other stuff never works.
17417 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17418 unsigned Bits = Ty->getScalarSizeInBits();
17420 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17421 // particularly cheaper than those without.
17425 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17426 // variable shifts just as cheap as scalar ones.
17427 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17430 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17431 // fully general vector.
17435 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17436 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17438 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17439 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17440 return NumBits1 > NumBits2;
17443 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17444 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17447 if (!isTypeLegal(EVT::getEVT(Ty1)))
17450 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17452 // Assuming the caller doesn't have a zeroext or signext return parameter,
17453 // truncation all the way down to i1 is valid.
17457 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17458 return isInt<32>(Imm);
17461 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17462 // Can also use sub to handle negated immediates.
17463 return isInt<32>(Imm);
17466 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17467 if (!VT1.isInteger() || !VT2.isInteger())
17469 unsigned NumBits1 = VT1.getSizeInBits();
17470 unsigned NumBits2 = VT2.getSizeInBits();
17471 return NumBits1 > NumBits2;
17474 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17475 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17476 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17479 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17480 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17481 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17484 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17485 EVT VT1 = Val.getValueType();
17486 if (isZExtFree(VT1, VT2))
17489 if (Val.getOpcode() != ISD::LOAD)
17492 if (!VT1.isSimple() || !VT1.isInteger() ||
17493 !VT2.isSimple() || !VT2.isInteger())
17496 switch (VT1.getSimpleVT().SimpleTy) {
17501 // X86 has 8, 16, and 32-bit zero-extending loads.
17508 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17511 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17512 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17515 VT = VT.getScalarType();
17517 if (!VT.isSimple())
17520 switch (VT.getSimpleVT().SimpleTy) {
17531 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17532 // i16 instructions are longer (0x66 prefix) and potentially slower.
17533 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17536 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17537 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17538 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17539 /// are assumed to be legal.
17541 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17543 if (!VT.isSimple())
17546 // Very little shuffling can be done for 64-bit vectors right now.
17547 if (VT.getSizeInBits() == 64)
17550 // We only care that the types being shuffled are legal. The lowering can
17551 // handle any possible shuffle mask that results.
17552 return isTypeLegal(VT.getSimpleVT());
17556 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17558 // Just delegate to the generic legality, clear masks aren't special.
17559 return isShuffleMaskLegal(Mask, VT);
17562 //===----------------------------------------------------------------------===//
17563 // X86 Scheduler Hooks
17564 //===----------------------------------------------------------------------===//
17566 /// Utility function to emit xbegin specifying the start of an RTM region.
17567 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17568 const TargetInstrInfo *TII) {
17569 DebugLoc DL = MI->getDebugLoc();
17571 const BasicBlock *BB = MBB->getBasicBlock();
17572 MachineFunction::iterator I = MBB;
17575 // For the v = xbegin(), we generate
17586 MachineBasicBlock *thisMBB = MBB;
17587 MachineFunction *MF = MBB->getParent();
17588 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17589 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17590 MF->insert(I, mainMBB);
17591 MF->insert(I, sinkMBB);
17593 // Transfer the remainder of BB and its successor edges to sinkMBB.
17594 sinkMBB->splice(sinkMBB->begin(), MBB,
17595 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17596 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17600 // # fallthrough to mainMBB
17601 // # abortion to sinkMBB
17602 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17603 thisMBB->addSuccessor(mainMBB);
17604 thisMBB->addSuccessor(sinkMBB);
17608 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17609 mainMBB->addSuccessor(sinkMBB);
17612 // EAX is live into the sinkMBB
17613 sinkMBB->addLiveIn(X86::EAX);
17614 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17615 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17618 MI->eraseFromParent();
17622 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17623 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17624 // in the .td file.
17625 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17626 const TargetInstrInfo *TII) {
17628 switch (MI->getOpcode()) {
17629 default: llvm_unreachable("illegal opcode!");
17630 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17631 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17632 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17633 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17634 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17635 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17636 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17637 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17640 DebugLoc dl = MI->getDebugLoc();
17641 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17643 unsigned NumArgs = MI->getNumOperands();
17644 for (unsigned i = 1; i < NumArgs; ++i) {
17645 MachineOperand &Op = MI->getOperand(i);
17646 if (!(Op.isReg() && Op.isImplicit()))
17647 MIB.addOperand(Op);
17649 if (MI->hasOneMemOperand())
17650 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17652 BuildMI(*BB, MI, dl,
17653 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17654 .addReg(X86::XMM0);
17656 MI->eraseFromParent();
17660 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17661 // defs in an instruction pattern
17662 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17663 const TargetInstrInfo *TII) {
17665 switch (MI->getOpcode()) {
17666 default: llvm_unreachable("illegal opcode!");
17667 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17668 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17669 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17670 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17671 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17672 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17673 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17674 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17677 DebugLoc dl = MI->getDebugLoc();
17678 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17680 unsigned NumArgs = MI->getNumOperands(); // remove the results
17681 for (unsigned i = 1; i < NumArgs; ++i) {
17682 MachineOperand &Op = MI->getOperand(i);
17683 if (!(Op.isReg() && Op.isImplicit()))
17684 MIB.addOperand(Op);
17686 if (MI->hasOneMemOperand())
17687 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17689 BuildMI(*BB, MI, dl,
17690 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17693 MI->eraseFromParent();
17697 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17698 const X86Subtarget *Subtarget) {
17699 DebugLoc dl = MI->getDebugLoc();
17700 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17701 // Address into RAX/EAX, other two args into ECX, EDX.
17702 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17703 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17704 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17705 for (int i = 0; i < X86::AddrNumOperands; ++i)
17706 MIB.addOperand(MI->getOperand(i));
17708 unsigned ValOps = X86::AddrNumOperands;
17709 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17710 .addReg(MI->getOperand(ValOps).getReg());
17711 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17712 .addReg(MI->getOperand(ValOps+1).getReg());
17714 // The instruction doesn't actually take any operands though.
17715 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17717 MI->eraseFromParent(); // The pseudo is gone now.
17721 MachineBasicBlock *
17722 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17723 MachineBasicBlock *MBB) const {
17724 // Emit va_arg instruction on X86-64.
17726 // Operands to this pseudo-instruction:
17727 // 0 ) Output : destination address (reg)
17728 // 1-5) Input : va_list address (addr, i64mem)
17729 // 6 ) ArgSize : Size (in bytes) of vararg type
17730 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17731 // 8 ) Align : Alignment of type
17732 // 9 ) EFLAGS (implicit-def)
17734 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17735 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17737 unsigned DestReg = MI->getOperand(0).getReg();
17738 MachineOperand &Base = MI->getOperand(1);
17739 MachineOperand &Scale = MI->getOperand(2);
17740 MachineOperand &Index = MI->getOperand(3);
17741 MachineOperand &Disp = MI->getOperand(4);
17742 MachineOperand &Segment = MI->getOperand(5);
17743 unsigned ArgSize = MI->getOperand(6).getImm();
17744 unsigned ArgMode = MI->getOperand(7).getImm();
17745 unsigned Align = MI->getOperand(8).getImm();
17747 // Memory Reference
17748 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17749 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17750 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17752 // Machine Information
17753 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17754 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17755 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17756 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17757 DebugLoc DL = MI->getDebugLoc();
17759 // struct va_list {
17762 // i64 overflow_area (address)
17763 // i64 reg_save_area (address)
17765 // sizeof(va_list) = 24
17766 // alignment(va_list) = 8
17768 unsigned TotalNumIntRegs = 6;
17769 unsigned TotalNumXMMRegs = 8;
17770 bool UseGPOffset = (ArgMode == 1);
17771 bool UseFPOffset = (ArgMode == 2);
17772 unsigned MaxOffset = TotalNumIntRegs * 8 +
17773 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17775 /* Align ArgSize to a multiple of 8 */
17776 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17777 bool NeedsAlign = (Align > 8);
17779 MachineBasicBlock *thisMBB = MBB;
17780 MachineBasicBlock *overflowMBB;
17781 MachineBasicBlock *offsetMBB;
17782 MachineBasicBlock *endMBB;
17784 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17785 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17786 unsigned OffsetReg = 0;
17788 if (!UseGPOffset && !UseFPOffset) {
17789 // If we only pull from the overflow region, we don't create a branch.
17790 // We don't need to alter control flow.
17791 OffsetDestReg = 0; // unused
17792 OverflowDestReg = DestReg;
17794 offsetMBB = nullptr;
17795 overflowMBB = thisMBB;
17798 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17799 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17800 // If not, pull from overflow_area. (branch to overflowMBB)
17805 // offsetMBB overflowMBB
17810 // Registers for the PHI in endMBB
17811 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17812 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17814 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17815 MachineFunction *MF = MBB->getParent();
17816 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17817 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17818 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17820 MachineFunction::iterator MBBIter = MBB;
17823 // Insert the new basic blocks
17824 MF->insert(MBBIter, offsetMBB);
17825 MF->insert(MBBIter, overflowMBB);
17826 MF->insert(MBBIter, endMBB);
17828 // Transfer the remainder of MBB and its successor edges to endMBB.
17829 endMBB->splice(endMBB->begin(), thisMBB,
17830 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17831 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17833 // Make offsetMBB and overflowMBB successors of thisMBB
17834 thisMBB->addSuccessor(offsetMBB);
17835 thisMBB->addSuccessor(overflowMBB);
17837 // endMBB is a successor of both offsetMBB and overflowMBB
17838 offsetMBB->addSuccessor(endMBB);
17839 overflowMBB->addSuccessor(endMBB);
17841 // Load the offset value into a register
17842 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17843 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17847 .addDisp(Disp, UseFPOffset ? 4 : 0)
17848 .addOperand(Segment)
17849 .setMemRefs(MMOBegin, MMOEnd);
17851 // Check if there is enough room left to pull this argument.
17852 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17854 .addImm(MaxOffset + 8 - ArgSizeA8);
17856 // Branch to "overflowMBB" if offset >= max
17857 // Fall through to "offsetMBB" otherwise
17858 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17859 .addMBB(overflowMBB);
17862 // In offsetMBB, emit code to use the reg_save_area.
17864 assert(OffsetReg != 0);
17866 // Read the reg_save_area address.
17867 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17868 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17873 .addOperand(Segment)
17874 .setMemRefs(MMOBegin, MMOEnd);
17876 // Zero-extend the offset
17877 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17878 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17881 .addImm(X86::sub_32bit);
17883 // Add the offset to the reg_save_area to get the final address.
17884 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17885 .addReg(OffsetReg64)
17886 .addReg(RegSaveReg);
17888 // Compute the offset for the next argument
17889 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17890 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17892 .addImm(UseFPOffset ? 16 : 8);
17894 // Store it back into the va_list.
17895 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17899 .addDisp(Disp, UseFPOffset ? 4 : 0)
17900 .addOperand(Segment)
17901 .addReg(NextOffsetReg)
17902 .setMemRefs(MMOBegin, MMOEnd);
17905 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
17910 // Emit code to use overflow area
17913 // Load the overflow_area address into a register.
17914 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17915 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17920 .addOperand(Segment)
17921 .setMemRefs(MMOBegin, MMOEnd);
17923 // If we need to align it, do so. Otherwise, just copy the address
17924 // to OverflowDestReg.
17926 // Align the overflow address
17927 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17928 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17930 // aligned_addr = (addr + (align-1)) & ~(align-1)
17931 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17932 .addReg(OverflowAddrReg)
17935 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17937 .addImm(~(uint64_t)(Align-1));
17939 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17940 .addReg(OverflowAddrReg);
17943 // Compute the next overflow address after this argument.
17944 // (the overflow address should be kept 8-byte aligned)
17945 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17946 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17947 .addReg(OverflowDestReg)
17948 .addImm(ArgSizeA8);
17950 // Store the new overflow address.
17951 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17956 .addOperand(Segment)
17957 .addReg(NextAddrReg)
17958 .setMemRefs(MMOBegin, MMOEnd);
17960 // If we branched, emit the PHI to the front of endMBB.
17962 BuildMI(*endMBB, endMBB->begin(), DL,
17963 TII->get(X86::PHI), DestReg)
17964 .addReg(OffsetDestReg).addMBB(offsetMBB)
17965 .addReg(OverflowDestReg).addMBB(overflowMBB);
17968 // Erase the pseudo instruction
17969 MI->eraseFromParent();
17974 MachineBasicBlock *
17975 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17977 MachineBasicBlock *MBB) const {
17978 // Emit code to save XMM registers to the stack. The ABI says that the
17979 // number of registers to save is given in %al, so it's theoretically
17980 // possible to do an indirect jump trick to avoid saving all of them,
17981 // however this code takes a simpler approach and just executes all
17982 // of the stores if %al is non-zero. It's less code, and it's probably
17983 // easier on the hardware branch predictor, and stores aren't all that
17984 // expensive anyway.
17986 // Create the new basic blocks. One block contains all the XMM stores,
17987 // and one block is the final destination regardless of whether any
17988 // stores were performed.
17989 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17990 MachineFunction *F = MBB->getParent();
17991 MachineFunction::iterator MBBIter = MBB;
17993 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17994 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17995 F->insert(MBBIter, XMMSaveMBB);
17996 F->insert(MBBIter, EndMBB);
17998 // Transfer the remainder of MBB and its successor edges to EndMBB.
17999 EndMBB->splice(EndMBB->begin(), MBB,
18000 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18001 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18003 // The original block will now fall through to the XMM save block.
18004 MBB->addSuccessor(XMMSaveMBB);
18005 // The XMMSaveMBB will fall through to the end block.
18006 XMMSaveMBB->addSuccessor(EndMBB);
18008 // Now add the instructions.
18009 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18010 DebugLoc DL = MI->getDebugLoc();
18012 unsigned CountReg = MI->getOperand(0).getReg();
18013 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18014 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18016 if (!Subtarget->isTargetWin64()) {
18017 // If %al is 0, branch around the XMM save block.
18018 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18019 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18020 MBB->addSuccessor(EndMBB);
18023 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18024 // that was just emitted, but clearly shouldn't be "saved".
18025 assert((MI->getNumOperands() <= 3 ||
18026 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18027 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18028 && "Expected last argument to be EFLAGS");
18029 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18030 // In the XMM save block, save all the XMM argument registers.
18031 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18032 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18033 MachineMemOperand *MMO =
18034 F->getMachineMemOperand(
18035 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18036 MachineMemOperand::MOStore,
18037 /*Size=*/16, /*Align=*/16);
18038 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18039 .addFrameIndex(RegSaveFrameIndex)
18040 .addImm(/*Scale=*/1)
18041 .addReg(/*IndexReg=*/0)
18042 .addImm(/*Disp=*/Offset)
18043 .addReg(/*Segment=*/0)
18044 .addReg(MI->getOperand(i).getReg())
18045 .addMemOperand(MMO);
18048 MI->eraseFromParent(); // The pseudo instruction is gone now.
18053 // The EFLAGS operand of SelectItr might be missing a kill marker
18054 // because there were multiple uses of EFLAGS, and ISel didn't know
18055 // which to mark. Figure out whether SelectItr should have had a
18056 // kill marker, and set it if it should. Returns the correct kill
18058 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18059 MachineBasicBlock* BB,
18060 const TargetRegisterInfo* TRI) {
18061 // Scan forward through BB for a use/def of EFLAGS.
18062 MachineBasicBlock::iterator miI(std::next(SelectItr));
18063 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18064 const MachineInstr& mi = *miI;
18065 if (mi.readsRegister(X86::EFLAGS))
18067 if (mi.definesRegister(X86::EFLAGS))
18068 break; // Should have kill-flag - update below.
18071 // If we hit the end of the block, check whether EFLAGS is live into a
18073 if (miI == BB->end()) {
18074 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18075 sEnd = BB->succ_end();
18076 sItr != sEnd; ++sItr) {
18077 MachineBasicBlock* succ = *sItr;
18078 if (succ->isLiveIn(X86::EFLAGS))
18083 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18084 // out. SelectMI should have a kill flag on EFLAGS.
18085 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18089 MachineBasicBlock *
18090 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18091 MachineBasicBlock *BB) const {
18092 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18093 DebugLoc DL = MI->getDebugLoc();
18095 // To "insert" a SELECT_CC instruction, we actually have to insert the
18096 // diamond control-flow pattern. The incoming instruction knows the
18097 // destination vreg to set, the condition code register to branch on, the
18098 // true/false values to select between, and a branch opcode to use.
18099 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18100 MachineFunction::iterator It = BB;
18106 // cmpTY ccX, r1, r2
18108 // fallthrough --> copy0MBB
18109 MachineBasicBlock *thisMBB = BB;
18110 MachineFunction *F = BB->getParent();
18112 // We also lower double CMOVs:
18113 // (CMOV (CMOV F, T, cc1), T, cc2)
18114 // to two successives branches. For that, we look for another CMOV as the
18115 // following instruction.
18117 // Without this, we would add a PHI between the two jumps, which ends up
18118 // creating a few copies all around. For instance, for
18120 // (sitofp (zext (fcmp une)))
18122 // we would generate:
18124 // ucomiss %xmm1, %xmm0
18125 // movss <1.0f>, %xmm0
18126 // movaps %xmm0, %xmm1
18128 // xorps %xmm1, %xmm1
18131 // movaps %xmm1, %xmm0
18135 // because this custom-inserter would have generated:
18147 // A: X = ...; Y = ...
18149 // C: Z = PHI [X, A], [Y, B]
18151 // E: PHI [X, C], [Z, D]
18153 // If we lower both CMOVs in a single step, we can instead generate:
18165 // A: X = ...; Y = ...
18167 // E: PHI [X, A], [X, C], [Y, D]
18169 // Which, in our sitofp/fcmp example, gives us something like:
18171 // ucomiss %xmm1, %xmm0
18172 // movss <1.0f>, %xmm0
18175 // xorps %xmm0, %xmm0
18179 MachineInstr *NextCMOV = nullptr;
18180 MachineBasicBlock::iterator NextMIIt =
18181 std::next(MachineBasicBlock::iterator(MI));
18182 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18183 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18184 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18185 NextCMOV = &*NextMIIt;
18187 MachineBasicBlock *jcc1MBB = nullptr;
18189 // If we have a double CMOV, we lower it to two successive branches to
18190 // the same block. EFLAGS is used by both, so mark it as live in the second.
18192 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18193 F->insert(It, jcc1MBB);
18194 jcc1MBB->addLiveIn(X86::EFLAGS);
18197 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18198 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18199 F->insert(It, copy0MBB);
18200 F->insert(It, sinkMBB);
18202 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18203 // live into the sink and copy blocks.
18204 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18206 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18207 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18208 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18209 copy0MBB->addLiveIn(X86::EFLAGS);
18210 sinkMBB->addLiveIn(X86::EFLAGS);
18213 // Transfer the remainder of BB and its successor edges to sinkMBB.
18214 sinkMBB->splice(sinkMBB->begin(), BB,
18215 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18216 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18218 // Add the true and fallthrough blocks as its successors.
18220 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18221 BB->addSuccessor(jcc1MBB);
18223 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18224 // jump to the sinkMBB.
18225 jcc1MBB->addSuccessor(copy0MBB);
18226 jcc1MBB->addSuccessor(sinkMBB);
18228 BB->addSuccessor(copy0MBB);
18231 // The true block target of the first (or only) branch is always sinkMBB.
18232 BB->addSuccessor(sinkMBB);
18234 // Create the conditional branch instruction.
18236 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18237 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18240 unsigned Opc2 = X86::GetCondBranchFromCond(
18241 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18242 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18246 // %FalseValue = ...
18247 // # fallthrough to sinkMBB
18248 copy0MBB->addSuccessor(sinkMBB);
18251 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18253 MachineInstrBuilder MIB =
18254 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18255 MI->getOperand(0).getReg())
18256 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18257 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18259 // If we have a double CMOV, the second Jcc provides the same incoming
18260 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18262 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18263 // Copy the PHI result to the register defined by the second CMOV.
18264 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18265 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18266 .addReg(MI->getOperand(0).getReg());
18267 NextCMOV->eraseFromParent();
18270 MI->eraseFromParent(); // The pseudo instruction is gone now.
18274 MachineBasicBlock *
18275 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18276 MachineBasicBlock *BB) const {
18277 MachineFunction *MF = BB->getParent();
18278 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18279 DebugLoc DL = MI->getDebugLoc();
18280 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18282 assert(MF->shouldSplitStack());
18284 const bool Is64Bit = Subtarget->is64Bit();
18285 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18287 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18288 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18291 // ... [Till the alloca]
18292 // If stacklet is not large enough, jump to mallocMBB
18295 // Allocate by subtracting from RSP
18296 // Jump to continueMBB
18299 // Allocate by call to runtime
18303 // [rest of original BB]
18306 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18307 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18308 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18310 MachineRegisterInfo &MRI = MF->getRegInfo();
18311 const TargetRegisterClass *AddrRegClass =
18312 getRegClassFor(getPointerTy());
18314 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18315 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18316 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18317 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18318 sizeVReg = MI->getOperand(1).getReg(),
18319 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18321 MachineFunction::iterator MBBIter = BB;
18324 MF->insert(MBBIter, bumpMBB);
18325 MF->insert(MBBIter, mallocMBB);
18326 MF->insert(MBBIter, continueMBB);
18328 continueMBB->splice(continueMBB->begin(), BB,
18329 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18330 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18332 // Add code to the main basic block to check if the stack limit has been hit,
18333 // and if so, jump to mallocMBB otherwise to bumpMBB.
18334 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18335 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18336 .addReg(tmpSPVReg).addReg(sizeVReg);
18337 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18338 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18339 .addReg(SPLimitVReg);
18340 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18342 // bumpMBB simply decreases the stack pointer, since we know the current
18343 // stacklet has enough space.
18344 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18345 .addReg(SPLimitVReg);
18346 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18347 .addReg(SPLimitVReg);
18348 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18350 // Calls into a routine in libgcc to allocate more space from the heap.
18351 const uint32_t *RegMask =
18352 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18354 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18356 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18357 .addExternalSymbol("__morestack_allocate_stack_space")
18358 .addRegMask(RegMask)
18359 .addReg(X86::RDI, RegState::Implicit)
18360 .addReg(X86::RAX, RegState::ImplicitDefine);
18361 } else if (Is64Bit) {
18362 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18364 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18365 .addExternalSymbol("__morestack_allocate_stack_space")
18366 .addRegMask(RegMask)
18367 .addReg(X86::EDI, RegState::Implicit)
18368 .addReg(X86::EAX, RegState::ImplicitDefine);
18370 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18372 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18373 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18374 .addExternalSymbol("__morestack_allocate_stack_space")
18375 .addRegMask(RegMask)
18376 .addReg(X86::EAX, RegState::ImplicitDefine);
18380 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18383 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18384 .addReg(IsLP64 ? X86::RAX : X86::EAX);
18385 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18387 // Set up the CFG correctly.
18388 BB->addSuccessor(bumpMBB);
18389 BB->addSuccessor(mallocMBB);
18390 mallocMBB->addSuccessor(continueMBB);
18391 bumpMBB->addSuccessor(continueMBB);
18393 // Take care of the PHI nodes.
18394 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18395 MI->getOperand(0).getReg())
18396 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18397 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18399 // Delete the original pseudo instruction.
18400 MI->eraseFromParent();
18403 return continueMBB;
18406 MachineBasicBlock *
18407 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18408 MachineBasicBlock *BB) const {
18409 DebugLoc DL = MI->getDebugLoc();
18411 assert(!Subtarget->isTargetMachO());
18413 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18415 MI->eraseFromParent(); // The pseudo instruction is gone now.
18419 MachineBasicBlock *
18420 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18421 MachineBasicBlock *BB) const {
18422 // This is pretty easy. We're taking the value that we received from
18423 // our load from the relocation, sticking it in either RDI (x86-64)
18424 // or EAX and doing an indirect call. The return value will then
18425 // be in the normal return register.
18426 MachineFunction *F = BB->getParent();
18427 const X86InstrInfo *TII = Subtarget->getInstrInfo();
18428 DebugLoc DL = MI->getDebugLoc();
18430 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18431 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18433 // Get a register mask for the lowered call.
18434 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18435 // proper register mask.
18436 const uint32_t *RegMask =
18437 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18438 if (Subtarget->is64Bit()) {
18439 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18440 TII->get(X86::MOV64rm), X86::RDI)
18442 .addImm(0).addReg(0)
18443 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18444 MI->getOperand(3).getTargetFlags())
18446 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18447 addDirectMem(MIB, X86::RDI);
18448 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18449 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18450 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18451 TII->get(X86::MOV32rm), X86::EAX)
18453 .addImm(0).addReg(0)
18454 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18455 MI->getOperand(3).getTargetFlags())
18457 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18458 addDirectMem(MIB, X86::EAX);
18459 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18461 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18462 TII->get(X86::MOV32rm), X86::EAX)
18463 .addReg(TII->getGlobalBaseReg(F))
18464 .addImm(0).addReg(0)
18465 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18466 MI->getOperand(3).getTargetFlags())
18468 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18469 addDirectMem(MIB, X86::EAX);
18470 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18473 MI->eraseFromParent(); // The pseudo instruction is gone now.
18477 MachineBasicBlock *
18478 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18479 MachineBasicBlock *MBB) const {
18480 DebugLoc DL = MI->getDebugLoc();
18481 MachineFunction *MF = MBB->getParent();
18482 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18483 MachineRegisterInfo &MRI = MF->getRegInfo();
18485 const BasicBlock *BB = MBB->getBasicBlock();
18486 MachineFunction::iterator I = MBB;
18489 // Memory Reference
18490 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18491 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18494 unsigned MemOpndSlot = 0;
18496 unsigned CurOp = 0;
18498 DstReg = MI->getOperand(CurOp++).getReg();
18499 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18500 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18501 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18502 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18504 MemOpndSlot = CurOp;
18506 MVT PVT = getPointerTy();
18507 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18508 "Invalid Pointer Size!");
18510 // For v = setjmp(buf), we generate
18513 // buf[LabelOffset] = restoreMBB
18514 // SjLjSetup restoreMBB
18520 // v = phi(main, restore)
18523 // if base pointer being used, load it from frame
18526 MachineBasicBlock *thisMBB = MBB;
18527 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18528 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18529 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18530 MF->insert(I, mainMBB);
18531 MF->insert(I, sinkMBB);
18532 MF->push_back(restoreMBB);
18534 MachineInstrBuilder MIB;
18536 // Transfer the remainder of BB and its successor edges to sinkMBB.
18537 sinkMBB->splice(sinkMBB->begin(), MBB,
18538 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18539 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18542 unsigned PtrStoreOpc = 0;
18543 unsigned LabelReg = 0;
18544 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18545 Reloc::Model RM = MF->getTarget().getRelocationModel();
18546 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18547 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18549 // Prepare IP either in reg or imm.
18550 if (!UseImmLabel) {
18551 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18552 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18553 LabelReg = MRI.createVirtualRegister(PtrRC);
18554 if (Subtarget->is64Bit()) {
18555 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18559 .addMBB(restoreMBB)
18562 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18563 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18564 .addReg(XII->getGlobalBaseReg(MF))
18567 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18571 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18573 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18574 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18575 if (i == X86::AddrDisp)
18576 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18578 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18581 MIB.addReg(LabelReg);
18583 MIB.addMBB(restoreMBB);
18584 MIB.setMemRefs(MMOBegin, MMOEnd);
18586 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18587 .addMBB(restoreMBB);
18589 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18590 MIB.addRegMask(RegInfo->getNoPreservedMask());
18591 thisMBB->addSuccessor(mainMBB);
18592 thisMBB->addSuccessor(restoreMBB);
18596 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18597 mainMBB->addSuccessor(sinkMBB);
18600 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18601 TII->get(X86::PHI), DstReg)
18602 .addReg(mainDstReg).addMBB(mainMBB)
18603 .addReg(restoreDstReg).addMBB(restoreMBB);
18606 if (RegInfo->hasBasePointer(*MF)) {
18607 const bool Uses64BitFramePtr =
18608 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18609 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18610 X86FI->setRestoreBasePointer(MF);
18611 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18612 unsigned BasePtr = RegInfo->getBaseRegister();
18613 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18614 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18615 FramePtr, true, X86FI->getRestoreBasePointerOffset())
18616 .setMIFlag(MachineInstr::FrameSetup);
18618 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18619 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18620 restoreMBB->addSuccessor(sinkMBB);
18622 MI->eraseFromParent();
18626 MachineBasicBlock *
18627 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18628 MachineBasicBlock *MBB) const {
18629 DebugLoc DL = MI->getDebugLoc();
18630 MachineFunction *MF = MBB->getParent();
18631 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18632 MachineRegisterInfo &MRI = MF->getRegInfo();
18634 // Memory Reference
18635 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18636 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18638 MVT PVT = getPointerTy();
18639 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18640 "Invalid Pointer Size!");
18642 const TargetRegisterClass *RC =
18643 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18644 unsigned Tmp = MRI.createVirtualRegister(RC);
18645 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18646 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18647 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18648 unsigned SP = RegInfo->getStackRegister();
18650 MachineInstrBuilder MIB;
18652 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18653 const int64_t SPOffset = 2 * PVT.getStoreSize();
18655 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18656 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18659 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18660 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18661 MIB.addOperand(MI->getOperand(i));
18662 MIB.setMemRefs(MMOBegin, MMOEnd);
18664 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18665 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18666 if (i == X86::AddrDisp)
18667 MIB.addDisp(MI->getOperand(i), LabelOffset);
18669 MIB.addOperand(MI->getOperand(i));
18671 MIB.setMemRefs(MMOBegin, MMOEnd);
18673 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18674 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18675 if (i == X86::AddrDisp)
18676 MIB.addDisp(MI->getOperand(i), SPOffset);
18678 MIB.addOperand(MI->getOperand(i));
18680 MIB.setMemRefs(MMOBegin, MMOEnd);
18682 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18684 MI->eraseFromParent();
18688 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18689 // accumulator loops. Writing back to the accumulator allows the coalescer
18690 // to remove extra copies in the loop.
18691 MachineBasicBlock *
18692 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18693 MachineBasicBlock *MBB) const {
18694 MachineOperand &AddendOp = MI->getOperand(3);
18696 // Bail out early if the addend isn't a register - we can't switch these.
18697 if (!AddendOp.isReg())
18700 MachineFunction &MF = *MBB->getParent();
18701 MachineRegisterInfo &MRI = MF.getRegInfo();
18703 // Check whether the addend is defined by a PHI:
18704 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18705 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18706 if (!AddendDef.isPHI())
18709 // Look for the following pattern:
18711 // %addend = phi [%entry, 0], [%loop, %result]
18713 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18717 // %addend = phi [%entry, 0], [%loop, %result]
18719 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18721 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18722 assert(AddendDef.getOperand(i).isReg());
18723 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18724 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18725 if (&PHISrcInst == MI) {
18726 // Found a matching instruction.
18727 unsigned NewFMAOpc = 0;
18728 switch (MI->getOpcode()) {
18729 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18730 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18731 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18732 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18733 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18734 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18735 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18736 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18737 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18738 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18739 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18740 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18741 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18742 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18743 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18744 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18745 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18746 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18747 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18748 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18750 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18751 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18752 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18753 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18754 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18755 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18756 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18757 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18758 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18759 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18760 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18761 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18762 default: llvm_unreachable("Unrecognized FMA variant.");
18765 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18766 MachineInstrBuilder MIB =
18767 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18768 .addOperand(MI->getOperand(0))
18769 .addOperand(MI->getOperand(3))
18770 .addOperand(MI->getOperand(2))
18771 .addOperand(MI->getOperand(1));
18772 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18773 MI->eraseFromParent();
18780 MachineBasicBlock *
18781 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18782 MachineBasicBlock *BB) const {
18783 switch (MI->getOpcode()) {
18784 default: llvm_unreachable("Unexpected instr type to insert");
18785 case X86::TAILJMPd64:
18786 case X86::TAILJMPr64:
18787 case X86::TAILJMPm64:
18788 case X86::TAILJMPd64_REX:
18789 case X86::TAILJMPr64_REX:
18790 case X86::TAILJMPm64_REX:
18791 llvm_unreachable("TAILJMP64 would not be touched here.");
18792 case X86::TCRETURNdi64:
18793 case X86::TCRETURNri64:
18794 case X86::TCRETURNmi64:
18796 case X86::WIN_ALLOCA:
18797 return EmitLoweredWinAlloca(MI, BB);
18798 case X86::SEG_ALLOCA_32:
18799 case X86::SEG_ALLOCA_64:
18800 return EmitLoweredSegAlloca(MI, BB);
18801 case X86::TLSCall_32:
18802 case X86::TLSCall_64:
18803 return EmitLoweredTLSCall(MI, BB);
18804 case X86::CMOV_GR8:
18805 case X86::CMOV_FR32:
18806 case X86::CMOV_FR64:
18807 case X86::CMOV_V4F32:
18808 case X86::CMOV_V2F64:
18809 case X86::CMOV_V2I64:
18810 case X86::CMOV_V8F32:
18811 case X86::CMOV_V4F64:
18812 case X86::CMOV_V4I64:
18813 case X86::CMOV_V16F32:
18814 case X86::CMOV_V8F64:
18815 case X86::CMOV_V8I64:
18816 case X86::CMOV_GR16:
18817 case X86::CMOV_GR32:
18818 case X86::CMOV_RFP32:
18819 case X86::CMOV_RFP64:
18820 case X86::CMOV_RFP80:
18821 return EmitLoweredSelect(MI, BB);
18823 case X86::FP32_TO_INT16_IN_MEM:
18824 case X86::FP32_TO_INT32_IN_MEM:
18825 case X86::FP32_TO_INT64_IN_MEM:
18826 case X86::FP64_TO_INT16_IN_MEM:
18827 case X86::FP64_TO_INT32_IN_MEM:
18828 case X86::FP64_TO_INT64_IN_MEM:
18829 case X86::FP80_TO_INT16_IN_MEM:
18830 case X86::FP80_TO_INT32_IN_MEM:
18831 case X86::FP80_TO_INT64_IN_MEM: {
18832 MachineFunction *F = BB->getParent();
18833 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18834 DebugLoc DL = MI->getDebugLoc();
18836 // Change the floating point control register to use "round towards zero"
18837 // mode when truncating to an integer value.
18838 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18839 addFrameReference(BuildMI(*BB, MI, DL,
18840 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18842 // Load the old value of the high byte of the control word...
18844 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18845 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18848 // Set the high part to be round to zero...
18849 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18852 // Reload the modified control word now...
18853 addFrameReference(BuildMI(*BB, MI, DL,
18854 TII->get(X86::FLDCW16m)), CWFrameIdx);
18856 // Restore the memory image of control word to original value
18857 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18860 // Get the X86 opcode to use.
18862 switch (MI->getOpcode()) {
18863 default: llvm_unreachable("illegal opcode!");
18864 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18865 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18866 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18867 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18868 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18869 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18870 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18871 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18872 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18876 MachineOperand &Op = MI->getOperand(0);
18878 AM.BaseType = X86AddressMode::RegBase;
18879 AM.Base.Reg = Op.getReg();
18881 AM.BaseType = X86AddressMode::FrameIndexBase;
18882 AM.Base.FrameIndex = Op.getIndex();
18884 Op = MI->getOperand(1);
18886 AM.Scale = Op.getImm();
18887 Op = MI->getOperand(2);
18889 AM.IndexReg = Op.getImm();
18890 Op = MI->getOperand(3);
18891 if (Op.isGlobal()) {
18892 AM.GV = Op.getGlobal();
18894 AM.Disp = Op.getImm();
18896 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18897 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18899 // Reload the original control word now.
18900 addFrameReference(BuildMI(*BB, MI, DL,
18901 TII->get(X86::FLDCW16m)), CWFrameIdx);
18903 MI->eraseFromParent(); // The pseudo instruction is gone now.
18906 // String/text processing lowering.
18907 case X86::PCMPISTRM128REG:
18908 case X86::VPCMPISTRM128REG:
18909 case X86::PCMPISTRM128MEM:
18910 case X86::VPCMPISTRM128MEM:
18911 case X86::PCMPESTRM128REG:
18912 case X86::VPCMPESTRM128REG:
18913 case X86::PCMPESTRM128MEM:
18914 case X86::VPCMPESTRM128MEM:
18915 assert(Subtarget->hasSSE42() &&
18916 "Target must have SSE4.2 or AVX features enabled");
18917 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
18919 // String/text processing lowering.
18920 case X86::PCMPISTRIREG:
18921 case X86::VPCMPISTRIREG:
18922 case X86::PCMPISTRIMEM:
18923 case X86::VPCMPISTRIMEM:
18924 case X86::PCMPESTRIREG:
18925 case X86::VPCMPESTRIREG:
18926 case X86::PCMPESTRIMEM:
18927 case X86::VPCMPESTRIMEM:
18928 assert(Subtarget->hasSSE42() &&
18929 "Target must have SSE4.2 or AVX features enabled");
18930 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
18932 // Thread synchronization.
18934 return EmitMonitor(MI, BB, Subtarget);
18938 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
18940 case X86::VASTART_SAVE_XMM_REGS:
18941 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18943 case X86::VAARG_64:
18944 return EmitVAARG64WithCustomInserter(MI, BB);
18946 case X86::EH_SjLj_SetJmp32:
18947 case X86::EH_SjLj_SetJmp64:
18948 return emitEHSjLjSetJmp(MI, BB);
18950 case X86::EH_SjLj_LongJmp32:
18951 case X86::EH_SjLj_LongJmp64:
18952 return emitEHSjLjLongJmp(MI, BB);
18954 case TargetOpcode::STATEPOINT:
18955 // As an implementation detail, STATEPOINT shares the STACKMAP format at
18956 // this point in the process. We diverge later.
18957 return emitPatchPoint(MI, BB);
18959 case TargetOpcode::STACKMAP:
18960 case TargetOpcode::PATCHPOINT:
18961 return emitPatchPoint(MI, BB);
18963 case X86::VFMADDPDr213r:
18964 case X86::VFMADDPSr213r:
18965 case X86::VFMADDSDr213r:
18966 case X86::VFMADDSSr213r:
18967 case X86::VFMSUBPDr213r:
18968 case X86::VFMSUBPSr213r:
18969 case X86::VFMSUBSDr213r:
18970 case X86::VFMSUBSSr213r:
18971 case X86::VFNMADDPDr213r:
18972 case X86::VFNMADDPSr213r:
18973 case X86::VFNMADDSDr213r:
18974 case X86::VFNMADDSSr213r:
18975 case X86::VFNMSUBPDr213r:
18976 case X86::VFNMSUBPSr213r:
18977 case X86::VFNMSUBSDr213r:
18978 case X86::VFNMSUBSSr213r:
18979 case X86::VFMADDSUBPDr213r:
18980 case X86::VFMADDSUBPSr213r:
18981 case X86::VFMSUBADDPDr213r:
18982 case X86::VFMSUBADDPSr213r:
18983 case X86::VFMADDPDr213rY:
18984 case X86::VFMADDPSr213rY:
18985 case X86::VFMSUBPDr213rY:
18986 case X86::VFMSUBPSr213rY:
18987 case X86::VFNMADDPDr213rY:
18988 case X86::VFNMADDPSr213rY:
18989 case X86::VFNMSUBPDr213rY:
18990 case X86::VFNMSUBPSr213rY:
18991 case X86::VFMADDSUBPDr213rY:
18992 case X86::VFMADDSUBPSr213rY:
18993 case X86::VFMSUBADDPDr213rY:
18994 case X86::VFMSUBADDPSr213rY:
18995 return emitFMA3Instr(MI, BB);
18999 //===----------------------------------------------------------------------===//
19000 // X86 Optimization Hooks
19001 //===----------------------------------------------------------------------===//
19003 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19006 const SelectionDAG &DAG,
19007 unsigned Depth) const {
19008 unsigned BitWidth = KnownZero.getBitWidth();
19009 unsigned Opc = Op.getOpcode();
19010 assert((Opc >= ISD::BUILTIN_OP_END ||
19011 Opc == ISD::INTRINSIC_WO_CHAIN ||
19012 Opc == ISD::INTRINSIC_W_CHAIN ||
19013 Opc == ISD::INTRINSIC_VOID) &&
19014 "Should use MaskedValueIsZero if you don't know whether Op"
19015 " is a target node!");
19017 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19031 // These nodes' second result is a boolean.
19032 if (Op.getResNo() == 0)
19035 case X86ISD::SETCC:
19036 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19038 case ISD::INTRINSIC_WO_CHAIN: {
19039 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19040 unsigned NumLoBits = 0;
19043 case Intrinsic::x86_sse_movmsk_ps:
19044 case Intrinsic::x86_avx_movmsk_ps_256:
19045 case Intrinsic::x86_sse2_movmsk_pd:
19046 case Intrinsic::x86_avx_movmsk_pd_256:
19047 case Intrinsic::x86_mmx_pmovmskb:
19048 case Intrinsic::x86_sse2_pmovmskb_128:
19049 case Intrinsic::x86_avx2_pmovmskb: {
19050 // High bits of movmskp{s|d}, pmovmskb are known zero.
19052 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19053 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19054 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19055 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19056 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19057 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19058 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19059 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19061 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19070 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19072 const SelectionDAG &,
19073 unsigned Depth) const {
19074 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19075 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19076 return Op.getValueType().getScalarType().getSizeInBits();
19082 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19083 /// node is a GlobalAddress + offset.
19084 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19085 const GlobalValue* &GA,
19086 int64_t &Offset) const {
19087 if (N->getOpcode() == X86ISD::Wrapper) {
19088 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19089 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19090 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19094 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19097 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19098 /// same as extracting the high 128-bit part of 256-bit vector and then
19099 /// inserting the result into the low part of a new 256-bit vector
19100 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19101 EVT VT = SVOp->getValueType(0);
19102 unsigned NumElems = VT.getVectorNumElements();
19104 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19105 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19106 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19107 SVOp->getMaskElt(j) >= 0)
19113 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19114 /// same as extracting the low 128-bit part of 256-bit vector and then
19115 /// inserting the result into the high part of a new 256-bit vector
19116 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19117 EVT VT = SVOp->getValueType(0);
19118 unsigned NumElems = VT.getVectorNumElements();
19120 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19121 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19122 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19123 SVOp->getMaskElt(j) >= 0)
19129 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19130 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19131 TargetLowering::DAGCombinerInfo &DCI,
19132 const X86Subtarget* Subtarget) {
19134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19135 SDValue V1 = SVOp->getOperand(0);
19136 SDValue V2 = SVOp->getOperand(1);
19137 EVT VT = SVOp->getValueType(0);
19138 unsigned NumElems = VT.getVectorNumElements();
19140 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19141 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19145 // V UNDEF BUILD_VECTOR UNDEF
19147 // CONCAT_VECTOR CONCAT_VECTOR
19150 // RESULT: V + zero extended
19152 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19153 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19154 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19157 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19160 // To match the shuffle mask, the first half of the mask should
19161 // be exactly the first vector, and all the rest a splat with the
19162 // first element of the second one.
19163 for (unsigned i = 0; i != NumElems/2; ++i)
19164 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19165 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19168 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19169 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19170 if (Ld->hasNUsesOfValue(1, 0)) {
19171 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19172 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19174 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19176 Ld->getPointerInfo(),
19177 Ld->getAlignment(),
19178 false/*isVolatile*/, true/*ReadMem*/,
19179 false/*WriteMem*/);
19181 // Make sure the newly-created LOAD is in the same position as Ld in
19182 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19183 // and update uses of Ld's output chain to use the TokenFactor.
19184 if (Ld->hasAnyUseOfValue(1)) {
19185 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19186 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19187 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19188 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19189 SDValue(ResNode.getNode(), 1));
19192 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19196 // Emit a zeroed vector and insert the desired subvector on its
19198 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19199 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19200 return DCI.CombineTo(N, InsV);
19203 //===--------------------------------------------------------------------===//
19204 // Combine some shuffles into subvector extracts and inserts:
19207 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19208 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19209 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19210 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19211 return DCI.CombineTo(N, InsV);
19214 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19215 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19216 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19217 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19218 return DCI.CombineTo(N, InsV);
19224 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19227 /// This is the leaf of the recursive combinine below. When we have found some
19228 /// chain of single-use x86 shuffle instructions and accumulated the combined
19229 /// shuffle mask represented by them, this will try to pattern match that mask
19230 /// into either a single instruction if there is a special purpose instruction
19231 /// for this operation, or into a PSHUFB instruction which is a fully general
19232 /// instruction but should only be used to replace chains over a certain depth.
19233 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19234 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19235 TargetLowering::DAGCombinerInfo &DCI,
19236 const X86Subtarget *Subtarget) {
19237 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19239 // Find the operand that enters the chain. Note that multiple uses are OK
19240 // here, we're not going to remove the operand we find.
19241 SDValue Input = Op.getOperand(0);
19242 while (Input.getOpcode() == ISD::BITCAST)
19243 Input = Input.getOperand(0);
19245 MVT VT = Input.getSimpleValueType();
19246 MVT RootVT = Root.getSimpleValueType();
19249 // Just remove no-op shuffle masks.
19250 if (Mask.size() == 1) {
19251 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19256 // Use the float domain if the operand type is a floating point type.
19257 bool FloatDomain = VT.isFloatingPoint();
19259 // For floating point shuffles, we don't have free copies in the shuffle
19260 // instructions or the ability to load as part of the instruction, so
19261 // canonicalize their shuffles to UNPCK or MOV variants.
19263 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19264 // vectors because it can have a load folded into it that UNPCK cannot. This
19265 // doesn't preclude something switching to the shorter encoding post-RA.
19267 // FIXME: Should teach these routines about AVX vector widths.
19268 if (FloatDomain && VT.getSizeInBits() == 128) {
19269 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19270 bool Lo = Mask.equals({0, 0});
19273 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19274 // is no slower than UNPCKLPD but has the option to fold the input operand
19275 // into even an unaligned memory load.
19276 if (Lo && Subtarget->hasSSE3()) {
19277 Shuffle = X86ISD::MOVDDUP;
19278 ShuffleVT = MVT::v2f64;
19280 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19281 // than the UNPCK variants.
19282 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19283 ShuffleVT = MVT::v4f32;
19285 if (Depth == 1 && Root->getOpcode() == Shuffle)
19286 return false; // Nothing to do!
19287 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19288 DCI.AddToWorklist(Op.getNode());
19289 if (Shuffle == X86ISD::MOVDDUP)
19290 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19292 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19293 DCI.AddToWorklist(Op.getNode());
19294 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19298 if (Subtarget->hasSSE3() &&
19299 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19300 bool Lo = Mask.equals({0, 0, 2, 2});
19301 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19302 MVT ShuffleVT = MVT::v4f32;
19303 if (Depth == 1 && Root->getOpcode() == Shuffle)
19304 return false; // Nothing to do!
19305 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19306 DCI.AddToWorklist(Op.getNode());
19307 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19308 DCI.AddToWorklist(Op.getNode());
19309 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19313 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19314 bool Lo = Mask.equals({0, 0, 1, 1});
19315 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19316 MVT ShuffleVT = MVT::v4f32;
19317 if (Depth == 1 && Root->getOpcode() == Shuffle)
19318 return false; // Nothing to do!
19319 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19320 DCI.AddToWorklist(Op.getNode());
19321 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19322 DCI.AddToWorklist(Op.getNode());
19323 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19329 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19330 // variants as none of these have single-instruction variants that are
19331 // superior to the UNPCK formulation.
19332 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19333 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19334 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19335 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19337 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19338 bool Lo = Mask[0] == 0;
19339 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19340 if (Depth == 1 && Root->getOpcode() == Shuffle)
19341 return false; // Nothing to do!
19343 switch (Mask.size()) {
19345 ShuffleVT = MVT::v8i16;
19348 ShuffleVT = MVT::v16i8;
19351 llvm_unreachable("Impossible mask size!");
19353 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19354 DCI.AddToWorklist(Op.getNode());
19355 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19356 DCI.AddToWorklist(Op.getNode());
19357 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19362 // Don't try to re-form single instruction chains under any circumstances now
19363 // that we've done encoding canonicalization for them.
19367 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19368 // can replace them with a single PSHUFB instruction profitably. Intel's
19369 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19370 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19371 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19372 SmallVector<SDValue, 16> PSHUFBMask;
19373 int NumBytes = VT.getSizeInBits() / 8;
19374 int Ratio = NumBytes / Mask.size();
19375 for (int i = 0; i < NumBytes; ++i) {
19376 if (Mask[i / Ratio] == SM_SentinelUndef) {
19377 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19380 int M = Mask[i / Ratio] != SM_SentinelZero
19381 ? Ratio * Mask[i / Ratio] + i % Ratio
19383 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19385 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19386 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19387 DCI.AddToWorklist(Op.getNode());
19388 SDValue PSHUFBMaskOp =
19389 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19390 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19391 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19392 DCI.AddToWorklist(Op.getNode());
19393 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19398 // Failed to find any combines.
19402 /// \brief Fully generic combining of x86 shuffle instructions.
19404 /// This should be the last combine run over the x86 shuffle instructions. Once
19405 /// they have been fully optimized, this will recursively consider all chains
19406 /// of single-use shuffle instructions, build a generic model of the cumulative
19407 /// shuffle operation, and check for simpler instructions which implement this
19408 /// operation. We use this primarily for two purposes:
19410 /// 1) Collapse generic shuffles to specialized single instructions when
19411 /// equivalent. In most cases, this is just an encoding size win, but
19412 /// sometimes we will collapse multiple generic shuffles into a single
19413 /// special-purpose shuffle.
19414 /// 2) Look for sequences of shuffle instructions with 3 or more total
19415 /// instructions, and replace them with the slightly more expensive SSSE3
19416 /// PSHUFB instruction if available. We do this as the last combining step
19417 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19418 /// a suitable short sequence of other instructions. The PHUFB will either
19419 /// use a register or have to read from memory and so is slightly (but only
19420 /// slightly) more expensive than the other shuffle instructions.
19422 /// Because this is inherently a quadratic operation (for each shuffle in
19423 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19424 /// This should never be an issue in practice as the shuffle lowering doesn't
19425 /// produce sequences of more than 8 instructions.
19427 /// FIXME: We will currently miss some cases where the redundant shuffling
19428 /// would simplify under the threshold for PSHUFB formation because of
19429 /// combine-ordering. To fix this, we should do the redundant instruction
19430 /// combining in this recursive walk.
19431 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19432 ArrayRef<int> RootMask,
19433 int Depth, bool HasPSHUFB,
19435 TargetLowering::DAGCombinerInfo &DCI,
19436 const X86Subtarget *Subtarget) {
19437 // Bound the depth of our recursive combine because this is ultimately
19438 // quadratic in nature.
19442 // Directly rip through bitcasts to find the underlying operand.
19443 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19444 Op = Op.getOperand(0);
19446 MVT VT = Op.getSimpleValueType();
19447 if (!VT.isVector())
19448 return false; // Bail if we hit a non-vector.
19450 assert(Root.getSimpleValueType().isVector() &&
19451 "Shuffles operate on vector types!");
19452 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19453 "Can only combine shuffles of the same vector register size.");
19455 if (!isTargetShuffle(Op.getOpcode()))
19457 SmallVector<int, 16> OpMask;
19459 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19460 // We only can combine unary shuffles which we can decode the mask for.
19461 if (!HaveMask || !IsUnary)
19464 assert(VT.getVectorNumElements() == OpMask.size() &&
19465 "Different mask size from vector size!");
19466 assert(((RootMask.size() > OpMask.size() &&
19467 RootMask.size() % OpMask.size() == 0) ||
19468 (OpMask.size() > RootMask.size() &&
19469 OpMask.size() % RootMask.size() == 0) ||
19470 OpMask.size() == RootMask.size()) &&
19471 "The smaller number of elements must divide the larger.");
19472 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19473 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19474 assert(((RootRatio == 1 && OpRatio == 1) ||
19475 (RootRatio == 1) != (OpRatio == 1)) &&
19476 "Must not have a ratio for both incoming and op masks!");
19478 SmallVector<int, 16> Mask;
19479 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19481 // Merge this shuffle operation's mask into our accumulated mask. Note that
19482 // this shuffle's mask will be the first applied to the input, followed by the
19483 // root mask to get us all the way to the root value arrangement. The reason
19484 // for this order is that we are recursing up the operation chain.
19485 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19486 int RootIdx = i / RootRatio;
19487 if (RootMask[RootIdx] < 0) {
19488 // This is a zero or undef lane, we're done.
19489 Mask.push_back(RootMask[RootIdx]);
19493 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19494 int OpIdx = RootMaskedIdx / OpRatio;
19495 if (OpMask[OpIdx] < 0) {
19496 // The incoming lanes are zero or undef, it doesn't matter which ones we
19498 Mask.push_back(OpMask[OpIdx]);
19502 // Ok, we have non-zero lanes, map them through.
19503 Mask.push_back(OpMask[OpIdx] * OpRatio +
19504 RootMaskedIdx % OpRatio);
19507 // See if we can recurse into the operand to combine more things.
19508 switch (Op.getOpcode()) {
19509 case X86ISD::PSHUFB:
19511 case X86ISD::PSHUFD:
19512 case X86ISD::PSHUFHW:
19513 case X86ISD::PSHUFLW:
19514 if (Op.getOperand(0).hasOneUse() &&
19515 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19516 HasPSHUFB, DAG, DCI, Subtarget))
19520 case X86ISD::UNPCKL:
19521 case X86ISD::UNPCKH:
19522 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19523 // We can't check for single use, we have to check that this shuffle is the only user.
19524 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19525 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19526 HasPSHUFB, DAG, DCI, Subtarget))
19531 // Minor canonicalization of the accumulated shuffle mask to make it easier
19532 // to match below. All this does is detect masks with squential pairs of
19533 // elements, and shrink them to the half-width mask. It does this in a loop
19534 // so it will reduce the size of the mask to the minimal width mask which
19535 // performs an equivalent shuffle.
19536 SmallVector<int, 16> WidenedMask;
19537 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19538 Mask = std::move(WidenedMask);
19539 WidenedMask.clear();
19542 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19546 /// \brief Get the PSHUF-style mask from PSHUF node.
19548 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19549 /// PSHUF-style masks that can be reused with such instructions.
19550 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19551 MVT VT = N.getSimpleValueType();
19552 SmallVector<int, 4> Mask;
19554 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19558 // If we have more than 128-bits, only the low 128-bits of shuffle mask
19559 // matter. Check that the upper masks are repeats and remove them.
19560 if (VT.getSizeInBits() > 128) {
19561 int LaneElts = 128 / VT.getScalarSizeInBits();
19563 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19564 for (int j = 0; j < LaneElts; ++j)
19565 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19566 "Mask doesn't repeat in high 128-bit lanes!");
19568 Mask.resize(LaneElts);
19571 switch (N.getOpcode()) {
19572 case X86ISD::PSHUFD:
19574 case X86ISD::PSHUFLW:
19577 case X86ISD::PSHUFHW:
19578 Mask.erase(Mask.begin(), Mask.begin() + 4);
19579 for (int &M : Mask)
19583 llvm_unreachable("No valid shuffle instruction found!");
19587 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19589 /// We walk up the chain and look for a combinable shuffle, skipping over
19590 /// shuffles that we could hoist this shuffle's transformation past without
19591 /// altering anything.
19593 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19595 TargetLowering::DAGCombinerInfo &DCI) {
19596 assert(N.getOpcode() == X86ISD::PSHUFD &&
19597 "Called with something other than an x86 128-bit half shuffle!");
19600 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19601 // of the shuffles in the chain so that we can form a fresh chain to replace
19603 SmallVector<SDValue, 8> Chain;
19604 SDValue V = N.getOperand(0);
19605 for (; V.hasOneUse(); V = V.getOperand(0)) {
19606 switch (V.getOpcode()) {
19608 return SDValue(); // Nothing combined!
19611 // Skip bitcasts as we always know the type for the target specific
19615 case X86ISD::PSHUFD:
19616 // Found another dword shuffle.
19619 case X86ISD::PSHUFLW:
19620 // Check that the low words (being shuffled) are the identity in the
19621 // dword shuffle, and the high words are self-contained.
19622 if (Mask[0] != 0 || Mask[1] != 1 ||
19623 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19626 Chain.push_back(V);
19629 case X86ISD::PSHUFHW:
19630 // Check that the high words (being shuffled) are the identity in the
19631 // dword shuffle, and the low words are self-contained.
19632 if (Mask[2] != 2 || Mask[3] != 3 ||
19633 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19636 Chain.push_back(V);
19639 case X86ISD::UNPCKL:
19640 case X86ISD::UNPCKH:
19641 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19642 // shuffle into a preceding word shuffle.
19643 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19644 V.getSimpleValueType().getScalarType() != MVT::i16)
19647 // Search for a half-shuffle which we can combine with.
19648 unsigned CombineOp =
19649 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19650 if (V.getOperand(0) != V.getOperand(1) ||
19651 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19653 Chain.push_back(V);
19654 V = V.getOperand(0);
19656 switch (V.getOpcode()) {
19658 return SDValue(); // Nothing to combine.
19660 case X86ISD::PSHUFLW:
19661 case X86ISD::PSHUFHW:
19662 if (V.getOpcode() == CombineOp)
19665 Chain.push_back(V);
19669 V = V.getOperand(0);
19673 } while (V.hasOneUse());
19676 // Break out of the loop if we break out of the switch.
19680 if (!V.hasOneUse())
19681 // We fell out of the loop without finding a viable combining instruction.
19684 // Merge this node's mask and our incoming mask.
19685 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19686 for (int &M : Mask)
19688 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19689 getV4X86ShuffleImm8ForMask(Mask, DAG));
19691 // Rebuild the chain around this new shuffle.
19692 while (!Chain.empty()) {
19693 SDValue W = Chain.pop_back_val();
19695 if (V.getValueType() != W.getOperand(0).getValueType())
19696 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19698 switch (W.getOpcode()) {
19700 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19702 case X86ISD::UNPCKL:
19703 case X86ISD::UNPCKH:
19704 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19707 case X86ISD::PSHUFD:
19708 case X86ISD::PSHUFLW:
19709 case X86ISD::PSHUFHW:
19710 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19714 if (V.getValueType() != N.getValueType())
19715 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19717 // Return the new chain to replace N.
19721 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19723 /// We walk up the chain, skipping shuffles of the other half and looking
19724 /// through shuffles which switch halves trying to find a shuffle of the same
19725 /// pair of dwords.
19726 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19728 TargetLowering::DAGCombinerInfo &DCI) {
19730 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19731 "Called with something other than an x86 128-bit half shuffle!");
19733 unsigned CombineOpcode = N.getOpcode();
19735 // Walk up a single-use chain looking for a combinable shuffle.
19736 SDValue V = N.getOperand(0);
19737 for (; V.hasOneUse(); V = V.getOperand(0)) {
19738 switch (V.getOpcode()) {
19740 return false; // Nothing combined!
19743 // Skip bitcasts as we always know the type for the target specific
19747 case X86ISD::PSHUFLW:
19748 case X86ISD::PSHUFHW:
19749 if (V.getOpcode() == CombineOpcode)
19752 // Other-half shuffles are no-ops.
19755 // Break out of the loop if we break out of the switch.
19759 if (!V.hasOneUse())
19760 // We fell out of the loop without finding a viable combining instruction.
19763 // Combine away the bottom node as its shuffle will be accumulated into
19764 // a preceding shuffle.
19765 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19767 // Record the old value.
19770 // Merge this node's mask and our incoming mask (adjusted to account for all
19771 // the pshufd instructions encountered).
19772 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19773 for (int &M : Mask)
19775 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19776 getV4X86ShuffleImm8ForMask(Mask, DAG));
19778 // Check that the shuffles didn't cancel each other out. If not, we need to
19779 // combine to the new one.
19781 // Replace the combinable shuffle with the combined one, updating all users
19782 // so that we re-evaluate the chain here.
19783 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19788 /// \brief Try to combine x86 target specific shuffles.
19789 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19790 TargetLowering::DAGCombinerInfo &DCI,
19791 const X86Subtarget *Subtarget) {
19793 MVT VT = N.getSimpleValueType();
19794 SmallVector<int, 4> Mask;
19796 switch (N.getOpcode()) {
19797 case X86ISD::PSHUFD:
19798 case X86ISD::PSHUFLW:
19799 case X86ISD::PSHUFHW:
19800 Mask = getPSHUFShuffleMask(N);
19801 assert(Mask.size() == 4);
19807 // Nuke no-op shuffles that show up after combining.
19808 if (isNoopShuffleMask(Mask))
19809 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19811 // Look for simplifications involving one or two shuffle instructions.
19812 SDValue V = N.getOperand(0);
19813 switch (N.getOpcode()) {
19816 case X86ISD::PSHUFLW:
19817 case X86ISD::PSHUFHW:
19818 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19820 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19821 return SDValue(); // We combined away this shuffle, so we're done.
19823 // See if this reduces to a PSHUFD which is no more expensive and can
19824 // combine with more operations. Note that it has to at least flip the
19825 // dwords as otherwise it would have been removed as a no-op.
19826 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19827 int DMask[] = {0, 1, 2, 3};
19828 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19829 DMask[DOffset + 0] = DOffset + 1;
19830 DMask[DOffset + 1] = DOffset + 0;
19831 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19832 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19833 DCI.AddToWorklist(V.getNode());
19834 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19835 getV4X86ShuffleImm8ForMask(DMask, DAG));
19836 DCI.AddToWorklist(V.getNode());
19837 return DAG.getNode(ISD::BITCAST, DL, VT, V);
19840 // Look for shuffle patterns which can be implemented as a single unpack.
19841 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19842 // only works when we have a PSHUFD followed by two half-shuffles.
19843 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19844 (V.getOpcode() == X86ISD::PSHUFLW ||
19845 V.getOpcode() == X86ISD::PSHUFHW) &&
19846 V.getOpcode() != N.getOpcode() &&
19848 SDValue D = V.getOperand(0);
19849 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19850 D = D.getOperand(0);
19851 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19852 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19853 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19854 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19855 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19857 for (int i = 0; i < 4; ++i) {
19858 WordMask[i + NOffset] = Mask[i] + NOffset;
19859 WordMask[i + VOffset] = VMask[i] + VOffset;
19861 // Map the word mask through the DWord mask.
19863 for (int i = 0; i < 8; ++i)
19864 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19865 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19866 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
19867 // We can replace all three shuffles with an unpack.
19868 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
19869 DCI.AddToWorklist(V.getNode());
19870 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19879 case X86ISD::PSHUFD:
19880 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19889 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19891 /// We combine this directly on the abstract vector shuffle nodes so it is
19892 /// easier to generically match. We also insert dummy vector shuffle nodes for
19893 /// the operands which explicitly discard the lanes which are unused by this
19894 /// operation to try to flow through the rest of the combiner the fact that
19895 /// they're unused.
19896 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
19898 EVT VT = N->getValueType(0);
19900 // We only handle target-independent shuffles.
19901 // FIXME: It would be easy and harmless to use the target shuffle mask
19902 // extraction tool to support more.
19903 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
19906 auto *SVN = cast<ShuffleVectorSDNode>(N);
19907 ArrayRef<int> Mask = SVN->getMask();
19908 SDValue V1 = N->getOperand(0);
19909 SDValue V2 = N->getOperand(1);
19911 // We require the first shuffle operand to be the SUB node, and the second to
19912 // be the ADD node.
19913 // FIXME: We should support the commuted patterns.
19914 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
19917 // If there are other uses of these operations we can't fold them.
19918 if (!V1->hasOneUse() || !V2->hasOneUse())
19921 // Ensure that both operations have the same operands. Note that we can
19922 // commute the FADD operands.
19923 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
19924 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
19925 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
19928 // We're looking for blends between FADD and FSUB nodes. We insist on these
19929 // nodes being lined up in a specific expected pattern.
19930 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
19931 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
19932 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
19935 // Only specific types are legal at this point, assert so we notice if and
19936 // when these change.
19937 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
19938 VT == MVT::v4f64) &&
19939 "Unknown vector type encountered!");
19941 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
19944 /// PerformShuffleCombine - Performs several different shuffle combines.
19945 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19946 TargetLowering::DAGCombinerInfo &DCI,
19947 const X86Subtarget *Subtarget) {
19949 SDValue N0 = N->getOperand(0);
19950 SDValue N1 = N->getOperand(1);
19951 EVT VT = N->getValueType(0);
19953 // Don't create instructions with illegal types after legalize types has run.
19954 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19955 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19958 // If we have legalized the vector types, look for blends of FADD and FSUB
19959 // nodes that we can fuse into an ADDSUB node.
19960 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
19961 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
19964 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19965 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19966 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19967 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19969 // During Type Legalization, when promoting illegal vector types,
19970 // the backend might introduce new shuffle dag nodes and bitcasts.
19972 // This code performs the following transformation:
19973 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19974 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19976 // We do this only if both the bitcast and the BINOP dag nodes have
19977 // one use. Also, perform this transformation only if the new binary
19978 // operation is legal. This is to avoid introducing dag nodes that
19979 // potentially need to be further expanded (or custom lowered) into a
19980 // less optimal sequence of dag nodes.
19981 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19982 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19983 N0.getOpcode() == ISD::BITCAST) {
19984 SDValue BC0 = N0.getOperand(0);
19985 EVT SVT = BC0.getValueType();
19986 unsigned Opcode = BC0.getOpcode();
19987 unsigned NumElts = VT.getVectorNumElements();
19989 if (BC0.hasOneUse() && SVT.isVector() &&
19990 SVT.getVectorNumElements() * 2 == NumElts &&
19991 TLI.isOperationLegal(Opcode, VT)) {
19992 bool CanFold = false;
20004 unsigned SVTNumElts = SVT.getVectorNumElements();
20005 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20006 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20007 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20008 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20009 CanFold = SVOp->getMaskElt(i) < 0;
20012 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20013 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20014 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20015 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20020 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20021 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20022 // consecutive, non-overlapping, and in the right order.
20023 SmallVector<SDValue, 16> Elts;
20024 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20025 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20027 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20031 if (isTargetShuffle(N->getOpcode())) {
20033 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20034 if (Shuffle.getNode())
20037 // Try recursively combining arbitrary sequences of x86 shuffle
20038 // instructions into higher-order shuffles. We do this after combining
20039 // specific PSHUF instruction sequences into their minimal form so that we
20040 // can evaluate how many specialized shuffle instructions are involved in
20041 // a particular chain.
20042 SmallVector<int, 1> NonceMask; // Just a placeholder.
20043 NonceMask.push_back(0);
20044 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20045 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20047 return SDValue(); // This routine will use CombineTo to replace N.
20053 /// PerformTruncateCombine - Converts truncate operation to
20054 /// a sequence of vector shuffle operations.
20055 /// It is possible when we truncate 256-bit vector to 128-bit vector
20056 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20057 TargetLowering::DAGCombinerInfo &DCI,
20058 const X86Subtarget *Subtarget) {
20062 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20063 /// specific shuffle of a load can be folded into a single element load.
20064 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20065 /// shuffles have been custom lowered so we need to handle those here.
20066 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20067 TargetLowering::DAGCombinerInfo &DCI) {
20068 if (DCI.isBeforeLegalizeOps())
20071 SDValue InVec = N->getOperand(0);
20072 SDValue EltNo = N->getOperand(1);
20074 if (!isa<ConstantSDNode>(EltNo))
20077 EVT OriginalVT = InVec.getValueType();
20079 if (InVec.getOpcode() == ISD::BITCAST) {
20080 // Don't duplicate a load with other uses.
20081 if (!InVec.hasOneUse())
20083 EVT BCVT = InVec.getOperand(0).getValueType();
20084 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20086 InVec = InVec.getOperand(0);
20089 EVT CurrentVT = InVec.getValueType();
20091 if (!isTargetShuffle(InVec.getOpcode()))
20094 // Don't duplicate a load with other uses.
20095 if (!InVec.hasOneUse())
20098 SmallVector<int, 16> ShuffleMask;
20100 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20101 ShuffleMask, UnaryShuffle))
20104 // Select the input vector, guarding against out of range extract vector.
20105 unsigned NumElems = CurrentVT.getVectorNumElements();
20106 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20107 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20108 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20109 : InVec.getOperand(1);
20111 // If inputs to shuffle are the same for both ops, then allow 2 uses
20112 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20113 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20115 if (LdNode.getOpcode() == ISD::BITCAST) {
20116 // Don't duplicate a load with other uses.
20117 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20120 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20121 LdNode = LdNode.getOperand(0);
20124 if (!ISD::isNormalLoad(LdNode.getNode()))
20127 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20129 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20132 EVT EltVT = N->getValueType(0);
20133 // If there's a bitcast before the shuffle, check if the load type and
20134 // alignment is valid.
20135 unsigned Align = LN0->getAlignment();
20136 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20137 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20138 EltVT.getTypeForEVT(*DAG.getContext()));
20140 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20143 // All checks match so transform back to vector_shuffle so that DAG combiner
20144 // can finish the job
20147 // Create shuffle node taking into account the case that its a unary shuffle
20148 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20149 : InVec.getOperand(1);
20150 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20151 InVec.getOperand(0), Shuffle,
20153 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20154 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20158 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20159 /// special and don't usually play with other vector types, it's better to
20160 /// handle them early to be sure we emit efficient code by avoiding
20161 /// store-load conversions.
20162 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20163 if (N->getValueType(0) != MVT::x86mmx ||
20164 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20165 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20168 SDValue V = N->getOperand(0);
20169 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20170 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20171 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20172 N->getValueType(0), V.getOperand(0));
20177 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20178 /// generation and convert it from being a bunch of shuffles and extracts
20179 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20180 /// storing the value and loading scalars back, while for x64 we should
20181 /// use 64-bit extracts and shifts.
20182 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20183 TargetLowering::DAGCombinerInfo &DCI) {
20184 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20185 if (NewOp.getNode())
20188 SDValue InputVector = N->getOperand(0);
20190 // Detect mmx to i32 conversion through a v2i32 elt extract.
20191 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20192 N->getValueType(0) == MVT::i32 &&
20193 InputVector.getValueType() == MVT::v2i32) {
20195 // The bitcast source is a direct mmx result.
20196 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20197 if (MMXSrc.getValueType() == MVT::x86mmx)
20198 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20199 N->getValueType(0),
20200 InputVector.getNode()->getOperand(0));
20202 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20203 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20204 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20205 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20206 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20207 MMXSrcOp.getValueType() == MVT::v1i64 &&
20208 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20209 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20210 N->getValueType(0),
20211 MMXSrcOp.getOperand(0));
20214 // Only operate on vectors of 4 elements, where the alternative shuffling
20215 // gets to be more expensive.
20216 if (InputVector.getValueType() != MVT::v4i32)
20219 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20220 // single use which is a sign-extend or zero-extend, and all elements are
20222 SmallVector<SDNode *, 4> Uses;
20223 unsigned ExtractedElements = 0;
20224 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20225 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20226 if (UI.getUse().getResNo() != InputVector.getResNo())
20229 SDNode *Extract = *UI;
20230 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20233 if (Extract->getValueType(0) != MVT::i32)
20235 if (!Extract->hasOneUse())
20237 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20238 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20240 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20243 // Record which element was extracted.
20244 ExtractedElements |=
20245 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20247 Uses.push_back(Extract);
20250 // If not all the elements were used, this may not be worthwhile.
20251 if (ExtractedElements != 15)
20254 // Ok, we've now decided to do the transformation.
20255 // If 64-bit shifts are legal, use the extract-shift sequence,
20256 // otherwise bounce the vector off the cache.
20257 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20259 SDLoc dl(InputVector);
20261 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20262 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20263 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20264 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20265 DAG.getConstant(0, VecIdxTy));
20266 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20267 DAG.getConstant(1, VecIdxTy));
20269 SDValue ShAmt = DAG.getConstant(32,
20270 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20271 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20272 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20273 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20274 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20275 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20276 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20278 // Store the value to a temporary stack slot.
20279 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20280 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20281 MachinePointerInfo(), false, false, 0);
20283 EVT ElementType = InputVector.getValueType().getVectorElementType();
20284 unsigned EltSize = ElementType.getSizeInBits() / 8;
20286 // Replace each use (extract) with a load of the appropriate element.
20287 for (unsigned i = 0; i < 4; ++i) {
20288 uint64_t Offset = EltSize * i;
20289 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20291 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20292 StackPtr, OffsetVal);
20294 // Load the scalar.
20295 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20296 ScalarAddr, MachinePointerInfo(),
20297 false, false, false, 0);
20302 // Replace the extracts
20303 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20304 UE = Uses.end(); UI != UE; ++UI) {
20305 SDNode *Extract = *UI;
20307 SDValue Idx = Extract->getOperand(1);
20308 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20309 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20312 // The replacement was made in place; don't return anything.
20316 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20317 static std::pair<unsigned, bool>
20318 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20319 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20320 if (!VT.isVector())
20321 return std::make_pair(0, false);
20323 bool NeedSplit = false;
20324 switch (VT.getSimpleVT().SimpleTy) {
20325 default: return std::make_pair(0, false);
20328 if (!Subtarget->hasVLX())
20329 return std::make_pair(0, false);
20333 if (!Subtarget->hasBWI())
20334 return std::make_pair(0, false);
20338 if (!Subtarget->hasAVX512())
20339 return std::make_pair(0, false);
20344 if (!Subtarget->hasAVX2())
20346 if (!Subtarget->hasAVX())
20347 return std::make_pair(0, false);
20352 if (!Subtarget->hasSSE2())
20353 return std::make_pair(0, false);
20356 // SSE2 has only a small subset of the operations.
20357 bool hasUnsigned = Subtarget->hasSSE41() ||
20358 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20359 bool hasSigned = Subtarget->hasSSE41() ||
20360 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20362 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20365 // Check for x CC y ? x : y.
20366 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20367 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20372 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20375 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20378 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20381 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20383 // Check for x CC y ? y : x -- a min/max with reversed arms.
20384 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20385 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20390 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20393 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20396 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20399 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20403 return std::make_pair(Opc, NeedSplit);
20407 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20408 const X86Subtarget *Subtarget) {
20410 SDValue Cond = N->getOperand(0);
20411 SDValue LHS = N->getOperand(1);
20412 SDValue RHS = N->getOperand(2);
20414 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20415 SDValue CondSrc = Cond->getOperand(0);
20416 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20417 Cond = CondSrc->getOperand(0);
20420 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20423 // A vselect where all conditions and data are constants can be optimized into
20424 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20425 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20426 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20429 unsigned MaskValue = 0;
20430 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20433 MVT VT = N->getSimpleValueType(0);
20434 unsigned NumElems = VT.getVectorNumElements();
20435 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20436 for (unsigned i = 0; i < NumElems; ++i) {
20437 // Be sure we emit undef where we can.
20438 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20439 ShuffleMask[i] = -1;
20441 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20444 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20445 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20447 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20450 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20452 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20453 TargetLowering::DAGCombinerInfo &DCI,
20454 const X86Subtarget *Subtarget) {
20456 SDValue Cond = N->getOperand(0);
20457 // Get the LHS/RHS of the select.
20458 SDValue LHS = N->getOperand(1);
20459 SDValue RHS = N->getOperand(2);
20460 EVT VT = LHS.getValueType();
20461 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20463 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20464 // instructions match the semantics of the common C idiom x<y?x:y but not
20465 // x<=y?x:y, because of how they handle negative zero (which can be
20466 // ignored in unsafe-math mode).
20467 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20468 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20469 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20470 (Subtarget->hasSSE2() ||
20471 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20472 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20474 unsigned Opcode = 0;
20475 // Check for x CC y ? x : y.
20476 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20477 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20481 // Converting this to a min would handle NaNs incorrectly, and swapping
20482 // the operands would cause it to handle comparisons between positive
20483 // and negative zero incorrectly.
20484 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20485 if (!DAG.getTarget().Options.UnsafeFPMath &&
20486 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20488 std::swap(LHS, RHS);
20490 Opcode = X86ISD::FMIN;
20493 // Converting this to a min would handle comparisons between positive
20494 // and negative zero incorrectly.
20495 if (!DAG.getTarget().Options.UnsafeFPMath &&
20496 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20498 Opcode = X86ISD::FMIN;
20501 // Converting this to a min would handle both negative zeros and NaNs
20502 // incorrectly, but we can swap the operands to fix both.
20503 std::swap(LHS, RHS);
20507 Opcode = X86ISD::FMIN;
20511 // Converting this to a max would handle comparisons between positive
20512 // and negative zero incorrectly.
20513 if (!DAG.getTarget().Options.UnsafeFPMath &&
20514 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20516 Opcode = X86ISD::FMAX;
20519 // Converting this to a max would handle NaNs incorrectly, and swapping
20520 // the operands would cause it to handle comparisons between positive
20521 // and negative zero incorrectly.
20522 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20523 if (!DAG.getTarget().Options.UnsafeFPMath &&
20524 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20526 std::swap(LHS, RHS);
20528 Opcode = X86ISD::FMAX;
20531 // Converting this to a max would handle both negative zeros and NaNs
20532 // incorrectly, but we can swap the operands to fix both.
20533 std::swap(LHS, RHS);
20537 Opcode = X86ISD::FMAX;
20540 // Check for x CC y ? y : x -- a min/max with reversed arms.
20541 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20542 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20546 // Converting this to a min would handle comparisons between positive
20547 // and negative zero incorrectly, and swapping the operands would
20548 // cause it to handle NaNs incorrectly.
20549 if (!DAG.getTarget().Options.UnsafeFPMath &&
20550 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20551 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20553 std::swap(LHS, RHS);
20555 Opcode = X86ISD::FMIN;
20558 // Converting this to a min would handle NaNs incorrectly.
20559 if (!DAG.getTarget().Options.UnsafeFPMath &&
20560 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20562 Opcode = X86ISD::FMIN;
20565 // Converting this to a min would handle both negative zeros and NaNs
20566 // incorrectly, but we can swap the operands to fix both.
20567 std::swap(LHS, RHS);
20571 Opcode = X86ISD::FMIN;
20575 // Converting this to a max would handle NaNs incorrectly.
20576 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20578 Opcode = X86ISD::FMAX;
20581 // Converting this to a max would handle comparisons between positive
20582 // and negative zero incorrectly, and swapping the operands would
20583 // cause it to handle NaNs incorrectly.
20584 if (!DAG.getTarget().Options.UnsafeFPMath &&
20585 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20586 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20588 std::swap(LHS, RHS);
20590 Opcode = X86ISD::FMAX;
20593 // Converting this to a max would handle both negative zeros and NaNs
20594 // incorrectly, but we can swap the operands to fix both.
20595 std::swap(LHS, RHS);
20599 Opcode = X86ISD::FMAX;
20605 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20608 EVT CondVT = Cond.getValueType();
20609 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20610 CondVT.getVectorElementType() == MVT::i1) {
20611 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20612 // lowering on KNL. In this case we convert it to
20613 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20614 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20615 // Since SKX these selects have a proper lowering.
20616 EVT OpVT = LHS.getValueType();
20617 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20618 (OpVT.getVectorElementType() == MVT::i8 ||
20619 OpVT.getVectorElementType() == MVT::i16) &&
20620 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20621 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20622 DCI.AddToWorklist(Cond.getNode());
20623 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20626 // If this is a select between two integer constants, try to do some
20628 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20629 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20630 // Don't do this for crazy integer types.
20631 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20632 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20633 // so that TrueC (the true value) is larger than FalseC.
20634 bool NeedsCondInvert = false;
20636 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20637 // Efficiently invertible.
20638 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20639 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20640 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20641 NeedsCondInvert = true;
20642 std::swap(TrueC, FalseC);
20645 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20646 if (FalseC->getAPIntValue() == 0 &&
20647 TrueC->getAPIntValue().isPowerOf2()) {
20648 if (NeedsCondInvert) // Invert the condition if needed.
20649 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20650 DAG.getConstant(1, Cond.getValueType()));
20652 // Zero extend the condition if needed.
20653 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20655 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20656 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20657 DAG.getConstant(ShAmt, MVT::i8));
20660 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20661 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20662 if (NeedsCondInvert) // Invert the condition if needed.
20663 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20664 DAG.getConstant(1, Cond.getValueType()));
20666 // Zero extend the condition if needed.
20667 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20668 FalseC->getValueType(0), Cond);
20669 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20670 SDValue(FalseC, 0));
20673 // Optimize cases that will turn into an LEA instruction. This requires
20674 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20675 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20676 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20677 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20679 bool isFastMultiplier = false;
20681 switch ((unsigned char)Diff) {
20683 case 1: // result = add base, cond
20684 case 2: // result = lea base( , cond*2)
20685 case 3: // result = lea base(cond, cond*2)
20686 case 4: // result = lea base( , cond*4)
20687 case 5: // result = lea base(cond, cond*4)
20688 case 8: // result = lea base( , cond*8)
20689 case 9: // result = lea base(cond, cond*8)
20690 isFastMultiplier = true;
20695 if (isFastMultiplier) {
20696 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20697 if (NeedsCondInvert) // Invert the condition if needed.
20698 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20699 DAG.getConstant(1, Cond.getValueType()));
20701 // Zero extend the condition if needed.
20702 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20704 // Scale the condition by the difference.
20706 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20707 DAG.getConstant(Diff, Cond.getValueType()));
20709 // Add the base if non-zero.
20710 if (FalseC->getAPIntValue() != 0)
20711 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20712 SDValue(FalseC, 0));
20719 // Canonicalize max and min:
20720 // (x > y) ? x : y -> (x >= y) ? x : y
20721 // (x < y) ? x : y -> (x <= y) ? x : y
20722 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20723 // the need for an extra compare
20724 // against zero. e.g.
20725 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20727 // testl %edi, %edi
20729 // cmovgl %edi, %eax
20733 // cmovsl %eax, %edi
20734 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20735 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20736 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20737 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20742 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20743 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20744 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20745 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20750 // Early exit check
20751 if (!TLI.isTypeLegal(VT))
20754 // Match VSELECTs into subs with unsigned saturation.
20755 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20756 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20757 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20758 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20759 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20761 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20762 // left side invert the predicate to simplify logic below.
20764 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20766 CC = ISD::getSetCCInverse(CC, true);
20767 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20771 if (Other.getNode() && Other->getNumOperands() == 2 &&
20772 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20773 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20774 SDValue CondRHS = Cond->getOperand(1);
20776 // Look for a general sub with unsigned saturation first.
20777 // x >= y ? x-y : 0 --> subus x, y
20778 // x > y ? x-y : 0 --> subus x, y
20779 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20780 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20781 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20783 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20784 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20785 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20786 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20787 // If the RHS is a constant we have to reverse the const
20788 // canonicalization.
20789 // x > C-1 ? x+-C : 0 --> subus x, C
20790 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20791 CondRHSConst->getAPIntValue() ==
20792 (-OpRHSConst->getAPIntValue() - 1))
20793 return DAG.getNode(
20794 X86ISD::SUBUS, DL, VT, OpLHS,
20795 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20797 // Another special case: If C was a sign bit, the sub has been
20798 // canonicalized into a xor.
20799 // FIXME: Would it be better to use computeKnownBits to determine
20800 // whether it's safe to decanonicalize the xor?
20801 // x s< 0 ? x^C : 0 --> subus x, C
20802 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20803 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20804 OpRHSConst->getAPIntValue().isSignBit())
20805 // Note that we have to rebuild the RHS constant here to ensure we
20806 // don't rely on particular values of undef lanes.
20807 return DAG.getNode(
20808 X86ISD::SUBUS, DL, VT, OpLHS,
20809 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20814 // Try to match a min/max vector operation.
20815 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20816 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20817 unsigned Opc = ret.first;
20818 bool NeedSplit = ret.second;
20820 if (Opc && NeedSplit) {
20821 unsigned NumElems = VT.getVectorNumElements();
20822 // Extract the LHS vectors
20823 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20824 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20826 // Extract the RHS vectors
20827 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20828 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20830 // Create min/max for each subvector
20831 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20832 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20834 // Merge the result
20835 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20837 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20840 // Simplify vector selection if condition value type matches vselect
20842 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20843 assert(Cond.getValueType().isVector() &&
20844 "vector select expects a vector selector!");
20846 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20847 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20849 // Try invert the condition if true value is not all 1s and false value
20851 if (!TValIsAllOnes && !FValIsAllZeros &&
20852 // Check if the selector will be produced by CMPP*/PCMP*
20853 Cond.getOpcode() == ISD::SETCC &&
20854 // Check if SETCC has already been promoted
20855 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20856 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20857 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20859 if (TValIsAllZeros || FValIsAllOnes) {
20860 SDValue CC = Cond.getOperand(2);
20861 ISD::CondCode NewCC =
20862 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20863 Cond.getOperand(0).getValueType().isInteger());
20864 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20865 std::swap(LHS, RHS);
20866 TValIsAllOnes = FValIsAllOnes;
20867 FValIsAllZeros = TValIsAllZeros;
20871 if (TValIsAllOnes || FValIsAllZeros) {
20874 if (TValIsAllOnes && FValIsAllZeros)
20876 else if (TValIsAllOnes)
20877 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20878 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20879 else if (FValIsAllZeros)
20880 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20881 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20883 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20887 // We should generate an X86ISD::BLENDI from a vselect if its argument
20888 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20889 // constants. This specific pattern gets generated when we split a
20890 // selector for a 512 bit vector in a machine without AVX512 (but with
20891 // 256-bit vectors), during legalization:
20893 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20895 // Iff we find this pattern and the build_vectors are built from
20896 // constants, we translate the vselect into a shuffle_vector that we
20897 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20898 if ((N->getOpcode() == ISD::VSELECT ||
20899 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
20900 !DCI.isBeforeLegalize()) {
20901 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20902 if (Shuffle.getNode())
20906 // If this is a *dynamic* select (non-constant condition) and we can match
20907 // this node with one of the variable blend instructions, restructure the
20908 // condition so that the blends can use the high bit of each element and use
20909 // SimplifyDemandedBits to simplify the condition operand.
20910 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20911 !DCI.isBeforeLegalize() &&
20912 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
20913 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20915 // Don't optimize vector selects that map to mask-registers.
20919 // We can only handle the cases where VSELECT is directly legal on the
20920 // subtarget. We custom lower VSELECT nodes with constant conditions and
20921 // this makes it hard to see whether a dynamic VSELECT will correctly
20922 // lower, so we both check the operation's status and explicitly handle the
20923 // cases where a *dynamic* blend will fail even though a constant-condition
20924 // blend could be custom lowered.
20925 // FIXME: We should find a better way to handle this class of problems.
20926 // Potentially, we should combine constant-condition vselect nodes
20927 // pre-legalization into shuffles and not mark as many types as custom
20929 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
20931 // FIXME: We don't support i16-element blends currently. We could and
20932 // should support them by making *all* the bits in the condition be set
20933 // rather than just the high bit and using an i8-element blend.
20934 if (VT.getScalarType() == MVT::i16)
20936 // Dynamic blending was only available from SSE4.1 onward.
20937 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
20939 // Byte blends are only available in AVX2
20940 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
20941 !Subtarget->hasAVX2())
20944 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20945 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20947 APInt KnownZero, KnownOne;
20948 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20949 DCI.isBeforeLegalizeOps());
20950 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20951 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
20953 // If we changed the computation somewhere in the DAG, this change
20954 // will affect all users of Cond.
20955 // Make sure it is fine and update all the nodes so that we do not
20956 // use the generic VSELECT anymore. Otherwise, we may perform
20957 // wrong optimizations as we messed up with the actual expectation
20958 // for the vector boolean values.
20959 if (Cond != TLO.Old) {
20960 // Check all uses of that condition operand to check whether it will be
20961 // consumed by non-BLEND instructions, which may depend on all bits are
20963 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20965 if (I->getOpcode() != ISD::VSELECT)
20966 // TODO: Add other opcodes eventually lowered into BLEND.
20969 // Update all the users of the condition, before committing the change,
20970 // so that the VSELECT optimizations that expect the correct vector
20971 // boolean value will not be triggered.
20972 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20974 DAG.ReplaceAllUsesOfValueWith(
20976 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
20977 Cond, I->getOperand(1), I->getOperand(2)));
20978 DCI.CommitTargetLoweringOpt(TLO);
20981 // At this point, only Cond is changed. Change the condition
20982 // just for N to keep the opportunity to optimize all other
20983 // users their own way.
20984 DAG.ReplaceAllUsesOfValueWith(
20986 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
20987 TLO.New, N->getOperand(1), N->getOperand(2)));
20995 // Check whether a boolean test is testing a boolean value generated by
20996 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20999 // Simplify the following patterns:
21000 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21001 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21002 // to (Op EFLAGS Cond)
21004 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21005 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21006 // to (Op EFLAGS !Cond)
21008 // where Op could be BRCOND or CMOV.
21010 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21011 // Quit if not CMP and SUB with its value result used.
21012 if (Cmp.getOpcode() != X86ISD::CMP &&
21013 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21016 // Quit if not used as a boolean value.
21017 if (CC != X86::COND_E && CC != X86::COND_NE)
21020 // Check CMP operands. One of them should be 0 or 1 and the other should be
21021 // an SetCC or extended from it.
21022 SDValue Op1 = Cmp.getOperand(0);
21023 SDValue Op2 = Cmp.getOperand(1);
21026 const ConstantSDNode* C = nullptr;
21027 bool needOppositeCond = (CC == X86::COND_E);
21028 bool checkAgainstTrue = false; // Is it a comparison against 1?
21030 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21032 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21034 else // Quit if all operands are not constants.
21037 if (C->getZExtValue() == 1) {
21038 needOppositeCond = !needOppositeCond;
21039 checkAgainstTrue = true;
21040 } else if (C->getZExtValue() != 0)
21041 // Quit if the constant is neither 0 or 1.
21044 bool truncatedToBoolWithAnd = false;
21045 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21046 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21047 SetCC.getOpcode() == ISD::TRUNCATE ||
21048 SetCC.getOpcode() == ISD::AND) {
21049 if (SetCC.getOpcode() == ISD::AND) {
21051 ConstantSDNode *CS;
21052 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21053 CS->getZExtValue() == 1)
21055 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21056 CS->getZExtValue() == 1)
21060 SetCC = SetCC.getOperand(OpIdx);
21061 truncatedToBoolWithAnd = true;
21063 SetCC = SetCC.getOperand(0);
21066 switch (SetCC.getOpcode()) {
21067 case X86ISD::SETCC_CARRY:
21068 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21069 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21070 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21071 // truncated to i1 using 'and'.
21072 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21074 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21075 "Invalid use of SETCC_CARRY!");
21077 case X86ISD::SETCC:
21078 // Set the condition code or opposite one if necessary.
21079 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21080 if (needOppositeCond)
21081 CC = X86::GetOppositeBranchCondition(CC);
21082 return SetCC.getOperand(1);
21083 case X86ISD::CMOV: {
21084 // Check whether false/true value has canonical one, i.e. 0 or 1.
21085 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21086 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21087 // Quit if true value is not a constant.
21090 // Quit if false value is not a constant.
21092 SDValue Op = SetCC.getOperand(0);
21093 // Skip 'zext' or 'trunc' node.
21094 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21095 Op.getOpcode() == ISD::TRUNCATE)
21096 Op = Op.getOperand(0);
21097 // A special case for rdrand/rdseed, where 0 is set if false cond is
21099 if ((Op.getOpcode() != X86ISD::RDRAND &&
21100 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21103 // Quit if false value is not the constant 0 or 1.
21104 bool FValIsFalse = true;
21105 if (FVal && FVal->getZExtValue() != 0) {
21106 if (FVal->getZExtValue() != 1)
21108 // If FVal is 1, opposite cond is needed.
21109 needOppositeCond = !needOppositeCond;
21110 FValIsFalse = false;
21112 // Quit if TVal is not the constant opposite of FVal.
21113 if (FValIsFalse && TVal->getZExtValue() != 1)
21115 if (!FValIsFalse && TVal->getZExtValue() != 0)
21117 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21118 if (needOppositeCond)
21119 CC = X86::GetOppositeBranchCondition(CC);
21120 return SetCC.getOperand(3);
21127 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21129 /// (X86or (X86setcc) (X86setcc))
21130 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21131 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21132 X86::CondCode &CC1, SDValue &Flags,
21134 if (Cond->getOpcode() == X86ISD::CMP) {
21135 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21136 if (!CondOp1C || !CondOp1C->isNullValue())
21139 Cond = Cond->getOperand(0);
21144 SDValue SetCC0, SetCC1;
21145 switch (Cond->getOpcode()) {
21146 default: return false;
21153 SetCC0 = Cond->getOperand(0);
21154 SetCC1 = Cond->getOperand(1);
21158 // Make sure we have SETCC nodes, using the same flags value.
21159 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21160 SetCC1.getOpcode() != X86ISD::SETCC ||
21161 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21164 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21165 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21166 Flags = SetCC0->getOperand(1);
21170 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21171 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21172 TargetLowering::DAGCombinerInfo &DCI,
21173 const X86Subtarget *Subtarget) {
21176 // If the flag operand isn't dead, don't touch this CMOV.
21177 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21180 SDValue FalseOp = N->getOperand(0);
21181 SDValue TrueOp = N->getOperand(1);
21182 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21183 SDValue Cond = N->getOperand(3);
21185 if (CC == X86::COND_E || CC == X86::COND_NE) {
21186 switch (Cond.getOpcode()) {
21190 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21191 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21192 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21198 Flags = checkBoolTestSetCCCombine(Cond, CC);
21199 if (Flags.getNode() &&
21200 // Extra check as FCMOV only supports a subset of X86 cond.
21201 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21202 SDValue Ops[] = { FalseOp, TrueOp,
21203 DAG.getConstant(CC, MVT::i8), Flags };
21204 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21207 // If this is a select between two integer constants, try to do some
21208 // optimizations. Note that the operands are ordered the opposite of SELECT
21210 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21211 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21212 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21213 // larger than FalseC (the false value).
21214 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21215 CC = X86::GetOppositeBranchCondition(CC);
21216 std::swap(TrueC, FalseC);
21217 std::swap(TrueOp, FalseOp);
21220 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21221 // This is efficient for any integer data type (including i8/i16) and
21223 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21224 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21225 DAG.getConstant(CC, MVT::i8), Cond);
21227 // Zero extend the condition if needed.
21228 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21230 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21231 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21232 DAG.getConstant(ShAmt, MVT::i8));
21233 if (N->getNumValues() == 2) // Dead flag value?
21234 return DCI.CombineTo(N, Cond, SDValue());
21238 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21239 // for any integer data type, including i8/i16.
21240 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21241 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21242 DAG.getConstant(CC, MVT::i8), Cond);
21244 // Zero extend the condition if needed.
21245 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21246 FalseC->getValueType(0), Cond);
21247 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21248 SDValue(FalseC, 0));
21250 if (N->getNumValues() == 2) // Dead flag value?
21251 return DCI.CombineTo(N, Cond, SDValue());
21255 // Optimize cases that will turn into an LEA instruction. This requires
21256 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21257 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21258 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21259 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21261 bool isFastMultiplier = false;
21263 switch ((unsigned char)Diff) {
21265 case 1: // result = add base, cond
21266 case 2: // result = lea base( , cond*2)
21267 case 3: // result = lea base(cond, cond*2)
21268 case 4: // result = lea base( , cond*4)
21269 case 5: // result = lea base(cond, cond*4)
21270 case 8: // result = lea base( , cond*8)
21271 case 9: // result = lea base(cond, cond*8)
21272 isFastMultiplier = true;
21277 if (isFastMultiplier) {
21278 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21279 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21280 DAG.getConstant(CC, MVT::i8), Cond);
21281 // Zero extend the condition if needed.
21282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21284 // Scale the condition by the difference.
21286 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21287 DAG.getConstant(Diff, Cond.getValueType()));
21289 // Add the base if non-zero.
21290 if (FalseC->getAPIntValue() != 0)
21291 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21292 SDValue(FalseC, 0));
21293 if (N->getNumValues() == 2) // Dead flag value?
21294 return DCI.CombineTo(N, Cond, SDValue());
21301 // Handle these cases:
21302 // (select (x != c), e, c) -> select (x != c), e, x),
21303 // (select (x == c), c, e) -> select (x == c), x, e)
21304 // where the c is an integer constant, and the "select" is the combination
21305 // of CMOV and CMP.
21307 // The rationale for this change is that the conditional-move from a constant
21308 // needs two instructions, however, conditional-move from a register needs
21309 // only one instruction.
21311 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21312 // some instruction-combining opportunities. This opt needs to be
21313 // postponed as late as possible.
21315 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21316 // the DCI.xxxx conditions are provided to postpone the optimization as
21317 // late as possible.
21319 ConstantSDNode *CmpAgainst = nullptr;
21320 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21321 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21322 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21324 if (CC == X86::COND_NE &&
21325 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21326 CC = X86::GetOppositeBranchCondition(CC);
21327 std::swap(TrueOp, FalseOp);
21330 if (CC == X86::COND_E &&
21331 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21332 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21333 DAG.getConstant(CC, MVT::i8), Cond };
21334 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21339 // Fold and/or of setcc's to double CMOV:
21340 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21341 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21343 // This combine lets us generate:
21344 // cmovcc1 (jcc1 if we don't have CMOV)
21350 // cmovne (jne if we don't have CMOV)
21351 // When we can't use the CMOV instruction, it might increase branch
21353 // When we can use CMOV, or when there is no mispredict, this improves
21354 // throughput and reduces register pressure.
21356 if (CC == X86::COND_NE) {
21358 X86::CondCode CC0, CC1;
21360 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21362 std::swap(FalseOp, TrueOp);
21363 CC0 = X86::GetOppositeBranchCondition(CC0);
21364 CC1 = X86::GetOppositeBranchCondition(CC1);
21367 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21369 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21370 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21371 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21372 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21380 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21381 const X86Subtarget *Subtarget) {
21382 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21384 default: return SDValue();
21385 // SSE/AVX/AVX2 blend intrinsics.
21386 case Intrinsic::x86_avx2_pblendvb:
21387 // Don't try to simplify this intrinsic if we don't have AVX2.
21388 if (!Subtarget->hasAVX2())
21391 case Intrinsic::x86_avx_blendv_pd_256:
21392 case Intrinsic::x86_avx_blendv_ps_256:
21393 // Don't try to simplify this intrinsic if we don't have AVX.
21394 if (!Subtarget->hasAVX())
21397 case Intrinsic::x86_sse41_blendvps:
21398 case Intrinsic::x86_sse41_blendvpd:
21399 case Intrinsic::x86_sse41_pblendvb: {
21400 SDValue Op0 = N->getOperand(1);
21401 SDValue Op1 = N->getOperand(2);
21402 SDValue Mask = N->getOperand(3);
21404 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21405 if (!Subtarget->hasSSE41())
21408 // fold (blend A, A, Mask) -> A
21411 // fold (blend A, B, allZeros) -> A
21412 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21414 // fold (blend A, B, allOnes) -> B
21415 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21418 // Simplify the case where the mask is a constant i32 value.
21419 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21420 if (C->isNullValue())
21422 if (C->isAllOnesValue())
21429 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21430 case Intrinsic::x86_sse2_psrai_w:
21431 case Intrinsic::x86_sse2_psrai_d:
21432 case Intrinsic::x86_avx2_psrai_w:
21433 case Intrinsic::x86_avx2_psrai_d:
21434 case Intrinsic::x86_sse2_psra_w:
21435 case Intrinsic::x86_sse2_psra_d:
21436 case Intrinsic::x86_avx2_psra_w:
21437 case Intrinsic::x86_avx2_psra_d: {
21438 SDValue Op0 = N->getOperand(1);
21439 SDValue Op1 = N->getOperand(2);
21440 EVT VT = Op0.getValueType();
21441 assert(VT.isVector() && "Expected a vector type!");
21443 if (isa<BuildVectorSDNode>(Op1))
21444 Op1 = Op1.getOperand(0);
21446 if (!isa<ConstantSDNode>(Op1))
21449 EVT SVT = VT.getVectorElementType();
21450 unsigned SVTBits = SVT.getSizeInBits();
21452 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21453 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21454 uint64_t ShAmt = C.getZExtValue();
21456 // Don't try to convert this shift into a ISD::SRA if the shift
21457 // count is bigger than or equal to the element size.
21458 if (ShAmt >= SVTBits)
21461 // Trivial case: if the shift count is zero, then fold this
21462 // into the first operand.
21466 // Replace this packed shift intrinsic with a target independent
21468 SDValue Splat = DAG.getConstant(C, VT);
21469 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21474 /// PerformMulCombine - Optimize a single multiply with constant into two
21475 /// in order to implement it with two cheaper instructions, e.g.
21476 /// LEA + SHL, LEA + LEA.
21477 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21478 TargetLowering::DAGCombinerInfo &DCI) {
21479 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21482 EVT VT = N->getValueType(0);
21483 if (VT != MVT::i64 && VT != MVT::i32)
21486 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21489 uint64_t MulAmt = C->getZExtValue();
21490 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21493 uint64_t MulAmt1 = 0;
21494 uint64_t MulAmt2 = 0;
21495 if ((MulAmt % 9) == 0) {
21497 MulAmt2 = MulAmt / 9;
21498 } else if ((MulAmt % 5) == 0) {
21500 MulAmt2 = MulAmt / 5;
21501 } else if ((MulAmt % 3) == 0) {
21503 MulAmt2 = MulAmt / 3;
21506 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21509 if (isPowerOf2_64(MulAmt2) &&
21510 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21511 // If second multiplifer is pow2, issue it first. We want the multiply by
21512 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21514 std::swap(MulAmt1, MulAmt2);
21517 if (isPowerOf2_64(MulAmt1))
21518 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21519 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21521 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21522 DAG.getConstant(MulAmt1, VT));
21524 if (isPowerOf2_64(MulAmt2))
21525 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21526 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21528 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21529 DAG.getConstant(MulAmt2, VT));
21531 // Do not add new nodes to DAG combiner worklist.
21532 DCI.CombineTo(N, NewMul, false);
21537 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21538 SDValue N0 = N->getOperand(0);
21539 SDValue N1 = N->getOperand(1);
21540 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21541 EVT VT = N0.getValueType();
21543 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21544 // since the result of setcc_c is all zero's or all ones.
21545 if (VT.isInteger() && !VT.isVector() &&
21546 N1C && N0.getOpcode() == ISD::AND &&
21547 N0.getOperand(1).getOpcode() == ISD::Constant) {
21548 SDValue N00 = N0.getOperand(0);
21549 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21550 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21551 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21552 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21553 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21554 APInt ShAmt = N1C->getAPIntValue();
21555 Mask = Mask.shl(ShAmt);
21557 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21558 N00, DAG.getConstant(Mask, VT));
21562 // Hardware support for vector shifts is sparse which makes us scalarize the
21563 // vector operations in many cases. Also, on sandybridge ADD is faster than
21565 // (shl V, 1) -> add V,V
21566 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21567 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21568 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21569 // We shift all of the values by one. In many cases we do not have
21570 // hardware support for this operation. This is better expressed as an ADD
21572 if (N1SplatC->getZExtValue() == 1)
21573 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21579 /// \brief Returns a vector of 0s if the node in input is a vector logical
21580 /// shift by a constant amount which is known to be bigger than or equal
21581 /// to the vector element size in bits.
21582 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21583 const X86Subtarget *Subtarget) {
21584 EVT VT = N->getValueType(0);
21586 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21587 (!Subtarget->hasInt256() ||
21588 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21591 SDValue Amt = N->getOperand(1);
21593 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21594 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21595 APInt ShiftAmt = AmtSplat->getAPIntValue();
21596 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21598 // SSE2/AVX2 logical shifts always return a vector of 0s
21599 // if the shift amount is bigger than or equal to
21600 // the element size. The constant shift amount will be
21601 // encoded as a 8-bit immediate.
21602 if (ShiftAmt.trunc(8).uge(MaxAmount))
21603 return getZeroVector(VT, Subtarget, DAG, DL);
21609 /// PerformShiftCombine - Combine shifts.
21610 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21611 TargetLowering::DAGCombinerInfo &DCI,
21612 const X86Subtarget *Subtarget) {
21613 if (N->getOpcode() == ISD::SHL) {
21614 SDValue V = PerformSHLCombine(N, DAG);
21615 if (V.getNode()) return V;
21618 if (N->getOpcode() != ISD::SRA) {
21619 // Try to fold this logical shift into a zero vector.
21620 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21621 if (V.getNode()) return V;
21627 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21628 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21629 // and friends. Likewise for OR -> CMPNEQSS.
21630 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21631 TargetLowering::DAGCombinerInfo &DCI,
21632 const X86Subtarget *Subtarget) {
21635 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21636 // we're requiring SSE2 for both.
21637 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21638 SDValue N0 = N->getOperand(0);
21639 SDValue N1 = N->getOperand(1);
21640 SDValue CMP0 = N0->getOperand(1);
21641 SDValue CMP1 = N1->getOperand(1);
21644 // The SETCCs should both refer to the same CMP.
21645 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21648 SDValue CMP00 = CMP0->getOperand(0);
21649 SDValue CMP01 = CMP0->getOperand(1);
21650 EVT VT = CMP00.getValueType();
21652 if (VT == MVT::f32 || VT == MVT::f64) {
21653 bool ExpectingFlags = false;
21654 // Check for any users that want flags:
21655 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21656 !ExpectingFlags && UI != UE; ++UI)
21657 switch (UI->getOpcode()) {
21662 ExpectingFlags = true;
21664 case ISD::CopyToReg:
21665 case ISD::SIGN_EXTEND:
21666 case ISD::ZERO_EXTEND:
21667 case ISD::ANY_EXTEND:
21671 if (!ExpectingFlags) {
21672 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21673 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21675 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21676 X86::CondCode tmp = cc0;
21681 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21682 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21683 // FIXME: need symbolic constants for these magic numbers.
21684 // See X86ATTInstPrinter.cpp:printSSECC().
21685 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21686 if (Subtarget->hasAVX512()) {
21687 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21688 CMP01, DAG.getConstant(x86cc, MVT::i8));
21689 if (N->getValueType(0) != MVT::i1)
21690 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21694 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21695 CMP00.getValueType(), CMP00, CMP01,
21696 DAG.getConstant(x86cc, MVT::i8));
21698 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21699 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21701 if (is64BitFP && !Subtarget->is64Bit()) {
21702 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21703 // 64-bit integer, since that's not a legal type. Since
21704 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21705 // bits, but can do this little dance to extract the lowest 32 bits
21706 // and work with those going forward.
21707 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21709 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21711 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21712 Vector32, DAG.getIntPtrConstant(0));
21716 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21717 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21718 DAG.getConstant(1, IntVT));
21719 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21720 return OneBitOfTruth;
21728 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21729 /// so it can be folded inside ANDNP.
21730 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21731 EVT VT = N->getValueType(0);
21733 // Match direct AllOnes for 128 and 256-bit vectors
21734 if (ISD::isBuildVectorAllOnes(N))
21737 // Look through a bit convert.
21738 if (N->getOpcode() == ISD::BITCAST)
21739 N = N->getOperand(0).getNode();
21741 // Sometimes the operand may come from a insert_subvector building a 256-bit
21743 if (VT.is256BitVector() &&
21744 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21745 SDValue V1 = N->getOperand(0);
21746 SDValue V2 = N->getOperand(1);
21748 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21749 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21750 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21751 ISD::isBuildVectorAllOnes(V2.getNode()))
21758 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21759 // register. In most cases we actually compare or select YMM-sized registers
21760 // and mixing the two types creates horrible code. This method optimizes
21761 // some of the transition sequences.
21762 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21763 TargetLowering::DAGCombinerInfo &DCI,
21764 const X86Subtarget *Subtarget) {
21765 EVT VT = N->getValueType(0);
21766 if (!VT.is256BitVector())
21769 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21770 N->getOpcode() == ISD::ZERO_EXTEND ||
21771 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21773 SDValue Narrow = N->getOperand(0);
21774 EVT NarrowVT = Narrow->getValueType(0);
21775 if (!NarrowVT.is128BitVector())
21778 if (Narrow->getOpcode() != ISD::XOR &&
21779 Narrow->getOpcode() != ISD::AND &&
21780 Narrow->getOpcode() != ISD::OR)
21783 SDValue N0 = Narrow->getOperand(0);
21784 SDValue N1 = Narrow->getOperand(1);
21787 // The Left side has to be a trunc.
21788 if (N0.getOpcode() != ISD::TRUNCATE)
21791 // The type of the truncated inputs.
21792 EVT WideVT = N0->getOperand(0)->getValueType(0);
21796 // The right side has to be a 'trunc' or a constant vector.
21797 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21798 ConstantSDNode *RHSConstSplat = nullptr;
21799 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21800 RHSConstSplat = RHSBV->getConstantSplatNode();
21801 if (!RHSTrunc && !RHSConstSplat)
21804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21806 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21809 // Set N0 and N1 to hold the inputs to the new wide operation.
21810 N0 = N0->getOperand(0);
21811 if (RHSConstSplat) {
21812 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21813 SDValue(RHSConstSplat, 0));
21814 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21815 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21816 } else if (RHSTrunc) {
21817 N1 = N1->getOperand(0);
21820 // Generate the wide operation.
21821 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21822 unsigned Opcode = N->getOpcode();
21824 case ISD::ANY_EXTEND:
21826 case ISD::ZERO_EXTEND: {
21827 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21828 APInt Mask = APInt::getAllOnesValue(InBits);
21829 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21830 return DAG.getNode(ISD::AND, DL, VT,
21831 Op, DAG.getConstant(Mask, VT));
21833 case ISD::SIGN_EXTEND:
21834 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21835 Op, DAG.getValueType(NarrowVT));
21837 llvm_unreachable("Unexpected opcode");
21841 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21842 TargetLowering::DAGCombinerInfo &DCI,
21843 const X86Subtarget *Subtarget) {
21844 SDValue N0 = N->getOperand(0);
21845 SDValue N1 = N->getOperand(1);
21848 // A vector zext_in_reg may be represented as a shuffle,
21849 // feeding into a bitcast (this represents anyext) feeding into
21850 // an and with a mask.
21851 // We'd like to try to combine that into a shuffle with zero
21852 // plus a bitcast, removing the and.
21853 if (N0.getOpcode() != ISD::BITCAST ||
21854 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21857 // The other side of the AND should be a splat of 2^C, where C
21858 // is the number of bits in the source type.
21859 if (N1.getOpcode() == ISD::BITCAST)
21860 N1 = N1.getOperand(0);
21861 if (N1.getOpcode() != ISD::BUILD_VECTOR)
21863 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21865 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21866 EVT SrcType = Shuffle->getValueType(0);
21868 // We expect a single-source shuffle
21869 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21872 unsigned SrcSize = SrcType.getScalarSizeInBits();
21874 APInt SplatValue, SplatUndef;
21875 unsigned SplatBitSize;
21877 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21878 SplatBitSize, HasAnyUndefs))
21881 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21882 // Make sure the splat matches the mask we expect
21883 if (SplatBitSize > ResSize ||
21884 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21887 // Make sure the input and output size make sense
21888 if (SrcSize >= ResSize || ResSize % SrcSize)
21891 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
21892 // The number of u's between each two values depends on the ratio between
21893 // the source and dest type.
21894 unsigned ZextRatio = ResSize / SrcSize;
21895 bool IsZext = true;
21896 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
21897 if (i % ZextRatio) {
21898 if (Shuffle->getMaskElt(i) > 0) {
21904 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
21905 // Expected element number
21915 // Ok, perform the transformation - replace the shuffle with
21916 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
21917 // (instead of undef) where the k elements come from the zero vector.
21918 SmallVector<int, 8> Mask;
21919 unsigned NumElems = SrcType.getVectorNumElements();
21920 for (unsigned i = 0; i < NumElems; ++i)
21922 Mask.push_back(NumElems);
21924 Mask.push_back(i / ZextRatio);
21926 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
21927 Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
21928 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
21931 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21932 TargetLowering::DAGCombinerInfo &DCI,
21933 const X86Subtarget *Subtarget) {
21934 if (DCI.isBeforeLegalizeOps())
21937 SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget);
21938 if (Zext.getNode())
21941 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21945 EVT VT = N->getValueType(0);
21946 SDValue N0 = N->getOperand(0);
21947 SDValue N1 = N->getOperand(1);
21950 // Create BEXTR instructions
21951 // BEXTR is ((X >> imm) & (2**size-1))
21952 if (VT == MVT::i32 || VT == MVT::i64) {
21953 // Check for BEXTR.
21954 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21955 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21956 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21957 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21958 if (MaskNode && ShiftNode) {
21959 uint64_t Mask = MaskNode->getZExtValue();
21960 uint64_t Shift = ShiftNode->getZExtValue();
21961 if (isMask_64(Mask)) {
21962 uint64_t MaskSize = countPopulation(Mask);
21963 if (Shift + MaskSize <= VT.getSizeInBits())
21964 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21965 DAG.getConstant(Shift | (MaskSize << 8), VT));
21973 // Want to form ANDNP nodes:
21974 // 1) In the hopes of then easily combining them with OR and AND nodes
21975 // to form PBLEND/PSIGN.
21976 // 2) To match ANDN packed intrinsics
21977 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21980 // Check LHS for vnot
21981 if (N0.getOpcode() == ISD::XOR &&
21982 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21983 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21984 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21986 // Check RHS for vnot
21987 if (N1.getOpcode() == ISD::XOR &&
21988 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21989 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21990 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21995 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21996 TargetLowering::DAGCombinerInfo &DCI,
21997 const X86Subtarget *Subtarget) {
21998 if (DCI.isBeforeLegalizeOps())
22001 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22005 SDValue N0 = N->getOperand(0);
22006 SDValue N1 = N->getOperand(1);
22007 EVT VT = N->getValueType(0);
22009 // look for psign/blend
22010 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22011 if (!Subtarget->hasSSSE3() ||
22012 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22015 // Canonicalize pandn to RHS
22016 if (N0.getOpcode() == X86ISD::ANDNP)
22018 // or (and (m, y), (pandn m, x))
22019 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22020 SDValue Mask = N1.getOperand(0);
22021 SDValue X = N1.getOperand(1);
22023 if (N0.getOperand(0) == Mask)
22024 Y = N0.getOperand(1);
22025 if (N0.getOperand(1) == Mask)
22026 Y = N0.getOperand(0);
22028 // Check to see if the mask appeared in both the AND and ANDNP and
22032 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22033 // Look through mask bitcast.
22034 if (Mask.getOpcode() == ISD::BITCAST)
22035 Mask = Mask.getOperand(0);
22036 if (X.getOpcode() == ISD::BITCAST)
22037 X = X.getOperand(0);
22038 if (Y.getOpcode() == ISD::BITCAST)
22039 Y = Y.getOperand(0);
22041 EVT MaskVT = Mask.getValueType();
22043 // Validate that the Mask operand is a vector sra node.
22044 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22045 // there is no psrai.b
22046 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22047 unsigned SraAmt = ~0;
22048 if (Mask.getOpcode() == ISD::SRA) {
22049 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22050 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22051 SraAmt = AmtConst->getZExtValue();
22052 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22053 SDValue SraC = Mask.getOperand(1);
22054 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22056 if ((SraAmt + 1) != EltBits)
22061 // Now we know we at least have a plendvb with the mask val. See if
22062 // we can form a psignb/w/d.
22063 // psign = x.type == y.type == mask.type && y = sub(0, x);
22064 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22065 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22066 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22067 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22068 "Unsupported VT for PSIGN");
22069 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22070 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22072 // PBLENDVB only available on SSE 4.1
22073 if (!Subtarget->hasSSE41())
22076 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22078 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22079 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22080 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22081 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22082 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22086 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22089 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22090 MachineFunction &MF = DAG.getMachineFunction();
22092 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22094 // SHLD/SHRD instructions have lower register pressure, but on some
22095 // platforms they have higher latency than the equivalent
22096 // series of shifts/or that would otherwise be generated.
22097 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22098 // have higher latencies and we are not optimizing for size.
22099 if (!OptForSize && Subtarget->isSHLDSlow())
22102 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22104 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22106 if (!N0.hasOneUse() || !N1.hasOneUse())
22109 SDValue ShAmt0 = N0.getOperand(1);
22110 if (ShAmt0.getValueType() != MVT::i8)
22112 SDValue ShAmt1 = N1.getOperand(1);
22113 if (ShAmt1.getValueType() != MVT::i8)
22115 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22116 ShAmt0 = ShAmt0.getOperand(0);
22117 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22118 ShAmt1 = ShAmt1.getOperand(0);
22121 unsigned Opc = X86ISD::SHLD;
22122 SDValue Op0 = N0.getOperand(0);
22123 SDValue Op1 = N1.getOperand(0);
22124 if (ShAmt0.getOpcode() == ISD::SUB) {
22125 Opc = X86ISD::SHRD;
22126 std::swap(Op0, Op1);
22127 std::swap(ShAmt0, ShAmt1);
22130 unsigned Bits = VT.getSizeInBits();
22131 if (ShAmt1.getOpcode() == ISD::SUB) {
22132 SDValue Sum = ShAmt1.getOperand(0);
22133 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22134 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22135 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22136 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22137 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22138 return DAG.getNode(Opc, DL, VT,
22140 DAG.getNode(ISD::TRUNCATE, DL,
22143 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22144 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22146 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22147 return DAG.getNode(Opc, DL, VT,
22148 N0.getOperand(0), N1.getOperand(0),
22149 DAG.getNode(ISD::TRUNCATE, DL,
22156 // Generate NEG and CMOV for integer abs.
22157 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22158 EVT VT = N->getValueType(0);
22160 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22161 // 8-bit integer abs to NEG and CMOV.
22162 if (VT.isInteger() && VT.getSizeInBits() == 8)
22165 SDValue N0 = N->getOperand(0);
22166 SDValue N1 = N->getOperand(1);
22169 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22170 // and change it to SUB and CMOV.
22171 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22172 N0.getOpcode() == ISD::ADD &&
22173 N0.getOperand(1) == N1 &&
22174 N1.getOpcode() == ISD::SRA &&
22175 N1.getOperand(0) == N0.getOperand(0))
22176 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22177 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22178 // Generate SUB & CMOV.
22179 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22180 DAG.getConstant(0, VT), N0.getOperand(0));
22182 SDValue Ops[] = { N0.getOperand(0), Neg,
22183 DAG.getConstant(X86::COND_GE, MVT::i8),
22184 SDValue(Neg.getNode(), 1) };
22185 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22190 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22191 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22192 TargetLowering::DAGCombinerInfo &DCI,
22193 const X86Subtarget *Subtarget) {
22194 if (DCI.isBeforeLegalizeOps())
22197 if (Subtarget->hasCMov()) {
22198 SDValue RV = performIntegerAbsCombine(N, DAG);
22206 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22207 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22208 TargetLowering::DAGCombinerInfo &DCI,
22209 const X86Subtarget *Subtarget) {
22210 LoadSDNode *Ld = cast<LoadSDNode>(N);
22211 EVT RegVT = Ld->getValueType(0);
22212 EVT MemVT = Ld->getMemoryVT();
22214 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22216 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22217 // into two 16-byte operations.
22218 ISD::LoadExtType Ext = Ld->getExtensionType();
22219 unsigned Alignment = Ld->getAlignment();
22220 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22221 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22222 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22223 unsigned NumElems = RegVT.getVectorNumElements();
22227 SDValue Ptr = Ld->getBasePtr();
22228 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22230 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22232 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22233 Ld->getPointerInfo(), Ld->isVolatile(),
22234 Ld->isNonTemporal(), Ld->isInvariant(),
22236 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22237 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22238 Ld->getPointerInfo(), Ld->isVolatile(),
22239 Ld->isNonTemporal(), Ld->isInvariant(),
22240 std::min(16U, Alignment));
22241 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22243 Load2.getValue(1));
22245 SDValue NewVec = DAG.getUNDEF(RegVT);
22246 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22247 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22248 return DCI.CombineTo(N, NewVec, TF, true);
22254 /// PerformMLOADCombine - Resolve extending loads
22255 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22256 TargetLowering::DAGCombinerInfo &DCI,
22257 const X86Subtarget *Subtarget) {
22258 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22259 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22262 EVT VT = Mld->getValueType(0);
22263 unsigned NumElems = VT.getVectorNumElements();
22264 EVT LdVT = Mld->getMemoryVT();
22267 assert(LdVT != VT && "Cannot extend to the same type");
22268 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22269 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22270 // From, To sizes and ElemCount must be pow of two
22271 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22272 "Unexpected size for extending masked load");
22274 unsigned SizeRatio = ToSz / FromSz;
22275 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22277 // Create a type on which we perform the shuffle
22278 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22279 LdVT.getScalarType(), NumElems*SizeRatio);
22280 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22282 // Convert Src0 value
22283 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22284 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22285 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22286 for (unsigned i = 0; i != NumElems; ++i)
22287 ShuffleVec[i] = i * SizeRatio;
22289 // Can't shuffle using an illegal type.
22290 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22291 && "WideVecVT should be legal");
22292 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22293 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22295 // Prepare the new mask
22297 SDValue Mask = Mld->getMask();
22298 if (Mask.getValueType() == VT) {
22299 // Mask and original value have the same type
22300 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22301 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22302 for (unsigned i = 0; i != NumElems; ++i)
22303 ShuffleVec[i] = i * SizeRatio;
22304 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22305 ShuffleVec[i] = NumElems*SizeRatio;
22306 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22307 DAG.getConstant(0, WideVecVT),
22311 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22312 unsigned WidenNumElts = NumElems*SizeRatio;
22313 unsigned MaskNumElts = VT.getVectorNumElements();
22314 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22317 unsigned NumConcat = WidenNumElts / MaskNumElts;
22318 SmallVector<SDValue, 16> Ops(NumConcat);
22319 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22321 for (unsigned i = 1; i != NumConcat; ++i)
22324 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22327 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22328 Mld->getBasePtr(), NewMask, WideSrc0,
22329 Mld->getMemoryVT(), Mld->getMemOperand(),
22331 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22332 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22335 /// PerformMSTORECombine - Resolve truncating stores
22336 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22337 const X86Subtarget *Subtarget) {
22338 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22339 if (!Mst->isTruncatingStore())
22342 EVT VT = Mst->getValue().getValueType();
22343 unsigned NumElems = VT.getVectorNumElements();
22344 EVT StVT = Mst->getMemoryVT();
22347 assert(StVT != VT && "Cannot truncate to the same type");
22348 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22349 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22351 // From, To sizes and ElemCount must be pow of two
22352 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22353 "Unexpected size for truncating masked store");
22354 // We are going to use the original vector elt for storing.
22355 // Accumulated smaller vector elements must be a multiple of the store size.
22356 assert (((NumElems * FromSz) % ToSz) == 0 &&
22357 "Unexpected ratio for truncating masked store");
22359 unsigned SizeRatio = FromSz / ToSz;
22360 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22362 // Create a type on which we perform the shuffle
22363 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22364 StVT.getScalarType(), NumElems*SizeRatio);
22366 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22368 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22369 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22370 for (unsigned i = 0; i != NumElems; ++i)
22371 ShuffleVec[i] = i * SizeRatio;
22373 // Can't shuffle using an illegal type.
22374 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22375 && "WideVecVT should be legal");
22377 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22378 DAG.getUNDEF(WideVecVT),
22382 SDValue Mask = Mst->getMask();
22383 if (Mask.getValueType() == VT) {
22384 // Mask and original value have the same type
22385 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22386 for (unsigned i = 0; i != NumElems; ++i)
22387 ShuffleVec[i] = i * SizeRatio;
22388 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22389 ShuffleVec[i] = NumElems*SizeRatio;
22390 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22391 DAG.getConstant(0, WideVecVT),
22395 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22396 unsigned WidenNumElts = NumElems*SizeRatio;
22397 unsigned MaskNumElts = VT.getVectorNumElements();
22398 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22401 unsigned NumConcat = WidenNumElts / MaskNumElts;
22402 SmallVector<SDValue, 16> Ops(NumConcat);
22403 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22405 for (unsigned i = 1; i != NumConcat; ++i)
22408 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22411 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22412 NewMask, StVT, Mst->getMemOperand(), false);
22414 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22415 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22416 const X86Subtarget *Subtarget) {
22417 StoreSDNode *St = cast<StoreSDNode>(N);
22418 EVT VT = St->getValue().getValueType();
22419 EVT StVT = St->getMemoryVT();
22421 SDValue StoredVal = St->getOperand(1);
22422 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22424 // If we are saving a concatenation of two XMM registers and 32-byte stores
22425 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22426 unsigned Alignment = St->getAlignment();
22427 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22428 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22429 StVT == VT && !IsAligned) {
22430 unsigned NumElems = VT.getVectorNumElements();
22434 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22435 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22437 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22438 SDValue Ptr0 = St->getBasePtr();
22439 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22441 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22442 St->getPointerInfo(), St->isVolatile(),
22443 St->isNonTemporal(), Alignment);
22444 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22445 St->getPointerInfo(), St->isVolatile(),
22446 St->isNonTemporal(),
22447 std::min(16U, Alignment));
22448 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22451 // Optimize trunc store (of multiple scalars) to shuffle and store.
22452 // First, pack all of the elements in one place. Next, store to memory
22453 // in fewer chunks.
22454 if (St->isTruncatingStore() && VT.isVector()) {
22455 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22456 unsigned NumElems = VT.getVectorNumElements();
22457 assert(StVT != VT && "Cannot truncate to the same type");
22458 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22459 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22461 // From, To sizes and ElemCount must be pow of two
22462 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22463 // We are going to use the original vector elt for storing.
22464 // Accumulated smaller vector elements must be a multiple of the store size.
22465 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22467 unsigned SizeRatio = FromSz / ToSz;
22469 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22471 // Create a type on which we perform the shuffle
22472 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22473 StVT.getScalarType(), NumElems*SizeRatio);
22475 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22477 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22478 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22479 for (unsigned i = 0; i != NumElems; ++i)
22480 ShuffleVec[i] = i * SizeRatio;
22482 // Can't shuffle using an illegal type.
22483 if (!TLI.isTypeLegal(WideVecVT))
22486 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22487 DAG.getUNDEF(WideVecVT),
22489 // At this point all of the data is stored at the bottom of the
22490 // register. We now need to save it to mem.
22492 // Find the largest store unit
22493 MVT StoreType = MVT::i8;
22494 for (MVT Tp : MVT::integer_valuetypes()) {
22495 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22499 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22500 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22501 (64 <= NumElems * ToSz))
22502 StoreType = MVT::f64;
22504 // Bitcast the original vector into a vector of store-size units
22505 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22506 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22507 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22508 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22509 SmallVector<SDValue, 8> Chains;
22510 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22511 TLI.getPointerTy());
22512 SDValue Ptr = St->getBasePtr();
22514 // Perform one or more big stores into memory.
22515 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22516 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22517 StoreType, ShuffWide,
22518 DAG.getIntPtrConstant(i));
22519 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22520 St->getPointerInfo(), St->isVolatile(),
22521 St->isNonTemporal(), St->getAlignment());
22522 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22523 Chains.push_back(Ch);
22526 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22529 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22530 // the FP state in cases where an emms may be missing.
22531 // A preferable solution to the general problem is to figure out the right
22532 // places to insert EMMS. This qualifies as a quick hack.
22534 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22535 if (VT.getSizeInBits() != 64)
22538 const Function *F = DAG.getMachineFunction().getFunction();
22539 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22540 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22541 && Subtarget->hasSSE2();
22542 if ((VT.isVector() ||
22543 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22544 isa<LoadSDNode>(St->getValue()) &&
22545 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22546 St->getChain().hasOneUse() && !St->isVolatile()) {
22547 SDNode* LdVal = St->getValue().getNode();
22548 LoadSDNode *Ld = nullptr;
22549 int TokenFactorIndex = -1;
22550 SmallVector<SDValue, 8> Ops;
22551 SDNode* ChainVal = St->getChain().getNode();
22552 // Must be a store of a load. We currently handle two cases: the load
22553 // is a direct child, and it's under an intervening TokenFactor. It is
22554 // possible to dig deeper under nested TokenFactors.
22555 if (ChainVal == LdVal)
22556 Ld = cast<LoadSDNode>(St->getChain());
22557 else if (St->getValue().hasOneUse() &&
22558 ChainVal->getOpcode() == ISD::TokenFactor) {
22559 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22560 if (ChainVal->getOperand(i).getNode() == LdVal) {
22561 TokenFactorIndex = i;
22562 Ld = cast<LoadSDNode>(St->getValue());
22564 Ops.push_back(ChainVal->getOperand(i));
22568 if (!Ld || !ISD::isNormalLoad(Ld))
22571 // If this is not the MMX case, i.e. we are just turning i64 load/store
22572 // into f64 load/store, avoid the transformation if there are multiple
22573 // uses of the loaded value.
22574 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22579 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22580 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22582 if (Subtarget->is64Bit() || F64IsLegal) {
22583 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22584 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22585 Ld->getPointerInfo(), Ld->isVolatile(),
22586 Ld->isNonTemporal(), Ld->isInvariant(),
22587 Ld->getAlignment());
22588 SDValue NewChain = NewLd.getValue(1);
22589 if (TokenFactorIndex != -1) {
22590 Ops.push_back(NewChain);
22591 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22593 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22594 St->getPointerInfo(),
22595 St->isVolatile(), St->isNonTemporal(),
22596 St->getAlignment());
22599 // Otherwise, lower to two pairs of 32-bit loads / stores.
22600 SDValue LoAddr = Ld->getBasePtr();
22601 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22602 DAG.getConstant(4, MVT::i32));
22604 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22605 Ld->getPointerInfo(),
22606 Ld->isVolatile(), Ld->isNonTemporal(),
22607 Ld->isInvariant(), Ld->getAlignment());
22608 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22609 Ld->getPointerInfo().getWithOffset(4),
22610 Ld->isVolatile(), Ld->isNonTemporal(),
22612 MinAlign(Ld->getAlignment(), 4));
22614 SDValue NewChain = LoLd.getValue(1);
22615 if (TokenFactorIndex != -1) {
22616 Ops.push_back(LoLd);
22617 Ops.push_back(HiLd);
22618 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22621 LoAddr = St->getBasePtr();
22622 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22623 DAG.getConstant(4, MVT::i32));
22625 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22626 St->getPointerInfo(),
22627 St->isVolatile(), St->isNonTemporal(),
22628 St->getAlignment());
22629 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22630 St->getPointerInfo().getWithOffset(4),
22632 St->isNonTemporal(),
22633 MinAlign(St->getAlignment(), 4));
22634 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22639 /// Return 'true' if this vector operation is "horizontal"
22640 /// and return the operands for the horizontal operation in LHS and RHS. A
22641 /// horizontal operation performs the binary operation on successive elements
22642 /// of its first operand, then on successive elements of its second operand,
22643 /// returning the resulting values in a vector. For example, if
22644 /// A = < float a0, float a1, float a2, float a3 >
22646 /// B = < float b0, float b1, float b2, float b3 >
22647 /// then the result of doing a horizontal operation on A and B is
22648 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22649 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22650 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22651 /// set to A, RHS to B, and the routine returns 'true'.
22652 /// Note that the binary operation should have the property that if one of the
22653 /// operands is UNDEF then the result is UNDEF.
22654 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22655 // Look for the following pattern: if
22656 // A = < float a0, float a1, float a2, float a3 >
22657 // B = < float b0, float b1, float b2, float b3 >
22659 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22660 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22661 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22662 // which is A horizontal-op B.
22664 // At least one of the operands should be a vector shuffle.
22665 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22666 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22669 MVT VT = LHS.getSimpleValueType();
22671 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22672 "Unsupported vector type for horizontal add/sub");
22674 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22675 // operate independently on 128-bit lanes.
22676 unsigned NumElts = VT.getVectorNumElements();
22677 unsigned NumLanes = VT.getSizeInBits()/128;
22678 unsigned NumLaneElts = NumElts / NumLanes;
22679 assert((NumLaneElts % 2 == 0) &&
22680 "Vector type should have an even number of elements in each lane");
22681 unsigned HalfLaneElts = NumLaneElts/2;
22683 // View LHS in the form
22684 // LHS = VECTOR_SHUFFLE A, B, LMask
22685 // If LHS is not a shuffle then pretend it is the shuffle
22686 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22687 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22690 SmallVector<int, 16> LMask(NumElts);
22691 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22692 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22693 A = LHS.getOperand(0);
22694 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22695 B = LHS.getOperand(1);
22696 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22697 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22699 if (LHS.getOpcode() != ISD::UNDEF)
22701 for (unsigned i = 0; i != NumElts; ++i)
22705 // Likewise, view RHS in the form
22706 // RHS = VECTOR_SHUFFLE C, D, RMask
22708 SmallVector<int, 16> RMask(NumElts);
22709 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22710 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22711 C = RHS.getOperand(0);
22712 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22713 D = RHS.getOperand(1);
22714 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22715 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22717 if (RHS.getOpcode() != ISD::UNDEF)
22719 for (unsigned i = 0; i != NumElts; ++i)
22723 // Check that the shuffles are both shuffling the same vectors.
22724 if (!(A == C && B == D) && !(A == D && B == C))
22727 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22728 if (!A.getNode() && !B.getNode())
22731 // If A and B occur in reverse order in RHS, then "swap" them (which means
22732 // rewriting the mask).
22734 CommuteVectorShuffleMask(RMask, NumElts);
22736 // At this point LHS and RHS are equivalent to
22737 // LHS = VECTOR_SHUFFLE A, B, LMask
22738 // RHS = VECTOR_SHUFFLE A, B, RMask
22739 // Check that the masks correspond to performing a horizontal operation.
22740 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22741 for (unsigned i = 0; i != NumLaneElts; ++i) {
22742 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22744 // Ignore any UNDEF components.
22745 if (LIdx < 0 || RIdx < 0 ||
22746 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22747 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22750 // Check that successive elements are being operated on. If not, this is
22751 // not a horizontal operation.
22752 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22753 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22754 if (!(LIdx == Index && RIdx == Index + 1) &&
22755 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22760 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22761 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22765 /// Do target-specific dag combines on floating point adds.
22766 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22767 const X86Subtarget *Subtarget) {
22768 EVT VT = N->getValueType(0);
22769 SDValue LHS = N->getOperand(0);
22770 SDValue RHS = N->getOperand(1);
22772 // Try to synthesize horizontal adds from adds of shuffles.
22773 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22774 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22775 isHorizontalBinOp(LHS, RHS, true))
22776 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22780 /// Do target-specific dag combines on floating point subs.
22781 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22782 const X86Subtarget *Subtarget) {
22783 EVT VT = N->getValueType(0);
22784 SDValue LHS = N->getOperand(0);
22785 SDValue RHS = N->getOperand(1);
22787 // Try to synthesize horizontal subs from subs of shuffles.
22788 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22789 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22790 isHorizontalBinOp(LHS, RHS, false))
22791 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22795 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22796 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22797 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22799 // F[X]OR(0.0, x) -> x
22800 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22801 if (C->getValueAPF().isPosZero())
22802 return N->getOperand(1);
22804 // F[X]OR(x, 0.0) -> x
22805 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22806 if (C->getValueAPF().isPosZero())
22807 return N->getOperand(0);
22811 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22812 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22813 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22815 // Only perform optimizations if UnsafeMath is used.
22816 if (!DAG.getTarget().Options.UnsafeFPMath)
22819 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22820 // into FMINC and FMAXC, which are Commutative operations.
22821 unsigned NewOp = 0;
22822 switch (N->getOpcode()) {
22823 default: llvm_unreachable("unknown opcode");
22824 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22825 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22828 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22829 N->getOperand(0), N->getOperand(1));
22832 /// Do target-specific dag combines on X86ISD::FAND nodes.
22833 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22834 // FAND(0.0, x) -> 0.0
22835 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22836 if (C->getValueAPF().isPosZero())
22837 return N->getOperand(0);
22839 // FAND(x, 0.0) -> 0.0
22840 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22841 if (C->getValueAPF().isPosZero())
22842 return N->getOperand(1);
22847 /// Do target-specific dag combines on X86ISD::FANDN nodes
22848 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22849 // FANDN(0.0, x) -> x
22850 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22851 if (C->getValueAPF().isPosZero())
22852 return N->getOperand(1);
22854 // FANDN(x, 0.0) -> 0.0
22855 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22856 if (C->getValueAPF().isPosZero())
22857 return N->getOperand(1);
22862 static SDValue PerformBTCombine(SDNode *N,
22864 TargetLowering::DAGCombinerInfo &DCI) {
22865 // BT ignores high bits in the bit index operand.
22866 SDValue Op1 = N->getOperand(1);
22867 if (Op1.hasOneUse()) {
22868 unsigned BitWidth = Op1.getValueSizeInBits();
22869 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22870 APInt KnownZero, KnownOne;
22871 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22872 !DCI.isBeforeLegalizeOps());
22873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22874 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22875 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22876 DCI.CommitTargetLoweringOpt(TLO);
22881 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22882 SDValue Op = N->getOperand(0);
22883 if (Op.getOpcode() == ISD::BITCAST)
22884 Op = Op.getOperand(0);
22885 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22886 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22887 VT.getVectorElementType().getSizeInBits() ==
22888 OpVT.getVectorElementType().getSizeInBits()) {
22889 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22894 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22895 const X86Subtarget *Subtarget) {
22896 EVT VT = N->getValueType(0);
22897 if (!VT.isVector())
22900 SDValue N0 = N->getOperand(0);
22901 SDValue N1 = N->getOperand(1);
22902 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22905 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22906 // both SSE and AVX2 since there is no sign-extended shift right
22907 // operation on a vector with 64-bit elements.
22908 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22909 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22910 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22911 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22912 SDValue N00 = N0.getOperand(0);
22914 // EXTLOAD has a better solution on AVX2,
22915 // it may be replaced with X86ISD::VSEXT node.
22916 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22917 if (!ISD::isNormalLoad(N00.getNode()))
22920 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22921 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22923 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22929 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22930 TargetLowering::DAGCombinerInfo &DCI,
22931 const X86Subtarget *Subtarget) {
22932 SDValue N0 = N->getOperand(0);
22933 EVT VT = N->getValueType(0);
22935 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
22936 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
22937 // This exposes the sext to the sdivrem lowering, so that it directly extends
22938 // from AH (which we otherwise need to do contortions to access).
22939 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
22940 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
22942 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22943 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
22944 N0.getOperand(0), N0.getOperand(1));
22945 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22946 return R.getValue(1);
22949 if (!DCI.isBeforeLegalizeOps())
22952 if (!Subtarget->hasFp256())
22955 if (VT.isVector() && VT.getSizeInBits() == 256) {
22956 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22964 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22965 const X86Subtarget* Subtarget) {
22967 EVT VT = N->getValueType(0);
22969 // Let legalize expand this if it isn't a legal type yet.
22970 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22973 EVT ScalarVT = VT.getScalarType();
22974 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22975 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22978 SDValue A = N->getOperand(0);
22979 SDValue B = N->getOperand(1);
22980 SDValue C = N->getOperand(2);
22982 bool NegA = (A.getOpcode() == ISD::FNEG);
22983 bool NegB = (B.getOpcode() == ISD::FNEG);
22984 bool NegC = (C.getOpcode() == ISD::FNEG);
22986 // Negative multiplication when NegA xor NegB
22987 bool NegMul = (NegA != NegB);
22989 A = A.getOperand(0);
22991 B = B.getOperand(0);
22993 C = C.getOperand(0);
22997 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22999 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23001 return DAG.getNode(Opcode, dl, VT, A, B, C);
23004 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23005 TargetLowering::DAGCombinerInfo &DCI,
23006 const X86Subtarget *Subtarget) {
23007 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23008 // (and (i32 x86isd::setcc_carry), 1)
23009 // This eliminates the zext. This transformation is necessary because
23010 // ISD::SETCC is always legalized to i8.
23012 SDValue N0 = N->getOperand(0);
23013 EVT VT = N->getValueType(0);
23015 if (N0.getOpcode() == ISD::AND &&
23017 N0.getOperand(0).hasOneUse()) {
23018 SDValue N00 = N0.getOperand(0);
23019 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23020 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23021 if (!C || C->getZExtValue() != 1)
23023 return DAG.getNode(ISD::AND, dl, VT,
23024 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23025 N00.getOperand(0), N00.getOperand(1)),
23026 DAG.getConstant(1, VT));
23030 if (N0.getOpcode() == ISD::TRUNCATE &&
23032 N0.getOperand(0).hasOneUse()) {
23033 SDValue N00 = N0.getOperand(0);
23034 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23035 return DAG.getNode(ISD::AND, dl, VT,
23036 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23037 N00.getOperand(0), N00.getOperand(1)),
23038 DAG.getConstant(1, VT));
23041 if (VT.is256BitVector()) {
23042 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23047 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23048 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23049 // This exposes the zext to the udivrem lowering, so that it directly extends
23050 // from AH (which we otherwise need to do contortions to access).
23051 if (N0.getOpcode() == ISD::UDIVREM &&
23052 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23053 (VT == MVT::i32 || VT == MVT::i64)) {
23054 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23055 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23056 N0.getOperand(0), N0.getOperand(1));
23057 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23058 return R.getValue(1);
23064 // Optimize x == -y --> x+y == 0
23065 // x != -y --> x+y != 0
23066 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23067 const X86Subtarget* Subtarget) {
23068 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23069 SDValue LHS = N->getOperand(0);
23070 SDValue RHS = N->getOperand(1);
23071 EVT VT = N->getValueType(0);
23074 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23075 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23076 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23077 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23078 LHS.getValueType(), RHS, LHS.getOperand(1));
23079 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23080 addV, DAG.getConstant(0, addV.getValueType()), CC);
23082 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23084 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23085 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23086 RHS.getValueType(), LHS, RHS.getOperand(1));
23087 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23088 addV, DAG.getConstant(0, addV.getValueType()), CC);
23091 if (VT.getScalarType() == MVT::i1) {
23092 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23093 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23094 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
23095 if (!IsSEXT0 && !IsVZero0)
23097 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
23098 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23099 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23101 if (!IsSEXT1 && !IsVZero1)
23104 if (IsSEXT0 && IsVZero1) {
23105 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
23106 if (CC == ISD::SETEQ)
23107 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23108 return LHS.getOperand(0);
23110 if (IsSEXT1 && IsVZero0) {
23111 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
23112 if (CC == ISD::SETEQ)
23113 return DAG.getNOT(DL, RHS.getOperand(0), VT);
23114 return RHS.getOperand(0);
23121 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23122 SelectionDAG &DAG) {
23124 MVT VT = Load->getSimpleValueType(0);
23125 MVT EVT = VT.getVectorElementType();
23126 SDValue Addr = Load->getOperand(1);
23127 SDValue NewAddr = DAG.getNode(
23128 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23129 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23132 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23133 DAG.getMachineFunction().getMachineMemOperand(
23134 Load->getMemOperand(), 0, EVT.getStoreSize()));
23138 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23139 const X86Subtarget *Subtarget) {
23141 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23142 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23143 "X86insertps is only defined for v4x32");
23145 SDValue Ld = N->getOperand(1);
23146 if (MayFoldLoad(Ld)) {
23147 // Extract the countS bits from the immediate so we can get the proper
23148 // address when narrowing the vector load to a specific element.
23149 // When the second source op is a memory address, insertps doesn't use
23150 // countS and just gets an f32 from that address.
23151 unsigned DestIndex =
23152 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23154 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23156 // Create this as a scalar to vector to match the instruction pattern.
23157 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23158 // countS bits are ignored when loading from memory on insertps, which
23159 // means we don't need to explicitly set them to 0.
23160 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23161 LoadScalarToVector, N->getOperand(2));
23166 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23167 SDValue V0 = N->getOperand(0);
23168 SDValue V1 = N->getOperand(1);
23170 EVT VT = N->getValueType(0);
23172 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23173 // operands and changing the mask to 1. This saves us a bunch of
23174 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23175 // x86InstrInfo knows how to commute this back after instruction selection
23176 // if it would help register allocation.
23178 // TODO: If optimizing for size or a processor that doesn't suffer from
23179 // partial register update stalls, this should be transformed into a MOVSD
23180 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23182 if (VT == MVT::v2f64)
23183 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23184 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23185 SDValue NewMask = DAG.getConstant(1, MVT::i8);
23186 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23192 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23193 // as "sbb reg,reg", since it can be extended without zext and produces
23194 // an all-ones bit which is more useful than 0/1 in some cases.
23195 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23198 return DAG.getNode(ISD::AND, DL, VT,
23199 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23200 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23201 DAG.getConstant(1, VT));
23202 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23203 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23204 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23205 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23208 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23209 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23210 TargetLowering::DAGCombinerInfo &DCI,
23211 const X86Subtarget *Subtarget) {
23213 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23214 SDValue EFLAGS = N->getOperand(1);
23216 if (CC == X86::COND_A) {
23217 // Try to convert COND_A into COND_B in an attempt to facilitate
23218 // materializing "setb reg".
23220 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23221 // cannot take an immediate as its first operand.
23223 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23224 EFLAGS.getValueType().isInteger() &&
23225 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23226 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23227 EFLAGS.getNode()->getVTList(),
23228 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23229 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23230 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23234 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23235 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23237 if (CC == X86::COND_B)
23238 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23242 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23243 if (Flags.getNode()) {
23244 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23245 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23251 // Optimize branch condition evaluation.
23253 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23254 TargetLowering::DAGCombinerInfo &DCI,
23255 const X86Subtarget *Subtarget) {
23257 SDValue Chain = N->getOperand(0);
23258 SDValue Dest = N->getOperand(1);
23259 SDValue EFLAGS = N->getOperand(3);
23260 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23264 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23265 if (Flags.getNode()) {
23266 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23267 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23274 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23275 SelectionDAG &DAG) {
23276 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23277 // optimize away operation when it's from a constant.
23279 // The general transformation is:
23280 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23281 // AND(VECTOR_CMP(x,y), constant2)
23282 // constant2 = UNARYOP(constant)
23284 // Early exit if this isn't a vector operation, the operand of the
23285 // unary operation isn't a bitwise AND, or if the sizes of the operations
23286 // aren't the same.
23287 EVT VT = N->getValueType(0);
23288 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23289 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23290 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23293 // Now check that the other operand of the AND is a constant. We could
23294 // make the transformation for non-constant splats as well, but it's unclear
23295 // that would be a benefit as it would not eliminate any operations, just
23296 // perform one more step in scalar code before moving to the vector unit.
23297 if (BuildVectorSDNode *BV =
23298 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23299 // Bail out if the vector isn't a constant.
23300 if (!BV->isConstant())
23303 // Everything checks out. Build up the new and improved node.
23305 EVT IntVT = BV->getValueType(0);
23306 // Create a new constant of the appropriate type for the transformed
23308 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23309 // The AND node needs bitcasts to/from an integer vector type around it.
23310 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23311 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23312 N->getOperand(0)->getOperand(0), MaskConst);
23313 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23320 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23321 const X86Subtarget *Subtarget) {
23322 // First try to optimize away the conversion entirely when it's
23323 // conditionally from a constant. Vectors only.
23324 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23325 if (Res != SDValue())
23328 // Now move on to more general possibilities.
23329 SDValue Op0 = N->getOperand(0);
23330 EVT InVT = Op0->getValueType(0);
23332 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23333 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23335 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23336 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23337 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23340 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23341 // a 32-bit target where SSE doesn't support i64->FP operations.
23342 if (Op0.getOpcode() == ISD::LOAD) {
23343 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23344 EVT VT = Ld->getValueType(0);
23345 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23346 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23347 !Subtarget->is64Bit() && VT == MVT::i64) {
23348 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23349 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23350 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23357 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23358 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23359 X86TargetLowering::DAGCombinerInfo &DCI) {
23360 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23361 // the result is either zero or one (depending on the input carry bit).
23362 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23363 if (X86::isZeroNode(N->getOperand(0)) &&
23364 X86::isZeroNode(N->getOperand(1)) &&
23365 // We don't have a good way to replace an EFLAGS use, so only do this when
23367 SDValue(N, 1).use_empty()) {
23369 EVT VT = N->getValueType(0);
23370 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23371 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23372 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23373 DAG.getConstant(X86::COND_B,MVT::i8),
23375 DAG.getConstant(1, VT));
23376 return DCI.CombineTo(N, Res1, CarryOut);
23382 // fold (add Y, (sete X, 0)) -> adc 0, Y
23383 // (add Y, (setne X, 0)) -> sbb -1, Y
23384 // (sub (sete X, 0), Y) -> sbb 0, Y
23385 // (sub (setne X, 0), Y) -> adc -1, Y
23386 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23389 // Look through ZExts.
23390 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23391 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23394 SDValue SetCC = Ext.getOperand(0);
23395 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23398 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23399 if (CC != X86::COND_E && CC != X86::COND_NE)
23402 SDValue Cmp = SetCC.getOperand(1);
23403 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23404 !X86::isZeroNode(Cmp.getOperand(1)) ||
23405 !Cmp.getOperand(0).getValueType().isInteger())
23408 SDValue CmpOp0 = Cmp.getOperand(0);
23409 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23410 DAG.getConstant(1, CmpOp0.getValueType()));
23412 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23413 if (CC == X86::COND_NE)
23414 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23415 DL, OtherVal.getValueType(), OtherVal,
23416 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23417 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23418 DL, OtherVal.getValueType(), OtherVal,
23419 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23422 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23423 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23424 const X86Subtarget *Subtarget) {
23425 EVT VT = N->getValueType(0);
23426 SDValue Op0 = N->getOperand(0);
23427 SDValue Op1 = N->getOperand(1);
23429 // Try to synthesize horizontal adds from adds of shuffles.
23430 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23431 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23432 isHorizontalBinOp(Op0, Op1, true))
23433 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23435 return OptimizeConditionalInDecrement(N, DAG);
23438 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23439 const X86Subtarget *Subtarget) {
23440 SDValue Op0 = N->getOperand(0);
23441 SDValue Op1 = N->getOperand(1);
23443 // X86 can't encode an immediate LHS of a sub. See if we can push the
23444 // negation into a preceding instruction.
23445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23446 // If the RHS of the sub is a XOR with one use and a constant, invert the
23447 // immediate. Then add one to the LHS of the sub so we can turn
23448 // X-Y -> X+~Y+1, saving one register.
23449 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23450 isa<ConstantSDNode>(Op1.getOperand(1))) {
23451 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23452 EVT VT = Op0.getValueType();
23453 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23455 DAG.getConstant(~XorC, VT));
23456 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23457 DAG.getConstant(C->getAPIntValue()+1, VT));
23461 // Try to synthesize horizontal adds from adds of shuffles.
23462 EVT VT = N->getValueType(0);
23463 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23464 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23465 isHorizontalBinOp(Op0, Op1, true))
23466 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23468 return OptimizeConditionalInDecrement(N, DAG);
23471 /// performVZEXTCombine - Performs build vector combines
23472 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23473 TargetLowering::DAGCombinerInfo &DCI,
23474 const X86Subtarget *Subtarget) {
23476 MVT VT = N->getSimpleValueType(0);
23477 SDValue Op = N->getOperand(0);
23478 MVT OpVT = Op.getSimpleValueType();
23479 MVT OpEltVT = OpVT.getVectorElementType();
23480 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23482 // (vzext (bitcast (vzext (x)) -> (vzext x)
23484 while (V.getOpcode() == ISD::BITCAST)
23485 V = V.getOperand(0);
23487 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23488 MVT InnerVT = V.getSimpleValueType();
23489 MVT InnerEltVT = InnerVT.getVectorElementType();
23491 // If the element sizes match exactly, we can just do one larger vzext. This
23492 // is always an exact type match as vzext operates on integer types.
23493 if (OpEltVT == InnerEltVT) {
23494 assert(OpVT == InnerVT && "Types must match for vzext!");
23495 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23498 // The only other way we can combine them is if only a single element of the
23499 // inner vzext is used in the input to the outer vzext.
23500 if (InnerEltVT.getSizeInBits() < InputBits)
23503 // In this case, the inner vzext is completely dead because we're going to
23504 // only look at bits inside of the low element. Just do the outer vzext on
23505 // a bitcast of the input to the inner.
23506 return DAG.getNode(X86ISD::VZEXT, DL, VT,
23507 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23510 // Check if we can bypass extracting and re-inserting an element of an input
23511 // vector. Essentialy:
23512 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23513 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23514 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23515 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23516 SDValue ExtractedV = V.getOperand(0);
23517 SDValue OrigV = ExtractedV.getOperand(0);
23518 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23519 if (ExtractIdx->getZExtValue() == 0) {
23520 MVT OrigVT = OrigV.getSimpleValueType();
23521 // Extract a subvector if necessary...
23522 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23523 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23524 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23525 OrigVT.getVectorNumElements() / Ratio);
23526 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23527 DAG.getIntPtrConstant(0));
23529 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23530 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23537 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23538 DAGCombinerInfo &DCI) const {
23539 SelectionDAG &DAG = DCI.DAG;
23540 switch (N->getOpcode()) {
23542 case ISD::EXTRACT_VECTOR_ELT:
23543 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23546 case X86ISD::SHRUNKBLEND:
23547 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23548 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
23549 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23550 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23551 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23552 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23553 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23556 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23557 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23558 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23559 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23560 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23561 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23562 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23563 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
23564 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23565 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23566 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23568 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23570 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23571 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23572 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23573 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23574 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23575 case ISD::ANY_EXTEND:
23576 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23577 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23578 case ISD::SIGN_EXTEND_INREG:
23579 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23580 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23581 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23582 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23583 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23584 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23585 case X86ISD::SHUFP: // Handle all target specific shuffles
23586 case X86ISD::PALIGNR:
23587 case X86ISD::UNPCKH:
23588 case X86ISD::UNPCKL:
23589 case X86ISD::MOVHLPS:
23590 case X86ISD::MOVLHPS:
23591 case X86ISD::PSHUFB:
23592 case X86ISD::PSHUFD:
23593 case X86ISD::PSHUFHW:
23594 case X86ISD::PSHUFLW:
23595 case X86ISD::MOVSS:
23596 case X86ISD::MOVSD:
23597 case X86ISD::VPERMILPI:
23598 case X86ISD::VPERM2X128:
23599 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23600 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23601 case ISD::INTRINSIC_WO_CHAIN:
23602 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23603 case X86ISD::INSERTPS: {
23604 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23605 return PerformINSERTPSCombine(N, DAG, Subtarget);
23608 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
23609 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23615 /// isTypeDesirableForOp - Return true if the target has native support for
23616 /// the specified value type and it is 'desirable' to use the type for the
23617 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23618 /// instruction encodings are longer and some i16 instructions are slow.
23619 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23620 if (!isTypeLegal(VT))
23622 if (VT != MVT::i16)
23629 case ISD::SIGN_EXTEND:
23630 case ISD::ZERO_EXTEND:
23631 case ISD::ANY_EXTEND:
23644 /// IsDesirableToPromoteOp - This method query the target whether it is
23645 /// beneficial for dag combiner to promote the specified node. If true, it
23646 /// should return the desired promotion type by reference.
23647 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23648 EVT VT = Op.getValueType();
23649 if (VT != MVT::i16)
23652 bool Promote = false;
23653 bool Commute = false;
23654 switch (Op.getOpcode()) {
23657 LoadSDNode *LD = cast<LoadSDNode>(Op);
23658 // If the non-extending load has a single use and it's not live out, then it
23659 // might be folded.
23660 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23661 Op.hasOneUse()*/) {
23662 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23663 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23664 // The only case where we'd want to promote LOAD (rather then it being
23665 // promoted as an operand is when it's only use is liveout.
23666 if (UI->getOpcode() != ISD::CopyToReg)
23673 case ISD::SIGN_EXTEND:
23674 case ISD::ZERO_EXTEND:
23675 case ISD::ANY_EXTEND:
23680 SDValue N0 = Op.getOperand(0);
23681 // Look out for (store (shl (load), x)).
23682 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23695 SDValue N0 = Op.getOperand(0);
23696 SDValue N1 = Op.getOperand(1);
23697 if (!Commute && MayFoldLoad(N1))
23699 // Avoid disabling potential load folding opportunities.
23700 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23702 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23712 //===----------------------------------------------------------------------===//
23713 // X86 Inline Assembly Support
23714 //===----------------------------------------------------------------------===//
23716 // Helper to match a string separated by whitespace.
23717 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23718 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23720 for (StringRef Piece : Pieces) {
23721 if (!S.startswith(Piece)) // Check if the piece matches.
23724 S = S.substr(Piece.size());
23725 StringRef::size_type Pos = S.find_first_not_of(" \t");
23726 if (Pos == 0) // We matched a prefix.
23735 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23737 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23738 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23739 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23740 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23742 if (AsmPieces.size() == 3)
23744 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23751 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23752 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23754 std::string AsmStr = IA->getAsmString();
23756 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23757 if (!Ty || Ty->getBitWidth() % 16 != 0)
23760 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23761 SmallVector<StringRef, 4> AsmPieces;
23762 SplitString(AsmStr, AsmPieces, ";\n");
23764 switch (AsmPieces.size()) {
23765 default: return false;
23767 // FIXME: this should verify that we are targeting a 486 or better. If not,
23768 // we will turn this bswap into something that will be lowered to logical
23769 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23770 // lower so don't worry about this.
23772 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23773 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23774 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23775 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23776 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23777 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23778 // No need to check constraints, nothing other than the equivalent of
23779 // "=r,0" would be valid here.
23780 return IntrinsicLowering::LowerToByteSwap(CI);
23783 // rorw $$8, ${0:w} --> llvm.bswap.i16
23784 if (CI->getType()->isIntegerTy(16) &&
23785 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23786 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23787 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23789 const std::string &ConstraintsStr = IA->getConstraintString();
23790 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23791 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23792 if (clobbersFlagRegisters(AsmPieces))
23793 return IntrinsicLowering::LowerToByteSwap(CI);
23797 if (CI->getType()->isIntegerTy(32) &&
23798 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23799 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23800 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23801 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23803 const std::string &ConstraintsStr = IA->getConstraintString();
23804 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23805 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23806 if (clobbersFlagRegisters(AsmPieces))
23807 return IntrinsicLowering::LowerToByteSwap(CI);
23810 if (CI->getType()->isIntegerTy(64)) {
23811 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23812 if (Constraints.size() >= 2 &&
23813 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23814 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23815 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23816 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23817 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23818 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23819 return IntrinsicLowering::LowerToByteSwap(CI);
23827 /// getConstraintType - Given a constraint letter, return the type of
23828 /// constraint it is for this target.
23829 X86TargetLowering::ConstraintType
23830 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23831 if (Constraint.size() == 1) {
23832 switch (Constraint[0]) {
23843 return C_RegisterClass;
23867 return TargetLowering::getConstraintType(Constraint);
23870 /// Examine constraint type and operand type and determine a weight value.
23871 /// This object must already have been set up with the operand type
23872 /// and the current alternative constraint selected.
23873 TargetLowering::ConstraintWeight
23874 X86TargetLowering::getSingleConstraintMatchWeight(
23875 AsmOperandInfo &info, const char *constraint) const {
23876 ConstraintWeight weight = CW_Invalid;
23877 Value *CallOperandVal = info.CallOperandVal;
23878 // If we don't have a value, we can't do a match,
23879 // but allow it at the lowest weight.
23880 if (!CallOperandVal)
23882 Type *type = CallOperandVal->getType();
23883 // Look at the constraint type.
23884 switch (*constraint) {
23886 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23897 if (CallOperandVal->getType()->isIntegerTy())
23898 weight = CW_SpecificReg;
23903 if (type->isFloatingPointTy())
23904 weight = CW_SpecificReg;
23907 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23908 weight = CW_SpecificReg;
23912 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23913 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23914 weight = CW_Register;
23917 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23918 if (C->getZExtValue() <= 31)
23919 weight = CW_Constant;
23923 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23924 if (C->getZExtValue() <= 63)
23925 weight = CW_Constant;
23929 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23930 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23931 weight = CW_Constant;
23935 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23936 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23937 weight = CW_Constant;
23941 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23942 if (C->getZExtValue() <= 3)
23943 weight = CW_Constant;
23947 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23948 if (C->getZExtValue() <= 0xff)
23949 weight = CW_Constant;
23954 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23955 weight = CW_Constant;
23959 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23960 if ((C->getSExtValue() >= -0x80000000LL) &&
23961 (C->getSExtValue() <= 0x7fffffffLL))
23962 weight = CW_Constant;
23966 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23967 if (C->getZExtValue() <= 0xffffffff)
23968 weight = CW_Constant;
23975 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23976 /// with another that has more specific requirements based on the type of the
23977 /// corresponding operand.
23978 const char *X86TargetLowering::
23979 LowerXConstraint(EVT ConstraintVT) const {
23980 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23981 // 'f' like normal targets.
23982 if (ConstraintVT.isFloatingPoint()) {
23983 if (Subtarget->hasSSE2())
23985 if (Subtarget->hasSSE1())
23989 return TargetLowering::LowerXConstraint(ConstraintVT);
23992 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23993 /// vector. If it is invalid, don't add anything to Ops.
23994 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23995 std::string &Constraint,
23996 std::vector<SDValue>&Ops,
23997 SelectionDAG &DAG) const {
24000 // Only support length 1 constraints for now.
24001 if (Constraint.length() > 1) return;
24003 char ConstraintLetter = Constraint[0];
24004 switch (ConstraintLetter) {
24007 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24008 if (C->getZExtValue() <= 31) {
24009 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24015 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24016 if (C->getZExtValue() <= 63) {
24017 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24023 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24024 if (isInt<8>(C->getSExtValue())) {
24025 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24032 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24033 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24034 Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24041 if (C->getZExtValue() <= 3) {
24042 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24049 if (C->getZExtValue() <= 255) {
24050 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24056 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24057 if (C->getZExtValue() <= 127) {
24058 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24064 // 32-bit signed value
24065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24066 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24067 C->getSExtValue())) {
24068 // Widen to 64 bits here to get it sign extended.
24069 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24072 // FIXME gcc accepts some relocatable values here too, but only in certain
24073 // memory models; it's complicated.
24078 // 32-bit unsigned value
24079 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24080 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24081 C->getZExtValue())) {
24082 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24086 // FIXME gcc accepts some relocatable values here too, but only in certain
24087 // memory models; it's complicated.
24091 // Literal immediates are always ok.
24092 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24093 // Widen to 64 bits here to get it sign extended.
24094 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24098 // In any sort of PIC mode addresses need to be computed at runtime by
24099 // adding in a register or some sort of table lookup. These can't
24100 // be used as immediates.
24101 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24104 // If we are in non-pic codegen mode, we allow the address of a global (with
24105 // an optional displacement) to be used with 'i'.
24106 GlobalAddressSDNode *GA = nullptr;
24107 int64_t Offset = 0;
24109 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24111 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24112 Offset += GA->getOffset();
24114 } else if (Op.getOpcode() == ISD::ADD) {
24115 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24116 Offset += C->getZExtValue();
24117 Op = Op.getOperand(0);
24120 } else if (Op.getOpcode() == ISD::SUB) {
24121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24122 Offset += -C->getZExtValue();
24123 Op = Op.getOperand(0);
24128 // Otherwise, this isn't something we can handle, reject it.
24132 const GlobalValue *GV = GA->getGlobal();
24133 // If we require an extra load to get this address, as in PIC mode, we
24134 // can't accept it.
24135 if (isGlobalStubReference(
24136 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24139 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24140 GA->getValueType(0), Offset);
24145 if (Result.getNode()) {
24146 Ops.push_back(Result);
24149 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24152 std::pair<unsigned, const TargetRegisterClass *>
24153 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24154 const std::string &Constraint,
24156 // First, see if this is a constraint that directly corresponds to an LLVM
24158 if (Constraint.size() == 1) {
24159 // GCC Constraint Letters
24160 switch (Constraint[0]) {
24162 // TODO: Slight differences here in allocation order and leaving
24163 // RIP in the class. Do they matter any more here than they do
24164 // in the normal allocation?
24165 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24166 if (Subtarget->is64Bit()) {
24167 if (VT == MVT::i32 || VT == MVT::f32)
24168 return std::make_pair(0U, &X86::GR32RegClass);
24169 if (VT == MVT::i16)
24170 return std::make_pair(0U, &X86::GR16RegClass);
24171 if (VT == MVT::i8 || VT == MVT::i1)
24172 return std::make_pair(0U, &X86::GR8RegClass);
24173 if (VT == MVT::i64 || VT == MVT::f64)
24174 return std::make_pair(0U, &X86::GR64RegClass);
24177 // 32-bit fallthrough
24178 case 'Q': // Q_REGS
24179 if (VT == MVT::i32 || VT == MVT::f32)
24180 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24181 if (VT == MVT::i16)
24182 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24183 if (VT == MVT::i8 || VT == MVT::i1)
24184 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24185 if (VT == MVT::i64)
24186 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24188 case 'r': // GENERAL_REGS
24189 case 'l': // INDEX_REGS
24190 if (VT == MVT::i8 || VT == MVT::i1)
24191 return std::make_pair(0U, &X86::GR8RegClass);
24192 if (VT == MVT::i16)
24193 return std::make_pair(0U, &X86::GR16RegClass);
24194 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24195 return std::make_pair(0U, &X86::GR32RegClass);
24196 return std::make_pair(0U, &X86::GR64RegClass);
24197 case 'R': // LEGACY_REGS
24198 if (VT == MVT::i8 || VT == MVT::i1)
24199 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24200 if (VT == MVT::i16)
24201 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24202 if (VT == MVT::i32 || !Subtarget->is64Bit())
24203 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24204 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24205 case 'f': // FP Stack registers.
24206 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24207 // value to the correct fpstack register class.
24208 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24209 return std::make_pair(0U, &X86::RFP32RegClass);
24210 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24211 return std::make_pair(0U, &X86::RFP64RegClass);
24212 return std::make_pair(0U, &X86::RFP80RegClass);
24213 case 'y': // MMX_REGS if MMX allowed.
24214 if (!Subtarget->hasMMX()) break;
24215 return std::make_pair(0U, &X86::VR64RegClass);
24216 case 'Y': // SSE_REGS if SSE2 allowed
24217 if (!Subtarget->hasSSE2()) break;
24219 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24220 if (!Subtarget->hasSSE1()) break;
24222 switch (VT.SimpleTy) {
24224 // Scalar SSE types.
24227 return std::make_pair(0U, &X86::FR32RegClass);
24230 return std::make_pair(0U, &X86::FR64RegClass);
24238 return std::make_pair(0U, &X86::VR128RegClass);
24246 return std::make_pair(0U, &X86::VR256RegClass);
24251 return std::make_pair(0U, &X86::VR512RegClass);
24257 // Use the default implementation in TargetLowering to convert the register
24258 // constraint into a member of a register class.
24259 std::pair<unsigned, const TargetRegisterClass*> Res;
24260 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24262 // Not found as a standard register?
24264 // Map st(0) -> st(7) -> ST0
24265 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24266 tolower(Constraint[1]) == 's' &&
24267 tolower(Constraint[2]) == 't' &&
24268 Constraint[3] == '(' &&
24269 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24270 Constraint[5] == ')' &&
24271 Constraint[6] == '}') {
24273 Res.first = X86::FP0+Constraint[4]-'0';
24274 Res.second = &X86::RFP80RegClass;
24278 // GCC allows "st(0)" to be called just plain "st".
24279 if (StringRef("{st}").equals_lower(Constraint)) {
24280 Res.first = X86::FP0;
24281 Res.second = &X86::RFP80RegClass;
24286 if (StringRef("{flags}").equals_lower(Constraint)) {
24287 Res.first = X86::EFLAGS;
24288 Res.second = &X86::CCRRegClass;
24292 // 'A' means EAX + EDX.
24293 if (Constraint == "A") {
24294 Res.first = X86::EAX;
24295 Res.second = &X86::GR32_ADRegClass;
24301 // Otherwise, check to see if this is a register class of the wrong value
24302 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24303 // turn into {ax},{dx}.
24304 if (Res.second->hasType(VT))
24305 return Res; // Correct type already, nothing to do.
24307 // All of the single-register GCC register classes map their values onto
24308 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24309 // really want an 8-bit or 32-bit register, map to the appropriate register
24310 // class and return the appropriate register.
24311 if (Res.second == &X86::GR16RegClass) {
24312 if (VT == MVT::i8 || VT == MVT::i1) {
24313 unsigned DestReg = 0;
24314 switch (Res.first) {
24316 case X86::AX: DestReg = X86::AL; break;
24317 case X86::DX: DestReg = X86::DL; break;
24318 case X86::CX: DestReg = X86::CL; break;
24319 case X86::BX: DestReg = X86::BL; break;
24322 Res.first = DestReg;
24323 Res.second = &X86::GR8RegClass;
24325 } else if (VT == MVT::i32 || VT == MVT::f32) {
24326 unsigned DestReg = 0;
24327 switch (Res.first) {
24329 case X86::AX: DestReg = X86::EAX; break;
24330 case X86::DX: DestReg = X86::EDX; break;
24331 case X86::CX: DestReg = X86::ECX; break;
24332 case X86::BX: DestReg = X86::EBX; break;
24333 case X86::SI: DestReg = X86::ESI; break;
24334 case X86::DI: DestReg = X86::EDI; break;
24335 case X86::BP: DestReg = X86::EBP; break;
24336 case X86::SP: DestReg = X86::ESP; break;
24339 Res.first = DestReg;
24340 Res.second = &X86::GR32RegClass;
24342 } else if (VT == MVT::i64 || VT == MVT::f64) {
24343 unsigned DestReg = 0;
24344 switch (Res.first) {
24346 case X86::AX: DestReg = X86::RAX; break;
24347 case X86::DX: DestReg = X86::RDX; break;
24348 case X86::CX: DestReg = X86::RCX; break;
24349 case X86::BX: DestReg = X86::RBX; break;
24350 case X86::SI: DestReg = X86::RSI; break;
24351 case X86::DI: DestReg = X86::RDI; break;
24352 case X86::BP: DestReg = X86::RBP; break;
24353 case X86::SP: DestReg = X86::RSP; break;
24356 Res.first = DestReg;
24357 Res.second = &X86::GR64RegClass;
24360 } else if (Res.second == &X86::FR32RegClass ||
24361 Res.second == &X86::FR64RegClass ||
24362 Res.second == &X86::VR128RegClass ||
24363 Res.second == &X86::VR256RegClass ||
24364 Res.second == &X86::FR32XRegClass ||
24365 Res.second == &X86::FR64XRegClass ||
24366 Res.second == &X86::VR128XRegClass ||
24367 Res.second == &X86::VR256XRegClass ||
24368 Res.second == &X86::VR512RegClass) {
24369 // Handle references to XMM physical registers that got mapped into the
24370 // wrong class. This can happen with constraints like {xmm0} where the
24371 // target independent register mapper will just pick the first match it can
24372 // find, ignoring the required type.
24374 if (VT == MVT::f32 || VT == MVT::i32)
24375 Res.second = &X86::FR32RegClass;
24376 else if (VT == MVT::f64 || VT == MVT::i64)
24377 Res.second = &X86::FR64RegClass;
24378 else if (X86::VR128RegClass.hasType(VT))
24379 Res.second = &X86::VR128RegClass;
24380 else if (X86::VR256RegClass.hasType(VT))
24381 Res.second = &X86::VR256RegClass;
24382 else if (X86::VR512RegClass.hasType(VT))
24383 Res.second = &X86::VR512RegClass;
24389 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24391 // Scaling factors are not free at all.
24392 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24393 // will take 2 allocations in the out of order engine instead of 1
24394 // for plain addressing mode, i.e. inst (reg1).
24396 // vaddps (%rsi,%drx), %ymm0, %ymm1
24397 // Requires two allocations (one for the load, one for the computation)
24399 // vaddps (%rsi), %ymm0, %ymm1
24400 // Requires just 1 allocation, i.e., freeing allocations for other operations
24401 // and having less micro operations to execute.
24403 // For some X86 architectures, this is even worse because for instance for
24404 // stores, the complex addressing mode forces the instruction to use the
24405 // "load" ports instead of the dedicated "store" port.
24406 // E.g., on Haswell:
24407 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24408 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24409 if (isLegalAddressingMode(AM, Ty))
24410 // Scale represents reg2 * scale, thus account for 1
24411 // as soon as we use a second register.
24412 return AM.Scale != 0;
24416 bool X86TargetLowering::isTargetFTOL() const {
24417 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();