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 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
874 setOperationAction(ISD::MULHS, MMXTy, Expand);
875 setOperationAction(ISD::AND, MMXTy, Expand);
876 setOperationAction(ISD::OR, MMXTy, Expand);
877 setOperationAction(ISD::XOR, MMXTy, Expand);
878 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
879 setOperationAction(ISD::SELECT, MMXTy, Expand);
880 setOperationAction(ISD::BITCAST, MMXTy, Expand);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
884 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
885 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
887 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
888 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
889 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
890 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
891 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
892 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
893 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
894 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
895 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
897 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
899 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
900 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
903 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
904 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
906 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
907 // registers cannot be used even for integer operations.
908 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
909 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
910 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
911 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
913 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
914 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
915 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
916 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
917 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
918 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
919 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
920 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
921 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
922 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
923 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
924 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
925 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
926 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
927 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
928 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
929 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
930 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
931 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
932 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
933 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
934 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
936 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
937 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
938 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
939 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
941 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
942 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
943 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
944 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
945 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
947 // Only provide customized ctpop vector bit twiddling for vector types we
948 // know to perform better than using the popcnt instructions on each vector
949 // element. If popcnt isn't supported, always provide the custom version.
950 if (!Subtarget->hasPOPCNT()) {
951 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
952 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
955 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
956 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
957 MVT VT = (MVT::SimpleValueType)i;
958 // Do not attempt to custom lower non-power-of-2 vectors
959 if (!isPowerOf2_32(VT.getVectorNumElements()))
961 // Do not attempt to custom lower non-128-bit vectors
962 if (!VT.is128BitVector())
964 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
965 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
966 setOperationAction(ISD::VSELECT, VT, Custom);
967 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
970 // We support custom legalizing of sext and anyext loads for specific
971 // memory vector types which we can load as a scalar (or sequence of
972 // scalars) and extend in-register to a legal 128-bit vector type. For sext
973 // loads these must work with a single scalar load.
974 for (MVT VT : MVT::integer_vector_valuetypes()) {
975 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
976 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
977 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
978 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
979 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
980 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
981 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
982 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
983 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
990 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
991 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
995 if (Subtarget->is64Bit()) {
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1000 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1004 // Do not attempt to promote non-128-bit vectors
1005 if (!VT.is128BitVector())
1008 setOperationAction(ISD::AND, VT, Promote);
1009 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1010 setOperationAction(ISD::OR, VT, Promote);
1011 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1012 setOperationAction(ISD::XOR, VT, Promote);
1013 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1014 setOperationAction(ISD::LOAD, VT, Promote);
1015 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1016 setOperationAction(ISD::SELECT, VT, Promote);
1017 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1020 // Custom lower v2i64 and v2f64 selects.
1021 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1022 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1023 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1024 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1026 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1027 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1031 // As there is no 64-bit GPR available, we need build a special custom
1032 // sequence to convert from v2i32 to v2f32.
1033 if (!Subtarget->is64Bit())
1034 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1039 for (MVT VT : MVT::fp_vector_valuetypes())
1040 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1042 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1043 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1044 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1047 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1048 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1049 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1050 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1051 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1052 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1053 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
1056 // FIXME: Do we need to handle scalar-to-vector here?
1057 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1059 // We directly match byte blends in the backend as they match the VSELECT
1061 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1063 // SSE41 brings specific instructions for doing vector sign extend even in
1064 // cases where we don't have SRA.
1065 for (MVT VT : MVT::integer_vector_valuetypes()) {
1066 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1067 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1068 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1071 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1072 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1073 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1074 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1075 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1076 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1077 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1079 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1080 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1081 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1082 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1083 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1084 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1086 // i8 and i16 vectors are custom because the source register and source
1087 // source memory operand types are not the same width. f32 vectors are
1088 // custom since the immediate controlling the insert encodes additional
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1095 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1096 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1100 // FIXME: these should be Legal, but that's only for the case where
1101 // the index is constant. For now custom expand to deal with that.
1102 if (Subtarget->is64Bit()) {
1103 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1108 if (Subtarget->hasSSE2()) {
1109 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1112 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1113 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1115 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1118 // In the customized shift lowering, the legal cases in AVX2 will be
1120 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1121 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1123 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1124 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1126 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1129 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1130 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1131 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1132 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1137 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1138 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1141 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1152 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1154 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1165 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1167 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1168 // even though v8i16 is a legal type.
1169 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1170 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1171 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1173 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1174 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1175 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1177 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1178 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1180 for (MVT VT : MVT::fp_vector_valuetypes())
1181 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1183 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1184 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1186 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1187 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1189 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1190 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1199 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1201 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1202 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1203 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1204 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1205 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1206 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1207 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1208 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1209 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1210 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1211 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1212 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1214 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1215 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1216 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1217 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1218 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1219 setOperationAction(ISD::FMA, MVT::f32, Legal);
1220 setOperationAction(ISD::FMA, MVT::f64, Legal);
1223 if (Subtarget->hasInt256()) {
1224 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1225 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1226 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1227 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1229 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1230 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1231 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1232 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1234 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1235 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1236 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1237 // Don't lower v32i8 because there is no 128-bit byte mul
1239 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1241 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1242 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1244 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1245 // when we have a 256bit-wide blend with immediate.
1246 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1248 // Only provide customized ctpop vector bit twiddling for vector types we
1249 // know to perform better than using the popcnt instructions on each
1250 // vector element. If popcnt isn't supported, always provide the custom
1252 if (!Subtarget->hasPOPCNT())
1253 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1255 // Custom CTPOP always performs better on natively supported v8i32
1256 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1258 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1259 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1260 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1261 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1262 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1263 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1264 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1266 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1267 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1268 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1269 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1270 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1271 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1273 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1274 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1275 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1276 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1278 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1279 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1280 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1281 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1283 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1284 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1285 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1286 // Don't lower v32i8 because there is no 128-bit byte mul
1289 // In the customized shift lowering, the legal cases in AVX2 will be
1291 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1292 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1294 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1295 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1297 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1299 // Custom lower several nodes for 256-bit types.
1300 for (MVT VT : MVT::vector_valuetypes()) {
1301 if (VT.getScalarSizeInBits() >= 32) {
1302 setOperationAction(ISD::MLOAD, VT, Legal);
1303 setOperationAction(ISD::MSTORE, VT, Legal);
1305 // Extract subvector is special because the value type
1306 // (result) is 128-bit but the source is 256-bit wide.
1307 if (VT.is128BitVector()) {
1308 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1310 // Do not attempt to custom lower other non-256-bit vectors
1311 if (!VT.is256BitVector())
1314 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1315 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1316 setOperationAction(ISD::VSELECT, VT, Custom);
1317 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1318 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1319 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1320 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1321 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1324 if (Subtarget->hasInt256())
1325 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1328 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1329 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1330 MVT VT = (MVT::SimpleValueType)i;
1332 // Do not attempt to promote non-256-bit vectors
1333 if (!VT.is256BitVector())
1336 setOperationAction(ISD::AND, VT, Promote);
1337 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1338 setOperationAction(ISD::OR, VT, Promote);
1339 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1340 setOperationAction(ISD::XOR, VT, Promote);
1341 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1342 setOperationAction(ISD::LOAD, VT, Promote);
1343 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1344 setOperationAction(ISD::SELECT, VT, Promote);
1345 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1349 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1350 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1351 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1352 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1353 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1355 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1356 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1357 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1359 for (MVT VT : MVT::fp_vector_valuetypes())
1360 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1362 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1363 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1364 setOperationAction(ISD::XOR, MVT::i1, Legal);
1365 setOperationAction(ISD::OR, MVT::i1, Legal);
1366 setOperationAction(ISD::AND, MVT::i1, Legal);
1367 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1368 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1369 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1370 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1371 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1373 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1374 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1375 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1376 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1377 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1378 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1380 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1381 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1382 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1383 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1384 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1385 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1386 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1387 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1390 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1391 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1392 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1393 if (Subtarget->is64Bit()) {
1394 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1395 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1396 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1397 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1399 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1400 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1401 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1402 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1403 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1404 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1405 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1406 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1407 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1408 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1409 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1410 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1411 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1412 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1414 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1415 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1416 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1417 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1418 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1419 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1420 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1421 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1422 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1423 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1424 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1425 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1426 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1428 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1429 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1430 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1431 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1432 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1433 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1434 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1435 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1436 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1437 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1439 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1445 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1446 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1448 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1454 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1456 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1460 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1461 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1463 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1464 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1466 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1468 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1469 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1471 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1472 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1474 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1475 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1477 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1478 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1479 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1481 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1482 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1484 if (Subtarget->hasCDI()) {
1485 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1486 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1489 // Custom lower several nodes.
1490 for (MVT VT : MVT::vector_valuetypes()) {
1491 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1492 // Extract subvector is special because the value type
1493 // (result) is 256/128-bit but the source is 512-bit wide.
1494 if (VT.is128BitVector() || VT.is256BitVector()) {
1495 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1497 if (VT.getVectorElementType() == MVT::i1)
1498 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1500 // Do not attempt to custom lower other non-512-bit vectors
1501 if (!VT.is512BitVector())
1504 if ( EltSize >= 32) {
1505 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1506 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1507 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1508 setOperationAction(ISD::VSELECT, VT, Legal);
1509 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1510 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1511 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1512 setOperationAction(ISD::MLOAD, VT, Legal);
1513 setOperationAction(ISD::MSTORE, VT, Legal);
1516 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517 MVT VT = (MVT::SimpleValueType)i;
1519 // Do not attempt to promote non-512-bit vectors.
1520 if (!VT.is512BitVector())
1523 setOperationAction(ISD::SELECT, VT, Promote);
1524 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1528 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1532 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1533 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1536 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1537 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1538 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1539 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1540 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1541 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1542 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1543 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1544 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1545 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1546 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1547 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1549 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1550 const MVT VT = (MVT::SimpleValueType)i;
1552 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1554 // Do not attempt to promote non-512-bit vectors.
1555 if (!VT.is512BitVector())
1559 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1560 setOperationAction(ISD::VSELECT, VT, Legal);
1565 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1566 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1567 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1569 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1570 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1571 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1572 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1573 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1574 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1576 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1577 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1578 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1579 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1580 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1581 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1584 // We want to custom lower some of our intrinsics.
1585 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1586 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1587 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1588 if (!Subtarget->is64Bit())
1589 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1591 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1592 // handle type legalization for these operations here.
1594 // FIXME: We really should do custom legalization for addition and
1595 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1596 // than generic legalization for 64-bit multiplication-with-overflow, though.
1597 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1598 // Add/Sub/Mul with overflow operations are custom lowered.
1600 setOperationAction(ISD::SADDO, VT, Custom);
1601 setOperationAction(ISD::UADDO, VT, Custom);
1602 setOperationAction(ISD::SSUBO, VT, Custom);
1603 setOperationAction(ISD::USUBO, VT, Custom);
1604 setOperationAction(ISD::SMULO, VT, Custom);
1605 setOperationAction(ISD::UMULO, VT, Custom);
1609 if (!Subtarget->is64Bit()) {
1610 // These libcalls are not available in 32-bit.
1611 setLibcallName(RTLIB::SHL_I128, nullptr);
1612 setLibcallName(RTLIB::SRL_I128, nullptr);
1613 setLibcallName(RTLIB::SRA_I128, nullptr);
1616 // Combine sin / cos into one node or libcall if possible.
1617 if (Subtarget->hasSinCos()) {
1618 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1619 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1620 if (Subtarget->isTargetDarwin()) {
1621 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1622 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1623 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1624 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1628 if (Subtarget->isTargetWin64()) {
1629 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1630 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1631 setOperationAction(ISD::SREM, MVT::i128, Custom);
1632 setOperationAction(ISD::UREM, MVT::i128, Custom);
1633 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1634 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1637 // We have target-specific dag combine patterns for the following nodes:
1638 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1639 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1640 setTargetDAGCombine(ISD::BITCAST);
1641 setTargetDAGCombine(ISD::VSELECT);
1642 setTargetDAGCombine(ISD::SELECT);
1643 setTargetDAGCombine(ISD::SHL);
1644 setTargetDAGCombine(ISD::SRA);
1645 setTargetDAGCombine(ISD::SRL);
1646 setTargetDAGCombine(ISD::OR);
1647 setTargetDAGCombine(ISD::AND);
1648 setTargetDAGCombine(ISD::ADD);
1649 setTargetDAGCombine(ISD::FADD);
1650 setTargetDAGCombine(ISD::FSUB);
1651 setTargetDAGCombine(ISD::FMA);
1652 setTargetDAGCombine(ISD::SUB);
1653 setTargetDAGCombine(ISD::LOAD);
1654 setTargetDAGCombine(ISD::MLOAD);
1655 setTargetDAGCombine(ISD::STORE);
1656 setTargetDAGCombine(ISD::MSTORE);
1657 setTargetDAGCombine(ISD::ZERO_EXTEND);
1658 setTargetDAGCombine(ISD::ANY_EXTEND);
1659 setTargetDAGCombine(ISD::SIGN_EXTEND);
1660 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1661 setTargetDAGCombine(ISD::TRUNCATE);
1662 setTargetDAGCombine(ISD::SINT_TO_FP);
1663 setTargetDAGCombine(ISD::SETCC);
1664 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1665 setTargetDAGCombine(ISD::BUILD_VECTOR);
1666 setTargetDAGCombine(ISD::MUL);
1667 setTargetDAGCombine(ISD::XOR);
1669 computeRegisterProperties(Subtarget->getRegisterInfo());
1671 // On Darwin, -Os means optimize for size without hurting performance,
1672 // do not reduce the limit.
1673 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1674 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1675 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1676 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1677 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1678 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1679 setPrefLoopAlignment(4); // 2^4 bytes.
1681 // Predictable cmov don't hurt on atom because it's in-order.
1682 PredictableSelectIsExpensive = !Subtarget->isAtom();
1683 EnableExtLdPromotion = true;
1684 setPrefFunctionAlignment(4); // 2^4 bytes.
1686 verifyIntrinsicTables();
1689 // This has so far only been implemented for 64-bit MachO.
1690 bool X86TargetLowering::useLoadStackGuardNode() const {
1691 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1694 TargetLoweringBase::LegalizeTypeAction
1695 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1696 if (ExperimentalVectorWideningLegalization &&
1697 VT.getVectorNumElements() != 1 &&
1698 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1699 return TypeWidenVector;
1701 return TargetLoweringBase::getPreferredVectorAction(VT);
1704 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1706 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1708 const unsigned NumElts = VT.getVectorNumElements();
1709 const EVT EltVT = VT.getVectorElementType();
1710 if (VT.is512BitVector()) {
1711 if (Subtarget->hasAVX512())
1712 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1713 EltVT == MVT::f32 || EltVT == MVT::f64)
1715 case 8: return MVT::v8i1;
1716 case 16: return MVT::v16i1;
1718 if (Subtarget->hasBWI())
1719 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1721 case 32: return MVT::v32i1;
1722 case 64: return MVT::v64i1;
1726 if (VT.is256BitVector() || VT.is128BitVector()) {
1727 if (Subtarget->hasVLX())
1728 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1729 EltVT == MVT::f32 || EltVT == MVT::f64)
1731 case 2: return MVT::v2i1;
1732 case 4: return MVT::v4i1;
1733 case 8: return MVT::v8i1;
1735 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1736 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1738 case 8: return MVT::v8i1;
1739 case 16: return MVT::v16i1;
1740 case 32: return MVT::v32i1;
1744 return VT.changeVectorElementTypeToInteger();
1747 /// Helper for getByValTypeAlignment to determine
1748 /// the desired ByVal argument alignment.
1749 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1752 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1753 if (VTy->getBitWidth() == 128)
1755 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1756 unsigned EltAlign = 0;
1757 getMaxByValAlign(ATy->getElementType(), EltAlign);
1758 if (EltAlign > MaxAlign)
1759 MaxAlign = EltAlign;
1760 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1761 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1762 unsigned EltAlign = 0;
1763 getMaxByValAlign(STy->getElementType(i), EltAlign);
1764 if (EltAlign > MaxAlign)
1765 MaxAlign = EltAlign;
1772 /// Return the desired alignment for ByVal aggregate
1773 /// function arguments in the caller parameter area. For X86, aggregates
1774 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1775 /// are at 4-byte boundaries.
1776 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1777 if (Subtarget->is64Bit()) {
1778 // Max of 8 and alignment of type.
1779 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1786 if (Subtarget->hasSSE1())
1787 getMaxByValAlign(Ty, Align);
1791 /// Returns the target specific optimal type for load
1792 /// and store operations as a result of memset, memcpy, and memmove
1793 /// lowering. If DstAlign is zero that means it's safe to destination
1794 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1795 /// means there isn't a need to check it against alignment requirement,
1796 /// probably because the source does not need to be loaded. If 'IsMemset' is
1797 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1798 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1799 /// source is constant so it does not need to be loaded.
1800 /// It returns EVT::Other if the type should be determined using generic
1801 /// target-independent logic.
1803 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1804 unsigned DstAlign, unsigned SrcAlign,
1805 bool IsMemset, bool ZeroMemset,
1807 MachineFunction &MF) const {
1808 const Function *F = MF.getFunction();
1809 if ((!IsMemset || ZeroMemset) &&
1810 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1812 (Subtarget->isUnalignedMemAccessFast() ||
1813 ((DstAlign == 0 || DstAlign >= 16) &&
1814 (SrcAlign == 0 || SrcAlign >= 16)))) {
1816 if (Subtarget->hasInt256())
1818 if (Subtarget->hasFp256())
1821 if (Subtarget->hasSSE2())
1823 if (Subtarget->hasSSE1())
1825 } else if (!MemcpyStrSrc && Size >= 8 &&
1826 !Subtarget->is64Bit() &&
1827 Subtarget->hasSSE2()) {
1828 // Do not use f64 to lower memcpy if source is string constant. It's
1829 // better to use i32 to avoid the loads.
1833 if (Subtarget->is64Bit() && Size >= 8)
1838 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1840 return X86ScalarSSEf32;
1841 else if (VT == MVT::f64)
1842 return X86ScalarSSEf64;
1847 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1852 *Fast = Subtarget->isUnalignedMemAccessFast();
1856 /// Return the entry encoding for a jump table in the
1857 /// current function. The returned value is a member of the
1858 /// MachineJumpTableInfo::JTEntryKind enum.
1859 unsigned X86TargetLowering::getJumpTableEncoding() const {
1860 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1862 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1863 Subtarget->isPICStyleGOT())
1864 return MachineJumpTableInfo::EK_Custom32;
1866 // Otherwise, use the normal jump table encoding heuristics.
1867 return TargetLowering::getJumpTableEncoding();
1871 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1872 const MachineBasicBlock *MBB,
1873 unsigned uid,MCContext &Ctx) const{
1874 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1875 Subtarget->isPICStyleGOT());
1876 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1878 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1879 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1882 /// Returns relocation base for the given PIC jumptable.
1883 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1884 SelectionDAG &DAG) const {
1885 if (!Subtarget->is64Bit())
1886 // This doesn't have SDLoc associated with it, but is not really the
1887 // same as a Register.
1888 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1892 /// This returns the relocation base for the given PIC jumptable,
1893 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1894 const MCExpr *X86TargetLowering::
1895 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1896 MCContext &Ctx) const {
1897 // X86-64 uses RIP relative addressing based on the jump table label.
1898 if (Subtarget->isPICStyleRIPRel())
1899 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1901 // Otherwise, the reference is relative to the PIC base.
1902 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1905 std::pair<const TargetRegisterClass *, uint8_t>
1906 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1908 const TargetRegisterClass *RRC = nullptr;
1910 switch (VT.SimpleTy) {
1912 return TargetLowering::findRepresentativeClass(TRI, VT);
1913 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1914 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1917 RRC = &X86::VR64RegClass;
1919 case MVT::f32: case MVT::f64:
1920 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1921 case MVT::v4f32: case MVT::v2f64:
1922 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1924 RRC = &X86::VR128RegClass;
1927 return std::make_pair(RRC, Cost);
1930 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1931 unsigned &Offset) const {
1932 if (!Subtarget->isTargetLinux())
1935 if (Subtarget->is64Bit()) {
1936 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1938 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1950 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1951 unsigned DestAS) const {
1952 assert(SrcAS != DestAS && "Expected different address spaces!");
1954 return SrcAS < 256 && DestAS < 256;
1957 //===----------------------------------------------------------------------===//
1958 // Return Value Calling Convention Implementation
1959 //===----------------------------------------------------------------------===//
1961 #include "X86GenCallingConv.inc"
1964 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1965 MachineFunction &MF, bool isVarArg,
1966 const SmallVectorImpl<ISD::OutputArg> &Outs,
1967 LLVMContext &Context) const {
1968 SmallVector<CCValAssign, 16> RVLocs;
1969 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1970 return CCInfo.CheckReturn(Outs, RetCC_X86);
1973 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1974 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1979 X86TargetLowering::LowerReturn(SDValue Chain,
1980 CallingConv::ID CallConv, bool isVarArg,
1981 const SmallVectorImpl<ISD::OutputArg> &Outs,
1982 const SmallVectorImpl<SDValue> &OutVals,
1983 SDLoc dl, SelectionDAG &DAG) const {
1984 MachineFunction &MF = DAG.getMachineFunction();
1985 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1987 SmallVector<CCValAssign, 16> RVLocs;
1988 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1989 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1992 SmallVector<SDValue, 6> RetOps;
1993 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1994 // Operand #1 = Bytes To Pop
1995 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1998 // Copy the result values into the output registers.
1999 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2000 CCValAssign &VA = RVLocs[i];
2001 assert(VA.isRegLoc() && "Can only return in registers!");
2002 SDValue ValToCopy = OutVals[i];
2003 EVT ValVT = ValToCopy.getValueType();
2005 // Promote values to the appropriate types.
2006 if (VA.getLocInfo() == CCValAssign::SExt)
2007 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2008 else if (VA.getLocInfo() == CCValAssign::ZExt)
2009 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2010 else if (VA.getLocInfo() == CCValAssign::AExt)
2011 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2012 else if (VA.getLocInfo() == CCValAssign::BCvt)
2013 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2015 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2016 "Unexpected FP-extend for return value.");
2018 // If this is x86-64, and we disabled SSE, we can't return FP values,
2019 // or SSE or MMX vectors.
2020 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2021 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2022 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2023 report_fatal_error("SSE register return with SSE disabled");
2025 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2026 // llvm-gcc has never done it right and no one has noticed, so this
2027 // should be OK for now.
2028 if (ValVT == MVT::f64 &&
2029 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2030 report_fatal_error("SSE2 register return with SSE2 disabled");
2032 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2033 // the RET instruction and handled by the FP Stackifier.
2034 if (VA.getLocReg() == X86::FP0 ||
2035 VA.getLocReg() == X86::FP1) {
2036 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2037 // change the value to the FP stack register class.
2038 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2039 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2040 RetOps.push_back(ValToCopy);
2041 // Don't emit a copytoreg.
2045 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2046 // which is returned in RAX / RDX.
2047 if (Subtarget->is64Bit()) {
2048 if (ValVT == MVT::x86mmx) {
2049 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2050 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2051 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2053 // If we don't have SSE2 available, convert to v4f32 so the generated
2054 // register is legal.
2055 if (!Subtarget->hasSSE2())
2056 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2061 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2062 Flag = Chain.getValue(1);
2063 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2066 // The x86-64 ABIs require that for returning structs by value we copy
2067 // the sret argument into %rax/%eax (depending on ABI) for the return.
2068 // Win32 requires us to put the sret argument to %eax as well.
2069 // We saved the argument into a virtual register in the entry block,
2070 // so now we copy the value out and into %rax/%eax.
2072 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2073 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2074 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2075 // either case FuncInfo->setSRetReturnReg() will have been called.
2076 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2077 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2078 "No need for an sret register");
2079 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2082 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2083 X86::RAX : X86::EAX;
2084 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2085 Flag = Chain.getValue(1);
2087 // RAX/EAX now acts like a return value.
2088 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2091 RetOps[0] = Chain; // Update chain.
2093 // Add the flag if we have it.
2095 RetOps.push_back(Flag);
2097 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2100 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2101 if (N->getNumValues() != 1)
2103 if (!N->hasNUsesOfValue(1, 0))
2106 SDValue TCChain = Chain;
2107 SDNode *Copy = *N->use_begin();
2108 if (Copy->getOpcode() == ISD::CopyToReg) {
2109 // If the copy has a glue operand, we conservatively assume it isn't safe to
2110 // perform a tail call.
2111 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2113 TCChain = Copy->getOperand(0);
2114 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2117 bool HasRet = false;
2118 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2120 if (UI->getOpcode() != X86ISD::RET_FLAG)
2122 // If we are returning more than one value, we can definitely
2123 // not make a tail call see PR19530
2124 if (UI->getNumOperands() > 4)
2126 if (UI->getNumOperands() == 4 &&
2127 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2140 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2141 ISD::NodeType ExtendKind) const {
2143 // TODO: Is this also valid on 32-bit?
2144 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2145 ReturnMVT = MVT::i8;
2147 ReturnMVT = MVT::i32;
2149 EVT MinVT = getRegisterType(Context, ReturnMVT);
2150 return VT.bitsLT(MinVT) ? MinVT : VT;
2153 /// Lower the result values of a call into the
2154 /// appropriate copies out of appropriate physical registers.
2157 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2158 CallingConv::ID CallConv, bool isVarArg,
2159 const SmallVectorImpl<ISD::InputArg> &Ins,
2160 SDLoc dl, SelectionDAG &DAG,
2161 SmallVectorImpl<SDValue> &InVals) const {
2163 // Assign locations to each value returned by this call.
2164 SmallVector<CCValAssign, 16> RVLocs;
2165 bool Is64Bit = Subtarget->is64Bit();
2166 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2168 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2170 // Copy all of the result registers out of their specified physreg.
2171 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2172 CCValAssign &VA = RVLocs[i];
2173 EVT CopyVT = VA.getValVT();
2175 // If this is x86-64, and we disabled SSE, we can't return FP values
2176 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2177 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2178 report_fatal_error("SSE register return with SSE disabled");
2181 // If we prefer to use the value in xmm registers, copy it out as f80 and
2182 // use a truncate to move it from fp stack reg to xmm reg.
2183 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2184 isScalarFPTypeInSSEReg(VA.getValVT()))
2187 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2188 CopyVT, InFlag).getValue(1);
2189 SDValue Val = Chain.getValue(0);
2191 if (CopyVT != VA.getValVT())
2192 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2193 // This truncation won't change the value.
2194 DAG.getIntPtrConstant(1));
2196 InFlag = Chain.getValue(2);
2197 InVals.push_back(Val);
2203 //===----------------------------------------------------------------------===//
2204 // C & StdCall & Fast Calling Convention implementation
2205 //===----------------------------------------------------------------------===//
2206 // StdCall calling convention seems to be standard for many Windows' API
2207 // routines and around. It differs from C calling convention just a little:
2208 // callee should clean up the stack, not caller. Symbols should be also
2209 // decorated in some fancy way :) It doesn't support any vector arguments.
2210 // For info on fast calling convention see Fast Calling Convention (tail call)
2211 // implementation LowerX86_32FastCCCallTo.
2213 /// CallIsStructReturn - Determines whether a call uses struct return
2215 enum StructReturnType {
2220 static StructReturnType
2221 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2223 return NotStructReturn;
2225 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2226 if (!Flags.isSRet())
2227 return NotStructReturn;
2228 if (Flags.isInReg())
2229 return RegStructReturn;
2230 return StackStructReturn;
2233 /// Determines whether a function uses struct return semantics.
2234 static StructReturnType
2235 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2237 return NotStructReturn;
2239 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2240 if (!Flags.isSRet())
2241 return NotStructReturn;
2242 if (Flags.isInReg())
2243 return RegStructReturn;
2244 return StackStructReturn;
2247 /// Make a copy of an aggregate at address specified by "Src" to address
2248 /// "Dst" with size and alignment information specified by the specific
2249 /// parameter attribute. The copy will be passed as a byval function parameter.
2251 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2252 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2254 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2256 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2257 /*isVolatile*/false, /*AlwaysInline=*/true,
2258 MachinePointerInfo(), MachinePointerInfo());
2261 /// Return true if the calling convention is one that
2262 /// supports tail call optimization.
2263 static bool IsTailCallConvention(CallingConv::ID CC) {
2264 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2265 CC == CallingConv::HiPE);
2268 /// \brief Return true if the calling convention is a C calling convention.
2269 static bool IsCCallConvention(CallingConv::ID CC) {
2270 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2271 CC == CallingConv::X86_64_SysV);
2274 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2275 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2279 CallingConv::ID CalleeCC = CS.getCallingConv();
2280 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2286 /// Return true if the function is being made into
2287 /// a tailcall target by changing its ABI.
2288 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2289 bool GuaranteedTailCallOpt) {
2290 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2294 X86TargetLowering::LowerMemArgument(SDValue Chain,
2295 CallingConv::ID CallConv,
2296 const SmallVectorImpl<ISD::InputArg> &Ins,
2297 SDLoc dl, SelectionDAG &DAG,
2298 const CCValAssign &VA,
2299 MachineFrameInfo *MFI,
2301 // Create the nodes corresponding to a load from this parameter slot.
2302 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2303 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2304 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2305 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2308 // If value is passed by pointer we have address passed instead of the value
2310 if (VA.getLocInfo() == CCValAssign::Indirect)
2311 ValVT = VA.getLocVT();
2313 ValVT = VA.getValVT();
2315 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2316 // changed with more analysis.
2317 // In case of tail call optimization mark all arguments mutable. Since they
2318 // could be overwritten by lowering of arguments in case of a tail call.
2319 if (Flags.isByVal()) {
2320 unsigned Bytes = Flags.getByValSize();
2321 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2322 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2323 return DAG.getFrameIndex(FI, getPointerTy());
2325 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2326 VA.getLocMemOffset(), isImmutable);
2327 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2328 return DAG.getLoad(ValVT, dl, Chain, FIN,
2329 MachinePointerInfo::getFixedStack(FI),
2330 false, false, false, 0);
2334 // FIXME: Get this from tablegen.
2335 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2336 const X86Subtarget *Subtarget) {
2337 assert(Subtarget->is64Bit());
2339 if (Subtarget->isCallingConvWin64(CallConv)) {
2340 static const MCPhysReg GPR64ArgRegsWin64[] = {
2341 X86::RCX, X86::RDX, X86::R8, X86::R9
2343 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2346 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2347 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2349 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2352 // FIXME: Get this from tablegen.
2353 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2354 CallingConv::ID CallConv,
2355 const X86Subtarget *Subtarget) {
2356 assert(Subtarget->is64Bit());
2357 if (Subtarget->isCallingConvWin64(CallConv)) {
2358 // The XMM registers which might contain var arg parameters are shadowed
2359 // in their paired GPR. So we only need to save the GPR to their home
2361 // TODO: __vectorcall will change this.
2365 const Function *Fn = MF.getFunction();
2366 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2367 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2368 "SSE register cannot be used when SSE is disabled!");
2369 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2370 !Subtarget->hasSSE1())
2371 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2375 static const MCPhysReg XMMArgRegs64Bit[] = {
2376 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2377 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2379 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2383 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2384 CallingConv::ID CallConv,
2386 const SmallVectorImpl<ISD::InputArg> &Ins,
2389 SmallVectorImpl<SDValue> &InVals)
2391 MachineFunction &MF = DAG.getMachineFunction();
2392 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2394 const Function* Fn = MF.getFunction();
2395 if (Fn->hasExternalLinkage() &&
2396 Subtarget->isTargetCygMing() &&
2397 Fn->getName() == "main")
2398 FuncInfo->setForceFramePointer(true);
2400 MachineFrameInfo *MFI = MF.getFrameInfo();
2401 bool Is64Bit = Subtarget->is64Bit();
2402 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2404 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2405 "Var args not supported with calling convention fastcc, ghc or hipe");
2407 // Assign locations to all of the incoming arguments.
2408 SmallVector<CCValAssign, 16> ArgLocs;
2409 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2411 // Allocate shadow area for Win64
2413 CCInfo.AllocateStack(32, 8);
2415 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2417 unsigned LastVal = ~0U;
2419 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2420 CCValAssign &VA = ArgLocs[i];
2421 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2423 assert(VA.getValNo() != LastVal &&
2424 "Don't support value assigned to multiple locs yet");
2426 LastVal = VA.getValNo();
2428 if (VA.isRegLoc()) {
2429 EVT RegVT = VA.getLocVT();
2430 const TargetRegisterClass *RC;
2431 if (RegVT == MVT::i32)
2432 RC = &X86::GR32RegClass;
2433 else if (Is64Bit && RegVT == MVT::i64)
2434 RC = &X86::GR64RegClass;
2435 else if (RegVT == MVT::f32)
2436 RC = &X86::FR32RegClass;
2437 else if (RegVT == MVT::f64)
2438 RC = &X86::FR64RegClass;
2439 else if (RegVT.is512BitVector())
2440 RC = &X86::VR512RegClass;
2441 else if (RegVT.is256BitVector())
2442 RC = &X86::VR256RegClass;
2443 else if (RegVT.is128BitVector())
2444 RC = &X86::VR128RegClass;
2445 else if (RegVT == MVT::x86mmx)
2446 RC = &X86::VR64RegClass;
2447 else if (RegVT == MVT::i1)
2448 RC = &X86::VK1RegClass;
2449 else if (RegVT == MVT::v8i1)
2450 RC = &X86::VK8RegClass;
2451 else if (RegVT == MVT::v16i1)
2452 RC = &X86::VK16RegClass;
2453 else if (RegVT == MVT::v32i1)
2454 RC = &X86::VK32RegClass;
2455 else if (RegVT == MVT::v64i1)
2456 RC = &X86::VK64RegClass;
2458 llvm_unreachable("Unknown argument type!");
2460 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2461 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2463 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2464 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2466 if (VA.getLocInfo() == CCValAssign::SExt)
2467 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2468 DAG.getValueType(VA.getValVT()));
2469 else if (VA.getLocInfo() == CCValAssign::ZExt)
2470 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2471 DAG.getValueType(VA.getValVT()));
2472 else if (VA.getLocInfo() == CCValAssign::BCvt)
2473 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2475 if (VA.isExtInLoc()) {
2476 // Handle MMX values passed in XMM regs.
2477 if (RegVT.isVector())
2478 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2480 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2483 assert(VA.isMemLoc());
2484 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2487 // If value is passed via pointer - do a load.
2488 if (VA.getLocInfo() == CCValAssign::Indirect)
2489 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2490 MachinePointerInfo(), false, false, false, 0);
2492 InVals.push_back(ArgValue);
2495 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2497 // The x86-64 ABIs require that for returning structs by value we copy
2498 // the sret argument into %rax/%eax (depending on ABI) for the return.
2499 // Win32 requires us to put the sret argument to %eax as well.
2500 // Save the argument into a virtual register so that we can access it
2501 // from the return points.
2502 if (Ins[i].Flags.isSRet()) {
2503 unsigned Reg = FuncInfo->getSRetReturnReg();
2505 MVT PtrTy = getPointerTy();
2506 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2507 FuncInfo->setSRetReturnReg(Reg);
2509 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2510 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2516 unsigned StackSize = CCInfo.getNextStackOffset();
2517 // Align stack specially for tail calls.
2518 if (FuncIsMadeTailCallSafe(CallConv,
2519 MF.getTarget().Options.GuaranteedTailCallOpt))
2520 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2522 // If the function takes variable number of arguments, make a frame index for
2523 // the start of the first vararg value... for expansion of llvm.va_start. We
2524 // can skip this if there are no va_start calls.
2525 if (MFI->hasVAStart() &&
2526 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2527 CallConv != CallingConv::X86_ThisCall))) {
2528 FuncInfo->setVarArgsFrameIndex(
2529 MFI->CreateFixedObject(1, StackSize, true));
2532 // Figure out if XMM registers are in use.
2533 assert(!(MF.getTarget().Options.UseSoftFloat &&
2534 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2535 "SSE register cannot be used when SSE is disabled!");
2537 // 64-bit calling conventions support varargs and register parameters, so we
2538 // have to do extra work to spill them in the prologue.
2539 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2540 // Find the first unallocated argument registers.
2541 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2542 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2543 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2544 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2545 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2546 "SSE register cannot be used when SSE is disabled!");
2548 // Gather all the live in physical registers.
2549 SmallVector<SDValue, 6> LiveGPRs;
2550 SmallVector<SDValue, 8> LiveXMMRegs;
2552 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2553 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2555 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2557 if (!ArgXMMs.empty()) {
2558 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2559 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2560 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2561 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2562 LiveXMMRegs.push_back(
2563 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2568 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2569 // Get to the caller-allocated home save location. Add 8 to account
2570 // for the return address.
2571 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2572 FuncInfo->setRegSaveFrameIndex(
2573 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2574 // Fixup to set vararg frame on shadow area (4 x i64).
2576 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2578 // For X86-64, if there are vararg parameters that are passed via
2579 // registers, then we must store them to their spots on the stack so
2580 // they may be loaded by deferencing the result of va_next.
2581 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2582 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2583 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2584 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2587 // Store the integer parameter registers.
2588 SmallVector<SDValue, 8> MemOps;
2589 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2591 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2592 for (SDValue Val : LiveGPRs) {
2593 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2594 DAG.getIntPtrConstant(Offset));
2596 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2597 MachinePointerInfo::getFixedStack(
2598 FuncInfo->getRegSaveFrameIndex(), Offset),
2600 MemOps.push_back(Store);
2604 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2605 // Now store the XMM (fp + vector) parameter registers.
2606 SmallVector<SDValue, 12> SaveXMMOps;
2607 SaveXMMOps.push_back(Chain);
2608 SaveXMMOps.push_back(ALVal);
2609 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2610 FuncInfo->getRegSaveFrameIndex()));
2611 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2612 FuncInfo->getVarArgsFPOffset()));
2613 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2615 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2616 MVT::Other, SaveXMMOps));
2619 if (!MemOps.empty())
2620 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2623 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2624 // Find the largest legal vector type.
2625 MVT VecVT = MVT::Other;
2626 // FIXME: Only some x86_32 calling conventions support AVX512.
2627 if (Subtarget->hasAVX512() &&
2628 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2629 CallConv == CallingConv::Intel_OCL_BI)))
2630 VecVT = MVT::v16f32;
2631 else if (Subtarget->hasAVX())
2633 else if (Subtarget->hasSSE2())
2636 // We forward some GPRs and some vector types.
2637 SmallVector<MVT, 2> RegParmTypes;
2638 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2639 RegParmTypes.push_back(IntVT);
2640 if (VecVT != MVT::Other)
2641 RegParmTypes.push_back(VecVT);
2643 // Compute the set of forwarded registers. The rest are scratch.
2644 SmallVectorImpl<ForwardedRegister> &Forwards =
2645 FuncInfo->getForwardedMustTailRegParms();
2646 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2648 // Conservatively forward AL on x86_64, since it might be used for varargs.
2649 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2650 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2651 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2654 // Copy all forwards from physical to virtual registers.
2655 for (ForwardedRegister &F : Forwards) {
2656 // FIXME: Can we use a less constrained schedule?
2657 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2658 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2659 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2663 // Some CCs need callee pop.
2664 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2665 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2666 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2668 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2669 // If this is an sret function, the return should pop the hidden pointer.
2670 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2671 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2672 argsAreStructReturn(Ins) == StackStructReturn)
2673 FuncInfo->setBytesToPopOnReturn(4);
2677 // RegSaveFrameIndex is X86-64 only.
2678 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2679 if (CallConv == CallingConv::X86_FastCall ||
2680 CallConv == CallingConv::X86_ThisCall)
2681 // fastcc functions can't have varargs.
2682 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2685 FuncInfo->setArgumentStackSize(StackSize);
2691 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2692 SDValue StackPtr, SDValue Arg,
2693 SDLoc dl, SelectionDAG &DAG,
2694 const CCValAssign &VA,
2695 ISD::ArgFlagsTy Flags) const {
2696 unsigned LocMemOffset = VA.getLocMemOffset();
2697 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2698 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2699 if (Flags.isByVal())
2700 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2702 return DAG.getStore(Chain, dl, Arg, PtrOff,
2703 MachinePointerInfo::getStack(LocMemOffset),
2707 /// Emit a load of return address if tail call
2708 /// optimization is performed and it is required.
2710 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2711 SDValue &OutRetAddr, SDValue Chain,
2712 bool IsTailCall, bool Is64Bit,
2713 int FPDiff, SDLoc dl) const {
2714 // Adjust the Return address stack slot.
2715 EVT VT = getPointerTy();
2716 OutRetAddr = getReturnAddressFrameIndex(DAG);
2718 // Load the "old" Return address.
2719 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2720 false, false, false, 0);
2721 return SDValue(OutRetAddr.getNode(), 1);
2724 /// Emit a store of the return address if tail call
2725 /// optimization is performed and it is required (FPDiff!=0).
2726 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2727 SDValue Chain, SDValue RetAddrFrIdx,
2728 EVT PtrVT, unsigned SlotSize,
2729 int FPDiff, SDLoc dl) {
2730 // Store the return address to the appropriate stack slot.
2731 if (!FPDiff) return Chain;
2732 // Calculate the new stack slot for the return address.
2733 int NewReturnAddrFI =
2734 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2736 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2737 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2738 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2744 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2745 SmallVectorImpl<SDValue> &InVals) const {
2746 SelectionDAG &DAG = CLI.DAG;
2748 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2749 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2750 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2751 SDValue Chain = CLI.Chain;
2752 SDValue Callee = CLI.Callee;
2753 CallingConv::ID CallConv = CLI.CallConv;
2754 bool &isTailCall = CLI.IsTailCall;
2755 bool isVarArg = CLI.IsVarArg;
2757 MachineFunction &MF = DAG.getMachineFunction();
2758 bool Is64Bit = Subtarget->is64Bit();
2759 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2760 StructReturnType SR = callIsStructReturn(Outs);
2761 bool IsSibcall = false;
2762 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2764 if (MF.getTarget().Options.DisableTailCalls)
2767 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2769 // Force this to be a tail call. The verifier rules are enough to ensure
2770 // that we can lower this successfully without moving the return address
2773 } else if (isTailCall) {
2774 // Check if it's really possible to do a tail call.
2775 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2776 isVarArg, SR != NotStructReturn,
2777 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2778 Outs, OutVals, Ins, DAG);
2780 // Sibcalls are automatically detected tailcalls which do not require
2782 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2789 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2790 "Var args not supported with calling convention fastcc, ghc or hipe");
2792 // Analyze operands of the call, assigning locations to each operand.
2793 SmallVector<CCValAssign, 16> ArgLocs;
2794 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2796 // Allocate shadow area for Win64
2798 CCInfo.AllocateStack(32, 8);
2800 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2802 // Get a count of how many bytes are to be pushed on the stack.
2803 unsigned NumBytes = CCInfo.getNextStackOffset();
2805 // This is a sibcall. The memory operands are available in caller's
2806 // own caller's stack.
2808 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2809 IsTailCallConvention(CallConv))
2810 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2813 if (isTailCall && !IsSibcall && !IsMustTail) {
2814 // Lower arguments at fp - stackoffset + fpdiff.
2815 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2817 FPDiff = NumBytesCallerPushed - NumBytes;
2819 // Set the delta of movement of the returnaddr stackslot.
2820 // But only set if delta is greater than previous delta.
2821 if (FPDiff < X86Info->getTCReturnAddrDelta())
2822 X86Info->setTCReturnAddrDelta(FPDiff);
2825 unsigned NumBytesToPush = NumBytes;
2826 unsigned NumBytesToPop = NumBytes;
2828 // If we have an inalloca argument, all stack space has already been allocated
2829 // for us and be right at the top of the stack. We don't support multiple
2830 // arguments passed in memory when using inalloca.
2831 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2833 if (!ArgLocs.back().isMemLoc())
2834 report_fatal_error("cannot use inalloca attribute on a register "
2836 if (ArgLocs.back().getLocMemOffset() != 0)
2837 report_fatal_error("any parameter with the inalloca attribute must be "
2838 "the only memory argument");
2842 Chain = DAG.getCALLSEQ_START(
2843 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2845 SDValue RetAddrFrIdx;
2846 // Load return address for tail calls.
2847 if (isTailCall && FPDiff)
2848 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2849 Is64Bit, FPDiff, dl);
2851 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2852 SmallVector<SDValue, 8> MemOpChains;
2855 // Walk the register/memloc assignments, inserting copies/loads. In the case
2856 // of tail call optimization arguments are handle later.
2857 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2858 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2859 // Skip inalloca arguments, they have already been written.
2860 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2861 if (Flags.isInAlloca())
2864 CCValAssign &VA = ArgLocs[i];
2865 EVT RegVT = VA.getLocVT();
2866 SDValue Arg = OutVals[i];
2867 bool isByVal = Flags.isByVal();
2869 // Promote the value if needed.
2870 switch (VA.getLocInfo()) {
2871 default: llvm_unreachable("Unknown loc info!");
2872 case CCValAssign::Full: break;
2873 case CCValAssign::SExt:
2874 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2876 case CCValAssign::ZExt:
2877 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2879 case CCValAssign::AExt:
2880 if (RegVT.is128BitVector()) {
2881 // Special case: passing MMX values in XMM registers.
2882 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2883 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2884 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2886 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2888 case CCValAssign::BCvt:
2889 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2891 case CCValAssign::Indirect: {
2892 // Store the argument.
2893 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2894 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2895 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2896 MachinePointerInfo::getFixedStack(FI),
2903 if (VA.isRegLoc()) {
2904 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2905 if (isVarArg && IsWin64) {
2906 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2907 // shadow reg if callee is a varargs function.
2908 unsigned ShadowReg = 0;
2909 switch (VA.getLocReg()) {
2910 case X86::XMM0: ShadowReg = X86::RCX; break;
2911 case X86::XMM1: ShadowReg = X86::RDX; break;
2912 case X86::XMM2: ShadowReg = X86::R8; break;
2913 case X86::XMM3: ShadowReg = X86::R9; break;
2916 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2918 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2919 assert(VA.isMemLoc());
2920 if (!StackPtr.getNode())
2921 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2923 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2924 dl, DAG, VA, Flags));
2928 if (!MemOpChains.empty())
2929 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2931 if (Subtarget->isPICStyleGOT()) {
2932 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2935 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2936 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2938 // If we are tail calling and generating PIC/GOT style code load the
2939 // address of the callee into ECX. The value in ecx is used as target of
2940 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2941 // for tail calls on PIC/GOT architectures. Normally we would just put the
2942 // address of GOT into ebx and then call target@PLT. But for tail calls
2943 // ebx would be restored (since ebx is callee saved) before jumping to the
2946 // Note: The actual moving to ECX is done further down.
2947 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2948 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2949 !G->getGlobal()->hasProtectedVisibility())
2950 Callee = LowerGlobalAddress(Callee, DAG);
2951 else if (isa<ExternalSymbolSDNode>(Callee))
2952 Callee = LowerExternalSymbol(Callee, DAG);
2956 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2957 // From AMD64 ABI document:
2958 // For calls that may call functions that use varargs or stdargs
2959 // (prototype-less calls or calls to functions containing ellipsis (...) in
2960 // the declaration) %al is used as hidden argument to specify the number
2961 // of SSE registers used. The contents of %al do not need to match exactly
2962 // the number of registers, but must be an ubound on the number of SSE
2963 // registers used and is in the range 0 - 8 inclusive.
2965 // Count the number of XMM registers allocated.
2966 static const MCPhysReg XMMArgRegs[] = {
2967 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2968 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2970 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2971 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2972 && "SSE registers cannot be used when SSE is disabled");
2974 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2975 DAG.getConstant(NumXMMRegs, MVT::i8)));
2978 if (isVarArg && IsMustTail) {
2979 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2980 for (const auto &F : Forwards) {
2981 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2982 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2986 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2987 // don't need this because the eligibility check rejects calls that require
2988 // shuffling arguments passed in memory.
2989 if (!IsSibcall && isTailCall) {
2990 // Force all the incoming stack arguments to be loaded from the stack
2991 // before any new outgoing arguments are stored to the stack, because the
2992 // outgoing stack slots may alias the incoming argument stack slots, and
2993 // the alias isn't otherwise explicit. This is slightly more conservative
2994 // than necessary, because it means that each store effectively depends
2995 // on every argument instead of just those arguments it would clobber.
2996 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2998 SmallVector<SDValue, 8> MemOpChains2;
3001 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3002 CCValAssign &VA = ArgLocs[i];
3005 assert(VA.isMemLoc());
3006 SDValue Arg = OutVals[i];
3007 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3008 // Skip inalloca arguments. They don't require any work.
3009 if (Flags.isInAlloca())
3011 // Create frame index.
3012 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3013 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3014 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3015 FIN = DAG.getFrameIndex(FI, getPointerTy());
3017 if (Flags.isByVal()) {
3018 // Copy relative to framepointer.
3019 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3020 if (!StackPtr.getNode())
3021 StackPtr = DAG.getCopyFromReg(Chain, dl,
3022 RegInfo->getStackRegister(),
3024 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3026 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3030 // Store relative to framepointer.
3031 MemOpChains2.push_back(
3032 DAG.getStore(ArgChain, dl, Arg, FIN,
3033 MachinePointerInfo::getFixedStack(FI),
3038 if (!MemOpChains2.empty())
3039 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3041 // Store the return address to the appropriate stack slot.
3042 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3043 getPointerTy(), RegInfo->getSlotSize(),
3047 // Build a sequence of copy-to-reg nodes chained together with token chain
3048 // and flag operands which copy the outgoing args into registers.
3050 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3051 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3052 RegsToPass[i].second, InFlag);
3053 InFlag = Chain.getValue(1);
3056 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3057 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3058 // In the 64-bit large code model, we have to make all calls
3059 // through a register, since the call instruction's 32-bit
3060 // pc-relative offset may not be large enough to hold the whole
3062 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3063 // If the callee is a GlobalAddress node (quite common, every direct call
3064 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3066 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3068 // We should use extra load for direct calls to dllimported functions in
3070 const GlobalValue *GV = G->getGlobal();
3071 if (!GV->hasDLLImportStorageClass()) {
3072 unsigned char OpFlags = 0;
3073 bool ExtraLoad = false;
3074 unsigned WrapperKind = ISD::DELETED_NODE;
3076 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3077 // external symbols most go through the PLT in PIC mode. If the symbol
3078 // has hidden or protected visibility, or if it is static or local, then
3079 // we don't need to use the PLT - we can directly call it.
3080 if (Subtarget->isTargetELF() &&
3081 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3082 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3083 OpFlags = X86II::MO_PLT;
3084 } else if (Subtarget->isPICStyleStubAny() &&
3085 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3086 (!Subtarget->getTargetTriple().isMacOSX() ||
3087 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3088 // PC-relative references to external symbols should go through $stub,
3089 // unless we're building with the leopard linker or later, which
3090 // automatically synthesizes these stubs.
3091 OpFlags = X86II::MO_DARWIN_STUB;
3092 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3093 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3094 // If the function is marked as non-lazy, generate an indirect call
3095 // which loads from the GOT directly. This avoids runtime overhead
3096 // at the cost of eager binding (and one extra byte of encoding).
3097 OpFlags = X86II::MO_GOTPCREL;
3098 WrapperKind = X86ISD::WrapperRIP;
3102 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3103 G->getOffset(), OpFlags);
3105 // Add a wrapper if needed.
3106 if (WrapperKind != ISD::DELETED_NODE)
3107 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3108 // Add extra indirection if needed.
3110 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3111 MachinePointerInfo::getGOT(),
3112 false, false, false, 0);
3114 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3115 unsigned char OpFlags = 0;
3117 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3118 // external symbols should go through the PLT.
3119 if (Subtarget->isTargetELF() &&
3120 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3121 OpFlags = X86II::MO_PLT;
3122 } else if (Subtarget->isPICStyleStubAny() &&
3123 (!Subtarget->getTargetTriple().isMacOSX() ||
3124 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3125 // PC-relative references to external symbols should go through $stub,
3126 // unless we're building with the leopard linker or later, which
3127 // automatically synthesizes these stubs.
3128 OpFlags = X86II::MO_DARWIN_STUB;
3131 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3133 } else if (Subtarget->isTarget64BitILP32() &&
3134 Callee->getValueType(0) == MVT::i32) {
3135 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3136 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3139 // Returns a chain & a flag for retval copy to use.
3140 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3141 SmallVector<SDValue, 8> Ops;
3143 if (!IsSibcall && isTailCall) {
3144 Chain = DAG.getCALLSEQ_END(Chain,
3145 DAG.getIntPtrConstant(NumBytesToPop, true),
3146 DAG.getIntPtrConstant(0, true), InFlag, dl);
3147 InFlag = Chain.getValue(1);
3150 Ops.push_back(Chain);
3151 Ops.push_back(Callee);
3154 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3156 // Add argument registers to the end of the list so that they are known live
3158 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3159 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3160 RegsToPass[i].second.getValueType()));
3162 // Add a register mask operand representing the call-preserved registers.
3163 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3164 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3165 assert(Mask && "Missing call preserved mask for calling convention");
3166 Ops.push_back(DAG.getRegisterMask(Mask));
3168 if (InFlag.getNode())
3169 Ops.push_back(InFlag);
3173 //// If this is the first return lowered for this function, add the regs
3174 //// to the liveout set for the function.
3175 // This isn't right, although it's probably harmless on x86; liveouts
3176 // should be computed from returns not tail calls. Consider a void
3177 // function making a tail call to a function returning int.
3178 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3181 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3182 InFlag = Chain.getValue(1);
3184 // Create the CALLSEQ_END node.
3185 unsigned NumBytesForCalleeToPop;
3186 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3187 DAG.getTarget().Options.GuaranteedTailCallOpt))
3188 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3189 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3190 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3191 SR == StackStructReturn)
3192 // If this is a call to a struct-return function, the callee
3193 // pops the hidden struct pointer, so we have to push it back.
3194 // This is common for Darwin/X86, Linux & Mingw32 targets.
3195 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3196 NumBytesForCalleeToPop = 4;
3198 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3200 // Returns a flag for retval copy to use.
3202 Chain = DAG.getCALLSEQ_END(Chain,
3203 DAG.getIntPtrConstant(NumBytesToPop, true),
3204 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3207 InFlag = Chain.getValue(1);
3210 // Handle result values, copying them out of physregs into vregs that we
3212 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3213 Ins, dl, DAG, InVals);
3216 //===----------------------------------------------------------------------===//
3217 // Fast Calling Convention (tail call) implementation
3218 //===----------------------------------------------------------------------===//
3220 // Like std call, callee cleans arguments, convention except that ECX is
3221 // reserved for storing the tail called function address. Only 2 registers are
3222 // free for argument passing (inreg). Tail call optimization is performed
3224 // * tailcallopt is enabled
3225 // * caller/callee are fastcc
3226 // On X86_64 architecture with GOT-style position independent code only local
3227 // (within module) calls are supported at the moment.
3228 // To keep the stack aligned according to platform abi the function
3229 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3230 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3231 // If a tail called function callee has more arguments than the caller the
3232 // caller needs to make sure that there is room to move the RETADDR to. This is
3233 // achieved by reserving an area the size of the argument delta right after the
3234 // original RETADDR, but before the saved framepointer or the spilled registers
3235 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3247 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3248 /// for a 16 byte align requirement.
3250 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3251 SelectionDAG& DAG) const {
3252 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3253 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3254 unsigned StackAlignment = TFI.getStackAlignment();
3255 uint64_t AlignMask = StackAlignment - 1;
3256 int64_t Offset = StackSize;
3257 unsigned SlotSize = RegInfo->getSlotSize();
3258 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3259 // Number smaller than 12 so just add the difference.
3260 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3262 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3263 Offset = ((~AlignMask) & Offset) + StackAlignment +
3264 (StackAlignment-SlotSize);
3269 /// MatchingStackOffset - Return true if the given stack call argument is
3270 /// already available in the same position (relatively) of the caller's
3271 /// incoming argument stack.
3273 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3274 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3275 const X86InstrInfo *TII) {
3276 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3278 if (Arg.getOpcode() == ISD::CopyFromReg) {
3279 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3280 if (!TargetRegisterInfo::isVirtualRegister(VR))
3282 MachineInstr *Def = MRI->getVRegDef(VR);
3285 if (!Flags.isByVal()) {
3286 if (!TII->isLoadFromStackSlot(Def, FI))
3289 unsigned Opcode = Def->getOpcode();
3290 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3291 Opcode == X86::LEA64_32r) &&
3292 Def->getOperand(1).isFI()) {
3293 FI = Def->getOperand(1).getIndex();
3294 Bytes = Flags.getByValSize();
3298 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3299 if (Flags.isByVal())
3300 // ByVal argument is passed in as a pointer but it's now being
3301 // dereferenced. e.g.
3302 // define @foo(%struct.X* %A) {
3303 // tail call @bar(%struct.X* byval %A)
3306 SDValue Ptr = Ld->getBasePtr();
3307 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3310 FI = FINode->getIndex();
3311 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3312 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3313 FI = FINode->getIndex();
3314 Bytes = Flags.getByValSize();
3318 assert(FI != INT_MAX);
3319 if (!MFI->isFixedObjectIndex(FI))
3321 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3324 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3325 /// for tail call optimization. Targets which want to do tail call
3326 /// optimization should implement this function.
3328 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3329 CallingConv::ID CalleeCC,
3331 bool isCalleeStructRet,
3332 bool isCallerStructRet,
3334 const SmallVectorImpl<ISD::OutputArg> &Outs,
3335 const SmallVectorImpl<SDValue> &OutVals,
3336 const SmallVectorImpl<ISD::InputArg> &Ins,
3337 SelectionDAG &DAG) const {
3338 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3341 // If -tailcallopt is specified, make fastcc functions tail-callable.
3342 const MachineFunction &MF = DAG.getMachineFunction();
3343 const Function *CallerF = MF.getFunction();
3345 // If the function return type is x86_fp80 and the callee return type is not,
3346 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3347 // perform a tailcall optimization here.
3348 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3351 CallingConv::ID CallerCC = CallerF->getCallingConv();
3352 bool CCMatch = CallerCC == CalleeCC;
3353 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3354 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3356 // Win64 functions have extra shadow space for argument homing. Don't do the
3357 // sibcall if the caller and callee have mismatched expectations for this
3359 if (IsCalleeWin64 != IsCallerWin64)
3362 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3363 if (IsTailCallConvention(CalleeCC) && CCMatch)
3368 // Look for obvious safe cases to perform tail call optimization that do not
3369 // require ABI changes. This is what gcc calls sibcall.
3371 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3372 // emit a special epilogue.
3373 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3374 if (RegInfo->needsStackRealignment(MF))
3377 // Also avoid sibcall optimization if either caller or callee uses struct
3378 // return semantics.
3379 if (isCalleeStructRet || isCallerStructRet)
3382 // An stdcall/thiscall caller is expected to clean up its arguments; the
3383 // callee isn't going to do that.
3384 // FIXME: this is more restrictive than needed. We could produce a tailcall
3385 // when the stack adjustment matches. For example, with a thiscall that takes
3386 // only one argument.
3387 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3388 CallerCC == CallingConv::X86_ThisCall))
3391 // Do not sibcall optimize vararg calls unless all arguments are passed via
3393 if (isVarArg && !Outs.empty()) {
3395 // Optimizing for varargs on Win64 is unlikely to be safe without
3396 // additional testing.
3397 if (IsCalleeWin64 || IsCallerWin64)
3400 SmallVector<CCValAssign, 16> ArgLocs;
3401 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3404 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3405 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3406 if (!ArgLocs[i].isRegLoc())
3410 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3411 // stack. Therefore, if it's not used by the call it is not safe to optimize
3412 // this into a sibcall.
3413 bool Unused = false;
3414 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3421 SmallVector<CCValAssign, 16> RVLocs;
3422 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3424 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3425 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3426 CCValAssign &VA = RVLocs[i];
3427 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3432 // If the calling conventions do not match, then we'd better make sure the
3433 // results are returned in the same way as what the caller expects.
3435 SmallVector<CCValAssign, 16> RVLocs1;
3436 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3438 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3440 SmallVector<CCValAssign, 16> RVLocs2;
3441 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3443 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3445 if (RVLocs1.size() != RVLocs2.size())
3447 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3448 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3450 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3452 if (RVLocs1[i].isRegLoc()) {
3453 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3456 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3462 // If the callee takes no arguments then go on to check the results of the
3464 if (!Outs.empty()) {
3465 // Check if stack adjustment is needed. For now, do not do this if any
3466 // argument is passed on the stack.
3467 SmallVector<CCValAssign, 16> ArgLocs;
3468 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3471 // Allocate shadow area for Win64
3473 CCInfo.AllocateStack(32, 8);
3475 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3476 if (CCInfo.getNextStackOffset()) {
3477 MachineFunction &MF = DAG.getMachineFunction();
3478 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3481 // Check if the arguments are already laid out in the right way as
3482 // the caller's fixed stack objects.
3483 MachineFrameInfo *MFI = MF.getFrameInfo();
3484 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3485 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3486 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3487 CCValAssign &VA = ArgLocs[i];
3488 SDValue Arg = OutVals[i];
3489 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3490 if (VA.getLocInfo() == CCValAssign::Indirect)
3492 if (!VA.isRegLoc()) {
3493 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3500 // If the tailcall address may be in a register, then make sure it's
3501 // possible to register allocate for it. In 32-bit, the call address can
3502 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3503 // callee-saved registers are restored. These happen to be the same
3504 // registers used to pass 'inreg' arguments so watch out for those.
3505 if (!Subtarget->is64Bit() &&
3506 ((!isa<GlobalAddressSDNode>(Callee) &&
3507 !isa<ExternalSymbolSDNode>(Callee)) ||
3508 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3509 unsigned NumInRegs = 0;
3510 // In PIC we need an extra register to formulate the address computation
3512 unsigned MaxInRegs =
3513 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3515 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3516 CCValAssign &VA = ArgLocs[i];
3519 unsigned Reg = VA.getLocReg();
3522 case X86::EAX: case X86::EDX: case X86::ECX:
3523 if (++NumInRegs == MaxInRegs)
3535 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3536 const TargetLibraryInfo *libInfo) const {
3537 return X86::createFastISel(funcInfo, libInfo);
3540 //===----------------------------------------------------------------------===//
3541 // Other Lowering Hooks
3542 //===----------------------------------------------------------------------===//
3544 static bool MayFoldLoad(SDValue Op) {
3545 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3548 static bool MayFoldIntoStore(SDValue Op) {
3549 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3552 static bool isTargetShuffle(unsigned Opcode) {
3554 default: return false;
3555 case X86ISD::BLENDI:
3556 case X86ISD::PSHUFB:
3557 case X86ISD::PSHUFD:
3558 case X86ISD::PSHUFHW:
3559 case X86ISD::PSHUFLW:
3561 case X86ISD::PALIGNR:
3562 case X86ISD::MOVLHPS:
3563 case X86ISD::MOVLHPD:
3564 case X86ISD::MOVHLPS:
3565 case X86ISD::MOVLPS:
3566 case X86ISD::MOVLPD:
3567 case X86ISD::MOVSHDUP:
3568 case X86ISD::MOVSLDUP:
3569 case X86ISD::MOVDDUP:
3572 case X86ISD::UNPCKL:
3573 case X86ISD::UNPCKH:
3574 case X86ISD::VPERMILPI:
3575 case X86ISD::VPERM2X128:
3576 case X86ISD::VPERMI:
3581 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3582 SDValue V1, unsigned TargetMask,
3583 SelectionDAG &DAG) {
3585 default: llvm_unreachable("Unknown x86 shuffle node");
3586 case X86ISD::PSHUFD:
3587 case X86ISD::PSHUFHW:
3588 case X86ISD::PSHUFLW:
3589 case X86ISD::VPERMILPI:
3590 case X86ISD::VPERMI:
3591 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3595 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3596 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3598 default: llvm_unreachable("Unknown x86 shuffle node");
3599 case X86ISD::MOVLHPS:
3600 case X86ISD::MOVLHPD:
3601 case X86ISD::MOVHLPS:
3602 case X86ISD::MOVLPS:
3603 case X86ISD::MOVLPD:
3606 case X86ISD::UNPCKL:
3607 case X86ISD::UNPCKH:
3608 return DAG.getNode(Opc, dl, VT, V1, V2);
3612 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3613 MachineFunction &MF = DAG.getMachineFunction();
3614 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3615 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3616 int ReturnAddrIndex = FuncInfo->getRAIndex();
3618 if (ReturnAddrIndex == 0) {
3619 // Set up a frame object for the return address.
3620 unsigned SlotSize = RegInfo->getSlotSize();
3621 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3624 FuncInfo->setRAIndex(ReturnAddrIndex);
3627 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3630 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3631 bool hasSymbolicDisplacement) {
3632 // Offset should fit into 32 bit immediate field.
3633 if (!isInt<32>(Offset))
3636 // If we don't have a symbolic displacement - we don't have any extra
3638 if (!hasSymbolicDisplacement)
3641 // FIXME: Some tweaks might be needed for medium code model.
3642 if (M != CodeModel::Small && M != CodeModel::Kernel)
3645 // For small code model we assume that latest object is 16MB before end of 31
3646 // bits boundary. We may also accept pretty large negative constants knowing
3647 // that all objects are in the positive half of address space.
3648 if (M == CodeModel::Small && Offset < 16*1024*1024)
3651 // For kernel code model we know that all object resist in the negative half
3652 // of 32bits address space. We may not accept negative offsets, since they may
3653 // be just off and we may accept pretty large positive ones.
3654 if (M == CodeModel::Kernel && Offset >= 0)
3660 /// isCalleePop - Determines whether the callee is required to pop its
3661 /// own arguments. Callee pop is necessary to support tail calls.
3662 bool X86::isCalleePop(CallingConv::ID CallingConv,
3663 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3664 switch (CallingConv) {
3667 case CallingConv::X86_StdCall:
3668 case CallingConv::X86_FastCall:
3669 case CallingConv::X86_ThisCall:
3671 case CallingConv::Fast:
3672 case CallingConv::GHC:
3673 case CallingConv::HiPE:
3680 /// \brief Return true if the condition is an unsigned comparison operation.
3681 static bool isX86CCUnsigned(unsigned X86CC) {
3683 default: llvm_unreachable("Invalid integer condition!");
3684 case X86::COND_E: return true;
3685 case X86::COND_G: return false;
3686 case X86::COND_GE: return false;
3687 case X86::COND_L: return false;
3688 case X86::COND_LE: return false;
3689 case X86::COND_NE: return true;
3690 case X86::COND_B: return true;
3691 case X86::COND_A: return true;
3692 case X86::COND_BE: return true;
3693 case X86::COND_AE: return true;
3695 llvm_unreachable("covered switch fell through?!");
3698 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3699 /// specific condition code, returning the condition code and the LHS/RHS of the
3700 /// comparison to make.
3701 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3702 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3704 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3705 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3706 // X > -1 -> X == 0, jump !sign.
3707 RHS = DAG.getConstant(0, RHS.getValueType());
3708 return X86::COND_NS;
3710 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3711 // X < 0 -> X == 0, jump on sign.
3714 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3716 RHS = DAG.getConstant(0, RHS.getValueType());
3717 return X86::COND_LE;
3721 switch (SetCCOpcode) {
3722 default: llvm_unreachable("Invalid integer condition!");
3723 case ISD::SETEQ: return X86::COND_E;
3724 case ISD::SETGT: return X86::COND_G;
3725 case ISD::SETGE: return X86::COND_GE;
3726 case ISD::SETLT: return X86::COND_L;
3727 case ISD::SETLE: return X86::COND_LE;
3728 case ISD::SETNE: return X86::COND_NE;
3729 case ISD::SETULT: return X86::COND_B;
3730 case ISD::SETUGT: return X86::COND_A;
3731 case ISD::SETULE: return X86::COND_BE;
3732 case ISD::SETUGE: return X86::COND_AE;
3736 // First determine if it is required or is profitable to flip the operands.
3738 // If LHS is a foldable load, but RHS is not, flip the condition.
3739 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3740 !ISD::isNON_EXTLoad(RHS.getNode())) {
3741 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3742 std::swap(LHS, RHS);
3745 switch (SetCCOpcode) {
3751 std::swap(LHS, RHS);
3755 // On a floating point condition, the flags are set as follows:
3757 // 0 | 0 | 0 | X > Y
3758 // 0 | 0 | 1 | X < Y
3759 // 1 | 0 | 0 | X == Y
3760 // 1 | 1 | 1 | unordered
3761 switch (SetCCOpcode) {
3762 default: llvm_unreachable("Condcode should be pre-legalized away");
3764 case ISD::SETEQ: return X86::COND_E;
3765 case ISD::SETOLT: // flipped
3767 case ISD::SETGT: return X86::COND_A;
3768 case ISD::SETOLE: // flipped
3770 case ISD::SETGE: return X86::COND_AE;
3771 case ISD::SETUGT: // flipped
3773 case ISD::SETLT: return X86::COND_B;
3774 case ISD::SETUGE: // flipped
3776 case ISD::SETLE: return X86::COND_BE;
3778 case ISD::SETNE: return X86::COND_NE;
3779 case ISD::SETUO: return X86::COND_P;
3780 case ISD::SETO: return X86::COND_NP;
3782 case ISD::SETUNE: return X86::COND_INVALID;
3786 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3787 /// code. Current x86 isa includes the following FP cmov instructions:
3788 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3789 static bool hasFPCMov(unsigned X86CC) {
3805 /// isFPImmLegal - Returns true if the target can instruction select the
3806 /// specified FP immediate natively. If false, the legalizer will
3807 /// materialize the FP immediate as a load from a constant pool.
3808 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3809 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3810 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3816 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3817 ISD::LoadExtType ExtTy,
3819 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3820 // relocation target a movq or addq instruction: don't let the load shrink.
3821 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3822 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3823 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3824 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3828 /// \brief Returns true if it is beneficial to convert a load of a constant
3829 /// to just the constant itself.
3830 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3832 assert(Ty->isIntegerTy());
3834 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3835 if (BitSize == 0 || BitSize > 64)
3840 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3841 unsigned Index) const {
3842 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3845 return (Index == 0 || Index == ResVT.getVectorNumElements());
3848 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3849 // Speculate cttz only if we can directly use TZCNT.
3850 return Subtarget->hasBMI();
3853 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3854 // Speculate ctlz only if we can directly use LZCNT.
3855 return Subtarget->hasLZCNT();
3858 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3859 /// the specified range (L, H].
3860 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3861 return (Val < 0) || (Val >= Low && Val < Hi);
3864 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3865 /// specified value.
3866 static bool isUndefOrEqual(int Val, int CmpVal) {
3867 return (Val < 0 || Val == CmpVal);
3870 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3871 /// from position Pos and ending in Pos+Size, falls within the specified
3872 /// sequential range (Low, Low+Size]. or is undef.
3873 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3874 unsigned Pos, unsigned Size, int Low) {
3875 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3876 if (!isUndefOrEqual(Mask[i], Low))
3881 /// isVEXTRACTIndex - Return true if the specified
3882 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3883 /// suitable for instruction that extract 128 or 256 bit vectors
3884 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3885 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3886 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3889 // The index should be aligned on a vecWidth-bit boundary.
3891 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3893 MVT VT = N->getSimpleValueType(0);
3894 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3895 bool Result = (Index * ElSize) % vecWidth == 0;
3900 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3901 /// operand specifies a subvector insert that is suitable for input to
3902 /// insertion of 128 or 256-bit subvectors
3903 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3904 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3905 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3907 // The index should be aligned on a vecWidth-bit boundary.
3909 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3911 MVT VT = N->getSimpleValueType(0);
3912 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3913 bool Result = (Index * ElSize) % vecWidth == 0;
3918 bool X86::isVINSERT128Index(SDNode *N) {
3919 return isVINSERTIndex(N, 128);
3922 bool X86::isVINSERT256Index(SDNode *N) {
3923 return isVINSERTIndex(N, 256);
3926 bool X86::isVEXTRACT128Index(SDNode *N) {
3927 return isVEXTRACTIndex(N, 128);
3930 bool X86::isVEXTRACT256Index(SDNode *N) {
3931 return isVEXTRACTIndex(N, 256);
3934 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3935 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3936 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3937 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3940 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3942 MVT VecVT = N->getOperand(0).getSimpleValueType();
3943 MVT ElVT = VecVT.getVectorElementType();
3945 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3946 return Index / NumElemsPerChunk;
3949 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3950 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3951 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3952 llvm_unreachable("Illegal insert subvector for VINSERT");
3955 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3957 MVT VecVT = N->getSimpleValueType(0);
3958 MVT ElVT = VecVT.getVectorElementType();
3960 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3961 return Index / NumElemsPerChunk;
3964 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3965 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3966 /// and VINSERTI128 instructions.
3967 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3968 return getExtractVEXTRACTImmediate(N, 128);
3971 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3972 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3973 /// and VINSERTI64x4 instructions.
3974 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3975 return getExtractVEXTRACTImmediate(N, 256);
3978 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3979 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3980 /// and VINSERTI128 instructions.
3981 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3982 return getInsertVINSERTImmediate(N, 128);
3985 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3986 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3987 /// and VINSERTI64x4 instructions.
3988 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3989 return getInsertVINSERTImmediate(N, 256);
3992 /// isZero - Returns true if Elt is a constant integer zero
3993 static bool isZero(SDValue V) {
3994 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3995 return C && C->isNullValue();
3998 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4000 bool X86::isZeroNode(SDValue Elt) {
4003 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4004 return CFP->getValueAPF().isPosZero();
4008 /// getZeroVector - Returns a vector of specified type with all zero elements.
4010 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4011 SelectionDAG &DAG, SDLoc dl) {
4012 assert(VT.isVector() && "Expected a vector type");
4014 // Always build SSE zero vectors as <4 x i32> bitcasted
4015 // to their dest type. This ensures they get CSE'd.
4017 if (VT.is128BitVector()) { // SSE
4018 if (Subtarget->hasSSE2()) { // SSE2
4019 SDValue Cst = DAG.getConstant(0, MVT::i32);
4020 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4022 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4023 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4025 } else if (VT.is256BitVector()) { // AVX
4026 if (Subtarget->hasInt256()) { // AVX2
4027 SDValue Cst = DAG.getConstant(0, MVT::i32);
4028 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4029 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4031 // 256-bit logic and arithmetic instructions in AVX are all
4032 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4033 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4034 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4035 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4037 } else if (VT.is512BitVector()) { // AVX-512
4038 SDValue Cst = DAG.getConstant(0, MVT::i32);
4039 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4040 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4041 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4042 } else if (VT.getScalarType() == MVT::i1) {
4044 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4045 && "Unexpected vector type");
4046 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4047 && "Unexpected vector type");
4048 SDValue Cst = DAG.getConstant(0, MVT::i1);
4049 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4050 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4052 llvm_unreachable("Unexpected vector type");
4054 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4057 /// getOnesVector - Returns a vector of specified type with all bits set.
4058 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4059 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4060 /// Then bitcast to their original type, ensuring they get CSE'd.
4061 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4063 assert(VT.isVector() && "Expected a vector type");
4065 SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4067 if (VT.is256BitVector()) {
4068 if (HasInt256) { // AVX2
4069 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4070 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4072 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4073 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4075 } else if (VT.is128BitVector()) {
4076 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4078 llvm_unreachable("Unexpected vector type");
4080 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4083 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4084 /// operation of specified width.
4085 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4087 unsigned NumElems = VT.getVectorNumElements();
4088 SmallVector<int, 8> Mask;
4089 Mask.push_back(NumElems);
4090 for (unsigned i = 1; i != NumElems; ++i)
4092 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4095 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4096 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4098 unsigned NumElems = VT.getVectorNumElements();
4099 SmallVector<int, 8> Mask;
4100 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4102 Mask.push_back(i + NumElems);
4104 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4107 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4108 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4110 unsigned NumElems = VT.getVectorNumElements();
4111 SmallVector<int, 8> Mask;
4112 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4113 Mask.push_back(i + Half);
4114 Mask.push_back(i + NumElems + Half);
4116 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4119 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4120 /// vector of zero or undef vector. This produces a shuffle where the low
4121 /// element of V2 is swizzled into the zero/undef vector, landing at element
4122 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4123 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4125 const X86Subtarget *Subtarget,
4126 SelectionDAG &DAG) {
4127 MVT VT = V2.getSimpleValueType();
4129 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4130 unsigned NumElems = VT.getVectorNumElements();
4131 SmallVector<int, 16> MaskVec;
4132 for (unsigned i = 0; i != NumElems; ++i)
4133 // If this is the insertion idx, put the low elt of V2 here.
4134 MaskVec.push_back(i == Idx ? NumElems : i);
4135 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4138 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4139 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4140 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4141 /// shuffles which use a single input multiple times, and in those cases it will
4142 /// adjust the mask to only have indices within that single input.
4143 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4144 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4145 unsigned NumElems = VT.getVectorNumElements();
4149 bool IsFakeUnary = false;
4150 switch(N->getOpcode()) {
4151 case X86ISD::BLENDI:
4152 ImmN = N->getOperand(N->getNumOperands()-1);
4153 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4156 ImmN = N->getOperand(N->getNumOperands()-1);
4157 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4158 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4160 case X86ISD::UNPCKH:
4161 DecodeUNPCKHMask(VT, Mask);
4162 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4164 case X86ISD::UNPCKL:
4165 DecodeUNPCKLMask(VT, Mask);
4166 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4168 case X86ISD::MOVHLPS:
4169 DecodeMOVHLPSMask(NumElems, Mask);
4170 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4172 case X86ISD::MOVLHPS:
4173 DecodeMOVLHPSMask(NumElems, Mask);
4174 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4176 case X86ISD::PALIGNR:
4177 ImmN = N->getOperand(N->getNumOperands()-1);
4178 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4180 case X86ISD::PSHUFD:
4181 case X86ISD::VPERMILPI:
4182 ImmN = N->getOperand(N->getNumOperands()-1);
4183 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4186 case X86ISD::PSHUFHW:
4187 ImmN = N->getOperand(N->getNumOperands()-1);
4188 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4191 case X86ISD::PSHUFLW:
4192 ImmN = N->getOperand(N->getNumOperands()-1);
4193 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196 case X86ISD::PSHUFB: {
4198 SDValue MaskNode = N->getOperand(1);
4199 while (MaskNode->getOpcode() == ISD::BITCAST)
4200 MaskNode = MaskNode->getOperand(0);
4202 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4203 // If we have a build-vector, then things are easy.
4204 EVT VT = MaskNode.getValueType();
4205 assert(VT.isVector() &&
4206 "Can't produce a non-vector with a build_vector!");
4207 if (!VT.isInteger())
4210 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4212 SmallVector<uint64_t, 32> RawMask;
4213 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4214 SDValue Op = MaskNode->getOperand(i);
4215 if (Op->getOpcode() == ISD::UNDEF) {
4216 RawMask.push_back((uint64_t)SM_SentinelUndef);
4219 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4222 APInt MaskElement = CN->getAPIntValue();
4224 // We now have to decode the element which could be any integer size and
4225 // extract each byte of it.
4226 for (int j = 0; j < NumBytesPerElement; ++j) {
4227 // Note that this is x86 and so always little endian: the low byte is
4228 // the first byte of the mask.
4229 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4230 MaskElement = MaskElement.lshr(8);
4233 DecodePSHUFBMask(RawMask, Mask);
4237 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4241 SDValue Ptr = MaskLoad->getBasePtr();
4242 if (Ptr->getOpcode() == X86ISD::Wrapper)
4243 Ptr = Ptr->getOperand(0);
4245 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4246 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4249 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4250 DecodePSHUFBMask(C, Mask);
4258 case X86ISD::VPERMI:
4259 ImmN = N->getOperand(N->getNumOperands()-1);
4260 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4265 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4267 case X86ISD::VPERM2X128:
4268 ImmN = N->getOperand(N->getNumOperands()-1);
4269 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4270 if (Mask.empty()) return false;
4272 case X86ISD::MOVSLDUP:
4273 DecodeMOVSLDUPMask(VT, Mask);
4276 case X86ISD::MOVSHDUP:
4277 DecodeMOVSHDUPMask(VT, Mask);
4280 case X86ISD::MOVDDUP:
4281 DecodeMOVDDUPMask(VT, Mask);
4284 case X86ISD::MOVLHPD:
4285 case X86ISD::MOVLPD:
4286 case X86ISD::MOVLPS:
4287 // Not yet implemented
4289 default: llvm_unreachable("unknown target shuffle node");
4292 // If we have a fake unary shuffle, the shuffle mask is spread across two
4293 // inputs that are actually the same node. Re-map the mask to always point
4294 // into the first input.
4297 if (M >= (int)Mask.size())
4303 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4304 /// element of the result of the vector shuffle.
4305 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4308 return SDValue(); // Limit search depth.
4310 SDValue V = SDValue(N, 0);
4311 EVT VT = V.getValueType();
4312 unsigned Opcode = V.getOpcode();
4314 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4315 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4316 int Elt = SV->getMaskElt(Index);
4319 return DAG.getUNDEF(VT.getVectorElementType());
4321 unsigned NumElems = VT.getVectorNumElements();
4322 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4323 : SV->getOperand(1);
4324 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4327 // Recurse into target specific vector shuffles to find scalars.
4328 if (isTargetShuffle(Opcode)) {
4329 MVT ShufVT = V.getSimpleValueType();
4330 unsigned NumElems = ShufVT.getVectorNumElements();
4331 SmallVector<int, 16> ShuffleMask;
4334 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4337 int Elt = ShuffleMask[Index];
4339 return DAG.getUNDEF(ShufVT.getVectorElementType());
4341 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4343 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4347 // Actual nodes that may contain scalar elements
4348 if (Opcode == ISD::BITCAST) {
4349 V = V.getOperand(0);
4350 EVT SrcVT = V.getValueType();
4351 unsigned NumElems = VT.getVectorNumElements();
4353 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4357 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4358 return (Index == 0) ? V.getOperand(0)
4359 : DAG.getUNDEF(VT.getVectorElementType());
4361 if (V.getOpcode() == ISD::BUILD_VECTOR)
4362 return V.getOperand(Index);
4367 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4369 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4370 unsigned NumNonZero, unsigned NumZero,
4372 const X86Subtarget* Subtarget,
4373 const TargetLowering &TLI) {
4380 for (unsigned i = 0; i < 16; ++i) {
4381 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4382 if (ThisIsNonZero && First) {
4384 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4386 V = DAG.getUNDEF(MVT::v8i16);
4391 SDValue ThisElt, LastElt;
4392 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4393 if (LastIsNonZero) {
4394 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4395 MVT::i16, Op.getOperand(i-1));
4397 if (ThisIsNonZero) {
4398 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4399 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4400 ThisElt, DAG.getConstant(8, MVT::i8));
4402 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4406 if (ThisElt.getNode())
4407 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4408 DAG.getIntPtrConstant(i/2));
4412 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4415 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4417 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4418 unsigned NumNonZero, unsigned NumZero,
4420 const X86Subtarget* Subtarget,
4421 const TargetLowering &TLI) {
4428 for (unsigned i = 0; i < 8; ++i) {
4429 bool isNonZero = (NonZeros & (1 << i)) != 0;
4433 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4435 V = DAG.getUNDEF(MVT::v8i16);
4438 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4439 MVT::v8i16, V, Op.getOperand(i),
4440 DAG.getIntPtrConstant(i));
4447 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4448 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4449 const X86Subtarget *Subtarget,
4450 const TargetLowering &TLI) {
4451 // Find all zeroable elements.
4452 std::bitset<4> Zeroable;
4453 for (int i=0; i < 4; ++i) {
4454 SDValue Elt = Op->getOperand(i);
4455 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4457 assert(Zeroable.size() - Zeroable.count() > 1 &&
4458 "We expect at least two non-zero elements!");
4460 // We only know how to deal with build_vector nodes where elements are either
4461 // zeroable or extract_vector_elt with constant index.
4462 SDValue FirstNonZero;
4463 unsigned FirstNonZeroIdx;
4464 for (unsigned i=0; i < 4; ++i) {
4467 SDValue Elt = Op->getOperand(i);
4468 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4469 !isa<ConstantSDNode>(Elt.getOperand(1)))
4471 // Make sure that this node is extracting from a 128-bit vector.
4472 MVT VT = Elt.getOperand(0).getSimpleValueType();
4473 if (!VT.is128BitVector())
4475 if (!FirstNonZero.getNode()) {
4477 FirstNonZeroIdx = i;
4481 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4482 SDValue V1 = FirstNonZero.getOperand(0);
4483 MVT VT = V1.getSimpleValueType();
4485 // See if this build_vector can be lowered as a blend with zero.
4487 unsigned EltMaskIdx, EltIdx;
4489 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4490 if (Zeroable[EltIdx]) {
4491 // The zero vector will be on the right hand side.
4492 Mask[EltIdx] = EltIdx+4;
4496 Elt = Op->getOperand(EltIdx);
4497 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4498 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4499 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4501 Mask[EltIdx] = EltIdx;
4505 // Let the shuffle legalizer deal with blend operations.
4506 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4507 if (V1.getSimpleValueType() != VT)
4508 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4509 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4512 // See if we can lower this build_vector to a INSERTPS.
4513 if (!Subtarget->hasSSE41())
4516 SDValue V2 = Elt.getOperand(0);
4517 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4520 bool CanFold = true;
4521 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4525 SDValue Current = Op->getOperand(i);
4526 SDValue SrcVector = Current->getOperand(0);
4529 CanFold = SrcVector == V1 &&
4530 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4536 assert(V1.getNode() && "Expected at least two non-zero elements!");
4537 if (V1.getSimpleValueType() != MVT::v4f32)
4538 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4539 if (V2.getSimpleValueType() != MVT::v4f32)
4540 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4542 // Ok, we can emit an INSERTPS instruction.
4543 unsigned ZMask = Zeroable.to_ulong();
4545 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4546 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4547 SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4548 DAG.getIntPtrConstant(InsertPSMask));
4549 return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4552 /// Return a vector logical shift node.
4553 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4554 unsigned NumBits, SelectionDAG &DAG,
4555 const TargetLowering &TLI, SDLoc dl) {
4556 assert(VT.is128BitVector() && "Unknown type for VShift");
4557 MVT ShVT = MVT::v2i64;
4558 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4559 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4560 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4561 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4562 SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4563 return DAG.getNode(ISD::BITCAST, dl, VT,
4564 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4568 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4570 // Check if the scalar load can be widened into a vector load. And if
4571 // the address is "base + cst" see if the cst can be "absorbed" into
4572 // the shuffle mask.
4573 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4574 SDValue Ptr = LD->getBasePtr();
4575 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4577 EVT PVT = LD->getValueType(0);
4578 if (PVT != MVT::i32 && PVT != MVT::f32)
4583 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4584 FI = FINode->getIndex();
4586 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4587 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4588 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4589 Offset = Ptr.getConstantOperandVal(1);
4590 Ptr = Ptr.getOperand(0);
4595 // FIXME: 256-bit vector instructions don't require a strict alignment,
4596 // improve this code to support it better.
4597 unsigned RequiredAlign = VT.getSizeInBits()/8;
4598 SDValue Chain = LD->getChain();
4599 // Make sure the stack object alignment is at least 16 or 32.
4600 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4601 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4602 if (MFI->isFixedObjectIndex(FI)) {
4603 // Can't change the alignment. FIXME: It's possible to compute
4604 // the exact stack offset and reference FI + adjust offset instead.
4605 // If someone *really* cares about this. That's the way to implement it.
4608 MFI->setObjectAlignment(FI, RequiredAlign);
4612 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4613 // Ptr + (Offset & ~15).
4616 if ((Offset % RequiredAlign) & 3)
4618 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4620 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4621 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4623 int EltNo = (Offset - StartOffset) >> 2;
4624 unsigned NumElems = VT.getVectorNumElements();
4626 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4627 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4628 LD->getPointerInfo().getWithOffset(StartOffset),
4629 false, false, false, 0);
4631 SmallVector<int, 8> Mask(NumElems, EltNo);
4633 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4639 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4640 /// elements can be replaced by a single large load which has the same value as
4641 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4643 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4645 /// FIXME: we'd also like to handle the case where the last elements are zero
4646 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4647 /// There's even a handy isZeroNode for that purpose.
4648 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4649 SDLoc &DL, SelectionDAG &DAG,
4650 bool isAfterLegalize) {
4651 unsigned NumElems = Elts.size();
4653 LoadSDNode *LDBase = nullptr;
4654 unsigned LastLoadedElt = -1U;
4656 // For each element in the initializer, see if we've found a load or an undef.
4657 // If we don't find an initial load element, or later load elements are
4658 // non-consecutive, bail out.
4659 for (unsigned i = 0; i < NumElems; ++i) {
4660 SDValue Elt = Elts[i];
4661 // Look through a bitcast.
4662 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4663 Elt = Elt.getOperand(0);
4664 if (!Elt.getNode() ||
4665 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4668 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4670 LDBase = cast<LoadSDNode>(Elt.getNode());
4674 if (Elt.getOpcode() == ISD::UNDEF)
4677 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4678 EVT LdVT = Elt.getValueType();
4679 // Each loaded element must be the correct fractional portion of the
4680 // requested vector load.
4681 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4683 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4688 // If we have found an entire vector of loads and undefs, then return a large
4689 // load of the entire vector width starting at the base pointer. If we found
4690 // consecutive loads for the low half, generate a vzext_load node.
4691 if (LastLoadedElt == NumElems - 1) {
4692 assert(LDBase && "Did not find base load for merging consecutive loads");
4693 EVT EltVT = LDBase->getValueType(0);
4694 // Ensure that the input vector size for the merged loads matches the
4695 // cumulative size of the input elements.
4696 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4699 if (isAfterLegalize &&
4700 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4703 SDValue NewLd = SDValue();
4705 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4706 LDBase->getPointerInfo(), LDBase->isVolatile(),
4707 LDBase->isNonTemporal(), LDBase->isInvariant(),
4708 LDBase->getAlignment());
4710 if (LDBase->hasAnyUseOfValue(1)) {
4711 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4713 SDValue(NewLd.getNode(), 1));
4714 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4715 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4716 SDValue(NewLd.getNode(), 1));
4722 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4723 //of a v4i32 / v4f32. It's probably worth generalizing.
4724 EVT EltVT = VT.getVectorElementType();
4725 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4726 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4727 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4728 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4730 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4731 LDBase->getPointerInfo(),
4732 LDBase->getAlignment(),
4733 false/*isVolatile*/, true/*ReadMem*/,
4736 // Make sure the newly-created LOAD is in the same position as LDBase in
4737 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4738 // update uses of LDBase's output chain to use the TokenFactor.
4739 if (LDBase->hasAnyUseOfValue(1)) {
4740 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4741 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4742 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4743 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4744 SDValue(ResNode.getNode(), 1));
4747 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4752 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4753 /// to generate a splat value for the following cases:
4754 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4755 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4756 /// a scalar load, or a constant.
4757 /// The VBROADCAST node is returned when a pattern is found,
4758 /// or SDValue() otherwise.
4759 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4760 SelectionDAG &DAG) {
4761 // VBROADCAST requires AVX.
4762 // TODO: Splats could be generated for non-AVX CPUs using SSE
4763 // instructions, but there's less potential gain for only 128-bit vectors.
4764 if (!Subtarget->hasAVX())
4767 MVT VT = Op.getSimpleValueType();
4770 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4771 "Unsupported vector type for broadcast.");
4776 switch (Op.getOpcode()) {
4778 // Unknown pattern found.
4781 case ISD::BUILD_VECTOR: {
4782 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4783 BitVector UndefElements;
4784 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4786 // We need a splat of a single value to use broadcast, and it doesn't
4787 // make any sense if the value is only in one element of the vector.
4788 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4792 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4793 Ld.getOpcode() == ISD::ConstantFP);
4795 // Make sure that all of the users of a non-constant load are from the
4796 // BUILD_VECTOR node.
4797 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4802 case ISD::VECTOR_SHUFFLE: {
4803 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4805 // Shuffles must have a splat mask where the first element is
4807 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4810 SDValue Sc = Op.getOperand(0);
4811 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4812 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4814 if (!Subtarget->hasInt256())
4817 // Use the register form of the broadcast instruction available on AVX2.
4818 if (VT.getSizeInBits() >= 256)
4819 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4820 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4823 Ld = Sc.getOperand(0);
4824 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4825 Ld.getOpcode() == ISD::ConstantFP);
4827 // The scalar_to_vector node and the suspected
4828 // load node must have exactly one user.
4829 // Constants may have multiple users.
4831 // AVX-512 has register version of the broadcast
4832 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4833 Ld.getValueType().getSizeInBits() >= 32;
4834 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4841 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4842 bool IsGE256 = (VT.getSizeInBits() >= 256);
4844 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4845 // instruction to save 8 or more bytes of constant pool data.
4846 // TODO: If multiple splats are generated to load the same constant,
4847 // it may be detrimental to overall size. There needs to be a way to detect
4848 // that condition to know if this is truly a size win.
4849 const Function *F = DAG.getMachineFunction().getFunction();
4850 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4852 // Handle broadcasting a single constant scalar from the constant pool
4854 // On Sandybridge (no AVX2), it is still better to load a constant vector
4855 // from the constant pool and not to broadcast it from a scalar.
4856 // But override that restriction when optimizing for size.
4857 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4858 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4859 EVT CVT = Ld.getValueType();
4860 assert(!CVT.isVector() && "Must not broadcast a vector type");
4862 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4863 // For size optimization, also splat v2f64 and v2i64, and for size opt
4864 // with AVX2, also splat i8 and i16.
4865 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4866 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4867 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4868 const Constant *C = nullptr;
4869 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4870 C = CI->getConstantIntValue();
4871 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4872 C = CF->getConstantFPValue();
4874 assert(C && "Invalid constant type");
4876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4877 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4878 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4879 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4880 MachinePointerInfo::getConstantPool(),
4881 false, false, false, Alignment);
4883 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4887 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4889 // Handle AVX2 in-register broadcasts.
4890 if (!IsLoad && Subtarget->hasInt256() &&
4891 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4892 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4894 // The scalar source must be a normal load.
4898 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4899 (Subtarget->hasVLX() && ScalarSize == 64))
4900 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4902 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4903 // double since there is no vbroadcastsd xmm
4904 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4905 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4906 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4909 // Unsupported broadcast.
4913 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4914 /// underlying vector and index.
4916 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4918 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4920 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4921 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4924 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4926 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4928 // (extract_vector_elt (vector_shuffle<2,u,u,u>
4929 // (extract_subvector (v8f32 %vreg0), Constant<4>),
4932 // In this case the vector is the extract_subvector expression and the index
4933 // is 2, as specified by the shuffle.
4934 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4935 SDValue ShuffleVec = SVOp->getOperand(0);
4936 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4937 assert(ShuffleVecVT.getVectorElementType() ==
4938 ExtractedFromVec.getSimpleValueType().getVectorElementType());
4940 int ShuffleIdx = SVOp->getMaskElt(Idx);
4941 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4942 ExtractedFromVec = ShuffleVec;
4948 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4949 MVT VT = Op.getSimpleValueType();
4951 // Skip if insert_vec_elt is not supported.
4952 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4953 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4957 unsigned NumElems = Op.getNumOperands();
4961 SmallVector<unsigned, 4> InsertIndices;
4962 SmallVector<int, 8> Mask(NumElems, -1);
4964 for (unsigned i = 0; i != NumElems; ++i) {
4965 unsigned Opc = Op.getOperand(i).getOpcode();
4967 if (Opc == ISD::UNDEF)
4970 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
4971 // Quit if more than 1 elements need inserting.
4972 if (InsertIndices.size() > 1)
4975 InsertIndices.push_back(i);
4979 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
4980 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
4981 // Quit if non-constant index.
4982 if (!isa<ConstantSDNode>(ExtIdx))
4984 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
4986 // Quit if extracted from vector of different type.
4987 if (ExtractedFromVec.getValueType() != VT)
4990 if (!VecIn1.getNode())
4991 VecIn1 = ExtractedFromVec;
4992 else if (VecIn1 != ExtractedFromVec) {
4993 if (!VecIn2.getNode())
4994 VecIn2 = ExtractedFromVec;
4995 else if (VecIn2 != ExtractedFromVec)
4996 // Quit if more than 2 vectors to shuffle
5000 if (ExtractedFromVec == VecIn1)
5002 else if (ExtractedFromVec == VecIn2)
5003 Mask[i] = Idx + NumElems;
5006 if (!VecIn1.getNode())
5009 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5010 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5011 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5012 unsigned Idx = InsertIndices[i];
5013 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5014 DAG.getIntPtrConstant(Idx));
5020 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5022 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5024 MVT VT = Op.getSimpleValueType();
5025 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5026 "Unexpected type in LowerBUILD_VECTORvXi1!");
5029 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5030 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5031 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5032 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5035 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5036 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5037 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5038 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5041 bool AllContants = true;
5042 uint64_t Immediate = 0;
5043 int NonConstIdx = -1;
5044 bool IsSplat = true;
5045 unsigned NumNonConsts = 0;
5046 unsigned NumConsts = 0;
5047 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5048 SDValue In = Op.getOperand(idx);
5049 if (In.getOpcode() == ISD::UNDEF)
5051 if (!isa<ConstantSDNode>(In)) {
5052 AllContants = false;
5057 if (cast<ConstantSDNode>(In)->getZExtValue())
5058 Immediate |= (1ULL << idx);
5060 if (In != Op.getOperand(0))
5065 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5066 DAG.getConstant(Immediate, MVT::i16));
5067 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5068 DAG.getIntPtrConstant(0));
5071 if (NumNonConsts == 1 && NonConstIdx != 0) {
5074 SDValue VecAsImm = DAG.getConstant(Immediate,
5075 MVT::getIntegerVT(VT.getSizeInBits()));
5076 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5079 DstVec = DAG.getUNDEF(VT);
5080 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5081 Op.getOperand(NonConstIdx),
5082 DAG.getIntPtrConstant(NonConstIdx));
5084 if (!IsSplat && (NonConstIdx != 0))
5085 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5086 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5089 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5090 DAG.getConstant(-1, SelectVT),
5091 DAG.getConstant(0, SelectVT));
5093 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5094 DAG.getConstant((Immediate | 1), SelectVT),
5095 DAG.getConstant(Immediate, SelectVT));
5096 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5099 /// \brief Return true if \p N implements a horizontal binop and return the
5100 /// operands for the horizontal binop into V0 and V1.
5102 /// This is a helper function of PerformBUILD_VECTORCombine.
5103 /// This function checks that the build_vector \p N in input implements a
5104 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5105 /// operation to match.
5106 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5107 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5108 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5111 /// This function only analyzes elements of \p N whose indices are
5112 /// in range [BaseIdx, LastIdx).
5113 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5115 unsigned BaseIdx, unsigned LastIdx,
5116 SDValue &V0, SDValue &V1) {
5117 EVT VT = N->getValueType(0);
5119 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5120 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5121 "Invalid Vector in input!");
5123 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5124 bool CanFold = true;
5125 unsigned ExpectedVExtractIdx = BaseIdx;
5126 unsigned NumElts = LastIdx - BaseIdx;
5127 V0 = DAG.getUNDEF(VT);
5128 V1 = DAG.getUNDEF(VT);
5130 // Check if N implements a horizontal binop.
5131 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5132 SDValue Op = N->getOperand(i + BaseIdx);
5135 if (Op->getOpcode() == ISD::UNDEF) {
5136 // Update the expected vector extract index.
5137 if (i * 2 == NumElts)
5138 ExpectedVExtractIdx = BaseIdx;
5139 ExpectedVExtractIdx += 2;
5143 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5148 SDValue Op0 = Op.getOperand(0);
5149 SDValue Op1 = Op.getOperand(1);
5151 // Try to match the following pattern:
5152 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5153 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5154 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5155 Op0.getOperand(0) == Op1.getOperand(0) &&
5156 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5157 isa<ConstantSDNode>(Op1.getOperand(1)));
5161 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5162 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5164 if (i * 2 < NumElts) {
5165 if (V0.getOpcode() == ISD::UNDEF)
5166 V0 = Op0.getOperand(0);
5168 if (V1.getOpcode() == ISD::UNDEF)
5169 V1 = Op0.getOperand(0);
5170 if (i * 2 == NumElts)
5171 ExpectedVExtractIdx = BaseIdx;
5174 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5175 if (I0 == ExpectedVExtractIdx)
5176 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5177 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5178 // Try to match the following dag sequence:
5179 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5180 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5184 ExpectedVExtractIdx += 2;
5190 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5191 /// a concat_vector.
5193 /// This is a helper function of PerformBUILD_VECTORCombine.
5194 /// This function expects two 256-bit vectors called V0 and V1.
5195 /// At first, each vector is split into two separate 128-bit vectors.
5196 /// Then, the resulting 128-bit vectors are used to implement two
5197 /// horizontal binary operations.
5199 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5201 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5202 /// the two new horizontal binop.
5203 /// When Mode is set, the first horizontal binop dag node would take as input
5204 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5205 /// horizontal binop dag node would take as input the lower 128-bit of V1
5206 /// and the upper 128-bit of V1.
5208 /// HADD V0_LO, V0_HI
5209 /// HADD V1_LO, V1_HI
5211 /// Otherwise, the first horizontal binop dag node takes as input the lower
5212 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5213 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5215 /// HADD V0_LO, V1_LO
5216 /// HADD V0_HI, V1_HI
5218 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5219 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5220 /// the upper 128-bits of the result.
5221 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5222 SDLoc DL, SelectionDAG &DAG,
5223 unsigned X86Opcode, bool Mode,
5224 bool isUndefLO, bool isUndefHI) {
5225 EVT VT = V0.getValueType();
5226 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5227 "Invalid nodes in input!");
5229 unsigned NumElts = VT.getVectorNumElements();
5230 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5231 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5232 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5233 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5234 EVT NewVT = V0_LO.getValueType();
5236 SDValue LO = DAG.getUNDEF(NewVT);
5237 SDValue HI = DAG.getUNDEF(NewVT);
5240 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5241 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5242 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5243 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5244 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5246 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5247 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5248 V1_LO->getOpcode() != ISD::UNDEF))
5249 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5251 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5252 V1_HI->getOpcode() != ISD::UNDEF))
5253 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5256 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5259 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5260 /// sequence of 'vadd + vsub + blendi'.
5261 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5262 const X86Subtarget *Subtarget) {
5264 EVT VT = BV->getValueType(0);
5265 unsigned NumElts = VT.getVectorNumElements();
5266 SDValue InVec0 = DAG.getUNDEF(VT);
5267 SDValue InVec1 = DAG.getUNDEF(VT);
5269 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5270 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5272 // Odd-numbered elements in the input build vector are obtained from
5273 // adding two integer/float elements.
5274 // Even-numbered elements in the input build vector are obtained from
5275 // subtracting two integer/float elements.
5276 unsigned ExpectedOpcode = ISD::FSUB;
5277 unsigned NextExpectedOpcode = ISD::FADD;
5278 bool AddFound = false;
5279 bool SubFound = false;
5281 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5282 SDValue Op = BV->getOperand(i);
5284 // Skip 'undef' values.
5285 unsigned Opcode = Op.getOpcode();
5286 if (Opcode == ISD::UNDEF) {
5287 std::swap(ExpectedOpcode, NextExpectedOpcode);
5291 // Early exit if we found an unexpected opcode.
5292 if (Opcode != ExpectedOpcode)
5295 SDValue Op0 = Op.getOperand(0);
5296 SDValue Op1 = Op.getOperand(1);
5298 // Try to match the following pattern:
5299 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5300 // Early exit if we cannot match that sequence.
5301 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5302 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5303 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5304 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5305 Op0.getOperand(1) != Op1.getOperand(1))
5308 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5312 // We found a valid add/sub node. Update the information accordingly.
5318 // Update InVec0 and InVec1.
5319 if (InVec0.getOpcode() == ISD::UNDEF)
5320 InVec0 = Op0.getOperand(0);
5321 if (InVec1.getOpcode() == ISD::UNDEF)
5322 InVec1 = Op1.getOperand(0);
5324 // Make sure that operands in input to each add/sub node always
5325 // come from a same pair of vectors.
5326 if (InVec0 != Op0.getOperand(0)) {
5327 if (ExpectedOpcode == ISD::FSUB)
5330 // FADD is commutable. Try to commute the operands
5331 // and then test again.
5332 std::swap(Op0, Op1);
5333 if (InVec0 != Op0.getOperand(0))
5337 if (InVec1 != Op1.getOperand(0))
5340 // Update the pair of expected opcodes.
5341 std::swap(ExpectedOpcode, NextExpectedOpcode);
5344 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5345 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5346 InVec1.getOpcode() != ISD::UNDEF)
5347 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5353 const X86Subtarget *Subtarget) {
5355 EVT VT = N->getValueType(0);
5356 unsigned NumElts = VT.getVectorNumElements();
5357 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5358 SDValue InVec0, InVec1;
5360 // Try to match an ADDSUB.
5361 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5362 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5363 SDValue Value = matchAddSub(BV, DAG, Subtarget);
5364 if (Value.getNode())
5368 // Try to match horizontal ADD/SUB.
5369 unsigned NumUndefsLO = 0;
5370 unsigned NumUndefsHI = 0;
5371 unsigned Half = NumElts/2;
5373 // Count the number of UNDEF operands in the build_vector in input.
5374 for (unsigned i = 0, e = Half; i != e; ++i)
5375 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5378 for (unsigned i = Half, e = NumElts; i != e; ++i)
5379 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5382 // Early exit if this is either a build_vector of all UNDEFs or all the
5383 // operands but one are UNDEF.
5384 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5387 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5388 // Try to match an SSE3 float HADD/HSUB.
5389 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5390 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5392 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5393 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5394 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5395 // Try to match an SSSE3 integer HADD/HSUB.
5396 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5397 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5399 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5400 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5403 if (!Subtarget->hasAVX())
5406 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5407 // Try to match an AVX horizontal add/sub of packed single/double
5408 // precision floating point values from 256-bit vectors.
5409 SDValue InVec2, InVec3;
5410 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5411 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5412 ((InVec0.getOpcode() == ISD::UNDEF ||
5413 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5414 ((InVec1.getOpcode() == ISD::UNDEF ||
5415 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5416 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5418 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5419 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5420 ((InVec0.getOpcode() == ISD::UNDEF ||
5421 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5422 ((InVec1.getOpcode() == ISD::UNDEF ||
5423 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5424 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5425 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5426 // Try to match an AVX2 horizontal add/sub of signed integers.
5427 SDValue InVec2, InVec3;
5429 bool CanFold = true;
5431 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5432 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5433 ((InVec0.getOpcode() == ISD::UNDEF ||
5434 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5435 ((InVec1.getOpcode() == ISD::UNDEF ||
5436 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5437 X86Opcode = X86ISD::HADD;
5438 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5439 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5440 ((InVec0.getOpcode() == ISD::UNDEF ||
5441 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5442 ((InVec1.getOpcode() == ISD::UNDEF ||
5443 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5444 X86Opcode = X86ISD::HSUB;
5449 // Fold this build_vector into a single horizontal add/sub.
5450 // Do this only if the target has AVX2.
5451 if (Subtarget->hasAVX2())
5452 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5454 // Do not try to expand this build_vector into a pair of horizontal
5455 // add/sub if we can emit a pair of scalar add/sub.
5456 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5459 // Convert this build_vector into a pair of horizontal binop followed by
5461 bool isUndefLO = NumUndefsLO == Half;
5462 bool isUndefHI = NumUndefsHI == Half;
5463 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5464 isUndefLO, isUndefHI);
5468 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5469 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5471 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5472 X86Opcode = X86ISD::HADD;
5473 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5474 X86Opcode = X86ISD::HSUB;
5475 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5476 X86Opcode = X86ISD::FHADD;
5477 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5478 X86Opcode = X86ISD::FHSUB;
5482 // Don't try to expand this build_vector into a pair of horizontal add/sub
5483 // if we can simply emit a pair of scalar add/sub.
5484 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5487 // Convert this build_vector into two horizontal add/sub followed by
5489 bool isUndefLO = NumUndefsLO == Half;
5490 bool isUndefHI = NumUndefsHI == Half;
5491 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5492 isUndefLO, isUndefHI);
5499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5502 MVT VT = Op.getSimpleValueType();
5503 MVT ExtVT = VT.getVectorElementType();
5504 unsigned NumElems = Op.getNumOperands();
5506 // Generate vectors for predicate vectors.
5507 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5508 return LowerBUILD_VECTORvXi1(Op, DAG);
5510 // Vectors containing all zeros can be matched by pxor and xorps later
5511 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5512 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5513 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5514 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5517 return getZeroVector(VT, Subtarget, DAG, dl);
5520 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5521 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5522 // vpcmpeqd on 256-bit vectors.
5523 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5524 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5527 if (!VT.is512BitVector())
5528 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5531 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5532 if (Broadcast.getNode())
5535 unsigned EVTBits = ExtVT.getSizeInBits();
5537 unsigned NumZero = 0;
5538 unsigned NumNonZero = 0;
5539 unsigned NonZeros = 0;
5540 bool IsAllConstants = true;
5541 SmallSet<SDValue, 8> Values;
5542 for (unsigned i = 0; i < NumElems; ++i) {
5543 SDValue Elt = Op.getOperand(i);
5544 if (Elt.getOpcode() == ISD::UNDEF)
5547 if (Elt.getOpcode() != ISD::Constant &&
5548 Elt.getOpcode() != ISD::ConstantFP)
5549 IsAllConstants = false;
5550 if (X86::isZeroNode(Elt))
5553 NonZeros |= (1 << i);
5558 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5559 if (NumNonZero == 0)
5560 return DAG.getUNDEF(VT);
5562 // Special case for single non-zero, non-undef, element.
5563 if (NumNonZero == 1) {
5564 unsigned Idx = countTrailingZeros(NonZeros);
5565 SDValue Item = Op.getOperand(Idx);
5567 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5568 // the value are obviously zero, truncate the value to i32 and do the
5569 // insertion that way. Only do this if the value is non-constant or if the
5570 // value is a constant being inserted into element 0. It is cheaper to do
5571 // a constant pool load than it is to do a movd + shuffle.
5572 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5573 (!IsAllConstants || Idx == 0)) {
5574 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5576 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5577 EVT VecVT = MVT::v4i32;
5579 // Truncate the value (which may itself be a constant) to i32, and
5580 // convert it to a vector with movd (S2V+shuffle to zero extend).
5581 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5582 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5584 ISD::BITCAST, dl, VT,
5585 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5589 // If we have a constant or non-constant insertion into the low element of
5590 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5591 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5592 // depending on what the source datatype is.
5595 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5597 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5598 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5599 if (VT.is512BitVector()) {
5600 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5601 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5602 Item, DAG.getIntPtrConstant(0));
5604 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5605 "Expected an SSE value type!");
5606 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5607 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5608 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5611 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5612 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5613 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5614 if (VT.is256BitVector()) {
5615 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5616 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5618 assert(VT.is128BitVector() && "Expected an SSE value type!");
5619 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5621 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5625 // Is it a vector logical left shift?
5626 if (NumElems == 2 && Idx == 1 &&
5627 X86::isZeroNode(Op.getOperand(0)) &&
5628 !X86::isZeroNode(Op.getOperand(1))) {
5629 unsigned NumBits = VT.getSizeInBits();
5630 return getVShift(true, VT,
5631 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5632 VT, Op.getOperand(1)),
5633 NumBits/2, DAG, *this, dl);
5636 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5639 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5640 // is a non-constant being inserted into an element other than the low one,
5641 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5642 // movd/movss) to move this into the low element, then shuffle it into
5644 if (EVTBits == 32) {
5645 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5646 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5650 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5651 if (Values.size() == 1) {
5652 if (EVTBits == 32) {
5653 // Instead of a shuffle like this:
5654 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5655 // Check if it's possible to issue this instead.
5656 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5657 unsigned Idx = countTrailingZeros(NonZeros);
5658 SDValue Item = Op.getOperand(Idx);
5659 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5660 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5665 // A vector full of immediates; various special cases are already
5666 // handled, so this is best done with a single constant-pool load.
5670 // For AVX-length vectors, see if we can use a vector load to get all of the
5671 // elements, otherwise build the individual 128-bit pieces and use
5672 // shuffles to put them in place.
5673 if (VT.is256BitVector() || VT.is512BitVector()) {
5674 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5676 // Check for a build vector of consecutive loads.
5677 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5680 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5682 // Build both the lower and upper subvector.
5683 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5684 makeArrayRef(&V[0], NumElems/2));
5685 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5686 makeArrayRef(&V[NumElems / 2], NumElems/2));
5688 // Recreate the wider vector with the lower and upper part.
5689 if (VT.is256BitVector())
5690 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5691 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5694 // Let legalizer expand 2-wide build_vectors.
5695 if (EVTBits == 64) {
5696 if (NumNonZero == 1) {
5697 // One half is zero or undef.
5698 unsigned Idx = countTrailingZeros(NonZeros);
5699 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5700 Op.getOperand(Idx));
5701 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5706 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5707 if (EVTBits == 8 && NumElems == 16) {
5708 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5710 if (V.getNode()) return V;
5713 if (EVTBits == 16 && NumElems == 8) {
5714 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5716 if (V.getNode()) return V;
5719 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5720 if (EVTBits == 32 && NumElems == 4) {
5721 SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5726 // If element VT is == 32 bits, turn it into a number of shuffles.
5727 SmallVector<SDValue, 8> V(NumElems);
5728 if (NumElems == 4 && NumZero > 0) {
5729 for (unsigned i = 0; i < 4; ++i) {
5730 bool isZero = !(NonZeros & (1 << i));
5732 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5734 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5737 for (unsigned i = 0; i < 2; ++i) {
5738 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5741 V[i] = V[i*2]; // Must be a zero vector.
5744 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5747 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5750 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5755 bool Reverse1 = (NonZeros & 0x3) == 2;
5756 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5760 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5761 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5763 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5766 if (Values.size() > 1 && VT.is128BitVector()) {
5767 // Check for a build vector of consecutive loads.
5768 for (unsigned i = 0; i < NumElems; ++i)
5769 V[i] = Op.getOperand(i);
5771 // Check for elements which are consecutive loads.
5772 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5776 // Check for a build vector from mostly shuffle plus few inserting.
5777 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5781 // For SSE 4.1, use insertps to put the high elements into the low element.
5782 if (Subtarget->hasSSE41()) {
5784 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5785 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5787 Result = DAG.getUNDEF(VT);
5789 for (unsigned i = 1; i < NumElems; ++i) {
5790 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5791 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5792 Op.getOperand(i), DAG.getIntPtrConstant(i));
5797 // Otherwise, expand into a number of unpckl*, start by extending each of
5798 // our (non-undef) elements to the full vector width with the element in the
5799 // bottom slot of the vector (which generates no code for SSE).
5800 for (unsigned i = 0; i < NumElems; ++i) {
5801 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5802 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5804 V[i] = DAG.getUNDEF(VT);
5807 // Next, we iteratively mix elements, e.g. for v4f32:
5808 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5809 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5810 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5811 unsigned EltStride = NumElems >> 1;
5812 while (EltStride != 0) {
5813 for (unsigned i = 0; i < EltStride; ++i) {
5814 // If V[i+EltStride] is undef and this is the first round of mixing,
5815 // then it is safe to just drop this shuffle: V[i] is already in the
5816 // right place, the one element (since it's the first round) being
5817 // inserted as undef can be dropped. This isn't safe for successive
5818 // rounds because they will permute elements within both vectors.
5819 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5820 EltStride == NumElems/2)
5823 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5832 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5833 // to create 256-bit vectors from two other 128-bit ones.
5834 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5836 MVT ResVT = Op.getSimpleValueType();
5838 assert((ResVT.is256BitVector() ||
5839 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5841 SDValue V1 = Op.getOperand(0);
5842 SDValue V2 = Op.getOperand(1);
5843 unsigned NumElems = ResVT.getVectorNumElements();
5844 if(ResVT.is256BitVector())
5845 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5847 if (Op.getNumOperands() == 4) {
5848 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5849 ResVT.getVectorNumElements()/2);
5850 SDValue V3 = Op.getOperand(2);
5851 SDValue V4 = Op.getOperand(3);
5852 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5853 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5855 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5858 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5859 const X86Subtarget *Subtarget,
5860 SelectionDAG & DAG) {
5862 MVT ResVT = Op.getSimpleValueType();
5863 unsigned NumOfOperands = Op.getNumOperands();
5865 assert(isPowerOf2_32(NumOfOperands) &&
5866 "Unexpected number of operands in CONCAT_VECTORS");
5868 if (NumOfOperands > 2) {
5869 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5870 ResVT.getVectorNumElements()/2);
5871 SmallVector<SDValue, 2> Ops;
5872 for (unsigned i = 0; i < NumOfOperands/2; i++)
5873 Ops.push_back(Op.getOperand(i));
5874 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5876 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
5877 Ops.push_back(Op.getOperand(i));
5878 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5879 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
5882 SDValue V1 = Op.getOperand(0);
5883 SDValue V2 = Op.getOperand(1);
5884 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
5885 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
5887 if (IsZeroV1 && IsZeroV2)
5888 return getZeroVector(ResVT, Subtarget, DAG, dl);
5890 SDValue ZeroIdx = DAG.getIntPtrConstant(0);
5891 SDValue Undef = DAG.getUNDEF(ResVT);
5892 unsigned NumElems = ResVT.getVectorNumElements();
5893 SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
5895 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
5896 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
5900 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
5901 // Zero the upper bits of V1
5902 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
5903 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
5906 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
5909 static SDValue LowerCONCAT_VECTORS(SDValue Op,
5910 const X86Subtarget *Subtarget,
5911 SelectionDAG &DAG) {
5912 MVT VT = Op.getSimpleValueType();
5913 if (VT.getVectorElementType() == MVT::i1)
5914 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
5916 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5917 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5918 Op.getNumOperands() == 4)));
5920 // AVX can use the vinsertf128 instruction to create 256-bit vectors
5921 // from two other 128-bit ones.
5923 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5924 return LowerAVXCONCAT_VECTORS(Op, DAG);
5928 //===----------------------------------------------------------------------===//
5929 // Vector shuffle lowering
5931 // This is an experimental code path for lowering vector shuffles on x86. It is
5932 // designed to handle arbitrary vector shuffles and blends, gracefully
5933 // degrading performance as necessary. It works hard to recognize idiomatic
5934 // shuffles and lower them to optimal instruction patterns without leaving
5935 // a framework that allows reasonably efficient handling of all vector shuffle
5937 //===----------------------------------------------------------------------===//
5939 /// \brief Tiny helper function to identify a no-op mask.
5941 /// This is a somewhat boring predicate function. It checks whether the mask
5942 /// array input, which is assumed to be a single-input shuffle mask of the kind
5943 /// used by the X86 shuffle instructions (not a fully general
5944 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5945 /// in-place shuffle are 'no-op's.
5946 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5947 for (int i = 0, Size = Mask.size(); i < Size; ++i)
5948 if (Mask[i] != -1 && Mask[i] != i)
5953 /// \brief Helper function to classify a mask as a single-input mask.
5955 /// This isn't a generic single-input test because in the vector shuffle
5956 /// lowering we canonicalize single inputs to be the first input operand. This
5957 /// means we can more quickly test for a single input by only checking whether
5958 /// an input from the second operand exists. We also assume that the size of
5959 /// mask corresponds to the size of the input vectors which isn't true in the
5960 /// fully general case.
5961 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5963 if (M >= (int)Mask.size())
5968 /// \brief Test whether there are elements crossing 128-bit lanes in this
5971 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5972 /// and we routinely test for these.
5973 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5974 int LaneSize = 128 / VT.getScalarSizeInBits();
5975 int Size = Mask.size();
5976 for (int i = 0; i < Size; ++i)
5977 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5982 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5984 /// This checks a shuffle mask to see if it is performing the same
5985 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5986 /// that it is also not lane-crossing. It may however involve a blend from the
5987 /// same lane of a second vector.
5989 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5990 /// non-trivial to compute in the face of undef lanes. The representation is
5991 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5992 /// entries from both V1 and V2 inputs to the wider mask.
5994 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5995 SmallVectorImpl<int> &RepeatedMask) {
5996 int LaneSize = 128 / VT.getScalarSizeInBits();
5997 RepeatedMask.resize(LaneSize, -1);
5998 int Size = Mask.size();
5999 for (int i = 0; i < Size; ++i) {
6002 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6003 // This entry crosses lanes, so there is no way to model this shuffle.
6006 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6007 if (RepeatedMask[i % LaneSize] == -1)
6008 // This is the first non-undef entry in this slot of a 128-bit lane.
6009 RepeatedMask[i % LaneSize] =
6010 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6011 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6012 // Found a mismatch with the repeated mask.
6018 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6021 /// This is a fast way to test a shuffle mask against a fixed pattern:
6023 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6025 /// It returns true if the mask is exactly as wide as the argument list, and
6026 /// each element of the mask is either -1 (signifying undef) or the value given
6027 /// in the argument.
6028 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6029 ArrayRef<int> ExpectedMask) {
6030 if (Mask.size() != ExpectedMask.size())
6033 int Size = Mask.size();
6035 // If the values are build vectors, we can look through them to find
6036 // equivalent inputs that make the shuffles equivalent.
6037 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6038 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6040 for (int i = 0; i < Size; ++i)
6041 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6042 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6043 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6044 if (!MaskBV || !ExpectedBV ||
6045 MaskBV->getOperand(Mask[i] % Size) !=
6046 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6053 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6055 /// This helper function produces an 8-bit shuffle immediate corresponding to
6056 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6057 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6060 /// NB: We rely heavily on "undef" masks preserving the input lane.
6061 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6062 SelectionDAG &DAG) {
6063 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6064 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6065 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6066 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6067 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6070 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6071 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6072 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6073 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6074 return DAG.getConstant(Imm, MVT::i8);
6077 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6079 /// This is used as a fallback approach when first class blend instructions are
6080 /// unavailable. Currently it is only suitable for integer vectors, but could
6081 /// be generalized for floating point vectors if desirable.
6082 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6083 SDValue V2, ArrayRef<int> Mask,
6084 SelectionDAG &DAG) {
6085 assert(VT.isInteger() && "Only supports integer vector types!");
6086 MVT EltVT = VT.getScalarType();
6087 int NumEltBits = EltVT.getSizeInBits();
6088 SDValue Zero = DAG.getConstant(0, EltVT);
6089 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6090 SmallVector<SDValue, 16> MaskOps;
6091 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6092 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6093 return SDValue(); // Shuffled input!
6094 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6097 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6098 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6099 // We have to cast V2 around.
6100 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6101 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6102 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6103 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6104 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6105 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6108 /// \brief Try to emit a blend instruction for a shuffle.
6110 /// This doesn't do any checks for the availability of instructions for blending
6111 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6112 /// be matched in the backend with the type given. What it does check for is
6113 /// that the shuffle mask is in fact a blend.
6114 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6115 SDValue V2, ArrayRef<int> Mask,
6116 const X86Subtarget *Subtarget,
6117 SelectionDAG &DAG) {
6118 unsigned BlendMask = 0;
6119 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6120 if (Mask[i] >= Size) {
6121 if (Mask[i] != i + Size)
6122 return SDValue(); // Shuffled V2 input!
6123 BlendMask |= 1u << i;
6126 if (Mask[i] >= 0 && Mask[i] != i)
6127 return SDValue(); // Shuffled V1 input!
6129 switch (VT.SimpleTy) {
6134 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6135 DAG.getConstant(BlendMask, MVT::i8));
6139 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6143 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6144 // that instruction.
6145 if (Subtarget->hasAVX2()) {
6146 // Scale the blend by the number of 32-bit dwords per element.
6147 int Scale = VT.getScalarSizeInBits() / 32;
6149 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6150 if (Mask[i] >= Size)
6151 for (int j = 0; j < Scale; ++j)
6152 BlendMask |= 1u << (i * Scale + j);
6154 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6155 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6156 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6157 return DAG.getNode(ISD::BITCAST, DL, VT,
6158 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6159 DAG.getConstant(BlendMask, MVT::i8)));
6163 // For integer shuffles we need to expand the mask and cast the inputs to
6164 // v8i16s prior to blending.
6165 int Scale = 8 / VT.getVectorNumElements();
6167 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6168 if (Mask[i] >= Size)
6169 for (int j = 0; j < Scale; ++j)
6170 BlendMask |= 1u << (i * Scale + j);
6172 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6173 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6174 return DAG.getNode(ISD::BITCAST, DL, VT,
6175 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6176 DAG.getConstant(BlendMask, MVT::i8)));
6180 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6181 SmallVector<int, 8> RepeatedMask;
6182 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6183 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6184 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6186 for (int i = 0; i < 8; ++i)
6187 if (RepeatedMask[i] >= 16)
6188 BlendMask |= 1u << i;
6189 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6190 DAG.getConstant(BlendMask, MVT::i8));
6196 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6197 "256-bit byte-blends require AVX2 support!");
6199 // Scale the blend by the number of bytes per element.
6200 int Scale = VT.getScalarSizeInBits() / 8;
6202 // This form of blend is always done on bytes. Compute the byte vector
6204 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6206 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6207 // mix of LLVM's code generator and the x86 backend. We tell the code
6208 // generator that boolean values in the elements of an x86 vector register
6209 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6210 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6211 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6212 // of the element (the remaining are ignored) and 0 in that high bit would
6213 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6214 // the LLVM model for boolean values in vector elements gets the relevant
6215 // bit set, it is set backwards and over constrained relative to x86's
6217 SmallVector<SDValue, 32> VSELECTMask;
6218 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6219 for (int j = 0; j < Scale; ++j)
6220 VSELECTMask.push_back(
6221 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6222 : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6224 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6225 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6227 ISD::BITCAST, DL, VT,
6228 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6229 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6234 llvm_unreachable("Not a supported integer vector type!");
6238 /// \brief Try to lower as a blend of elements from two inputs followed by
6239 /// a single-input permutation.
6241 /// This matches the pattern where we can blend elements from two inputs and
6242 /// then reduce the shuffle to a single-input permutation.
6243 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6246 SelectionDAG &DAG) {
6247 // We build up the blend mask while checking whether a blend is a viable way
6248 // to reduce the shuffle.
6249 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6250 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6252 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6256 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6258 if (BlendMask[Mask[i] % Size] == -1)
6259 BlendMask[Mask[i] % Size] = Mask[i];
6260 else if (BlendMask[Mask[i] % Size] != Mask[i])
6261 return SDValue(); // Can't blend in the needed input!
6263 PermuteMask[i] = Mask[i] % Size;
6266 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6267 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6270 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6271 /// blends and permutes.
6273 /// This matches the extremely common pattern for handling combined
6274 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6275 /// operations. It will try to pick the best arrangement of shuffles and
6277 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6281 SelectionDAG &DAG) {
6282 // Shuffle the input elements into the desired positions in V1 and V2 and
6283 // blend them together.
6284 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6285 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6286 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6287 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6288 if (Mask[i] >= 0 && Mask[i] < Size) {
6289 V1Mask[i] = Mask[i];
6291 } else if (Mask[i] >= Size) {
6292 V2Mask[i] = Mask[i] - Size;
6293 BlendMask[i] = i + Size;
6296 // Try to lower with the simpler initial blend strategy unless one of the
6297 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6298 // shuffle may be able to fold with a load or other benefit. However, when
6299 // we'll have to do 2x as many shuffles in order to achieve this, blending
6300 // first is a better strategy.
6301 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6302 if (SDValue BlendPerm =
6303 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6306 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6307 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6308 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6311 /// \brief Try to lower a vector shuffle as a byte rotation.
6313 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6314 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6315 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6316 /// try to generically lower a vector shuffle through such an pattern. It
6317 /// does not check for the profitability of lowering either as PALIGNR or
6318 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6319 /// This matches shuffle vectors that look like:
6321 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6323 /// Essentially it concatenates V1 and V2, shifts right by some number of
6324 /// elements, and takes the low elements as the result. Note that while this is
6325 /// specified as a *right shift* because x86 is little-endian, it is a *left
6326 /// rotate* of the vector lanes.
6327 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6330 const X86Subtarget *Subtarget,
6331 SelectionDAG &DAG) {
6332 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6334 int NumElts = Mask.size();
6335 int NumLanes = VT.getSizeInBits() / 128;
6336 int NumLaneElts = NumElts / NumLanes;
6338 // We need to detect various ways of spelling a rotation:
6339 // [11, 12, 13, 14, 15, 0, 1, 2]
6340 // [-1, 12, 13, 14, -1, -1, 1, -1]
6341 // [-1, -1, -1, -1, -1, -1, 1, 2]
6342 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6343 // [-1, 4, 5, 6, -1, -1, 9, -1]
6344 // [-1, 4, 5, 6, -1, -1, -1, -1]
6347 for (int l = 0; l < NumElts; l += NumLaneElts) {
6348 for (int i = 0; i < NumLaneElts; ++i) {
6349 if (Mask[l + i] == -1)
6351 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6353 // Get the mod-Size index and lane correct it.
6354 int LaneIdx = (Mask[l + i] % NumElts) - l;
6355 // Make sure it was in this lane.
6356 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6359 // Determine where a rotated vector would have started.
6360 int StartIdx = i - LaneIdx;
6362 // The identity rotation isn't interesting, stop.
6365 // If we found the tail of a vector the rotation must be the missing
6366 // front. If we found the head of a vector, it must be how much of the
6368 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6371 Rotation = CandidateRotation;
6372 else if (Rotation != CandidateRotation)
6373 // The rotations don't match, so we can't match this mask.
6376 // Compute which value this mask is pointing at.
6377 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6379 // Compute which of the two target values this index should be assigned
6380 // to. This reflects whether the high elements are remaining or the low
6381 // elements are remaining.
6382 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6384 // Either set up this value if we've not encountered it before, or check
6385 // that it remains consistent.
6388 else if (TargetV != MaskV)
6389 // This may be a rotation, but it pulls from the inputs in some
6390 // unsupported interleaving.
6395 // Check that we successfully analyzed the mask, and normalize the results.
6396 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6397 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6403 // The actual rotate instruction rotates bytes, so we need to scale the
6404 // rotation based on how many bytes are in the vector lane.
6405 int Scale = 16 / NumLaneElts;
6407 // SSSE3 targets can use the palignr instruction.
6408 if (Subtarget->hasSSSE3()) {
6409 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6410 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6411 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6412 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6414 return DAG.getNode(ISD::BITCAST, DL, VT,
6415 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6416 DAG.getConstant(Rotation * Scale, MVT::i8)));
6419 assert(VT.getSizeInBits() == 128 &&
6420 "Rotate-based lowering only supports 128-bit lowering!");
6421 assert(Mask.size() <= 16 &&
6422 "Can shuffle at most 16 bytes in a 128-bit vector!");
6424 // Default SSE2 implementation
6425 int LoByteShift = 16 - Rotation * Scale;
6426 int HiByteShift = Rotation * Scale;
6428 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6429 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6430 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6432 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6433 DAG.getConstant(LoByteShift, MVT::i8));
6434 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6435 DAG.getConstant(HiByteShift, MVT::i8));
6436 return DAG.getNode(ISD::BITCAST, DL, VT,
6437 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6440 /// \brief Compute whether each element of a shuffle is zeroable.
6442 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6443 /// Either it is an undef element in the shuffle mask, the element of the input
6444 /// referenced is undef, or the element of the input referenced is known to be
6445 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6446 /// as many lanes with this technique as possible to simplify the remaining
6448 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6449 SDValue V1, SDValue V2) {
6450 SmallBitVector Zeroable(Mask.size(), false);
6452 while (V1.getOpcode() == ISD::BITCAST)
6453 V1 = V1->getOperand(0);
6454 while (V2.getOpcode() == ISD::BITCAST)
6455 V2 = V2->getOperand(0);
6457 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6458 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6460 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6462 // Handle the easy cases.
6463 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6468 // If this is an index into a build_vector node (which has the same number
6469 // of elements), dig out the input value and use it.
6470 SDValue V = M < Size ? V1 : V2;
6471 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6474 SDValue Input = V.getOperand(M % Size);
6475 // The UNDEF opcode check really should be dead code here, but not quite
6476 // worth asserting on (it isn't invalid, just unexpected).
6477 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6484 /// \brief Try to emit a bitmask instruction for a shuffle.
6486 /// This handles cases where we can model a blend exactly as a bitmask due to
6487 /// one of the inputs being zeroable.
6488 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6489 SDValue V2, ArrayRef<int> Mask,
6490 SelectionDAG &DAG) {
6491 MVT EltVT = VT.getScalarType();
6492 int NumEltBits = EltVT.getSizeInBits();
6493 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6494 SDValue Zero = DAG.getConstant(0, IntEltVT);
6495 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6496 if (EltVT.isFloatingPoint()) {
6497 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6498 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6500 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6501 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6503 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6506 if (Mask[i] % Size != i)
6507 return SDValue(); // Not a blend.
6509 V = Mask[i] < Size ? V1 : V2;
6510 else if (V != (Mask[i] < Size ? V1 : V2))
6511 return SDValue(); // Can only let one input through the mask.
6513 VMaskOps[i] = AllOnes;
6516 return SDValue(); // No non-zeroable elements!
6518 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6519 V = DAG.getNode(VT.isFloatingPoint()
6520 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6525 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6527 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6528 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6529 /// matches elements from one of the input vectors shuffled to the left or
6530 /// right with zeroable elements 'shifted in'. It handles both the strictly
6531 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6534 /// PSHL : (little-endian) left bit shift.
6535 /// [ zz, 0, zz, 2 ]
6536 /// [ -1, 4, zz, -1 ]
6537 /// PSRL : (little-endian) right bit shift.
6539 /// [ -1, -1, 7, zz]
6540 /// PSLLDQ : (little-endian) left byte shift
6541 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6542 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6543 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6544 /// PSRLDQ : (little-endian) right byte shift
6545 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6546 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6547 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6548 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6549 SDValue V2, ArrayRef<int> Mask,
6550 SelectionDAG &DAG) {
6551 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6553 int Size = Mask.size();
6554 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6556 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6557 for (int i = 0; i < Size; i += Scale)
6558 for (int j = 0; j < Shift; ++j)
6559 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6565 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6566 for (int i = 0; i != Size; i += Scale) {
6567 unsigned Pos = Left ? i + Shift : i;
6568 unsigned Low = Left ? i : i + Shift;
6569 unsigned Len = Scale - Shift;
6570 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6571 Low + (V == V1 ? 0 : Size)))
6575 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6576 bool ByteShift = ShiftEltBits > 64;
6577 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6578 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6579 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6581 // Normalize the scale for byte shifts to still produce an i64 element
6583 Scale = ByteShift ? Scale / 2 : Scale;
6585 // We need to round trip through the appropriate type for the shift.
6586 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6587 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6588 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6589 "Illegal integer vector type");
6590 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6592 V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6593 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6596 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6597 // keep doubling the size of the integer elements up to that. We can
6598 // then shift the elements of the integer vector by whole multiples of
6599 // their width within the elements of the larger integer vector. Test each
6600 // multiple to see if we can find a match with the moved element indices
6601 // and that the shifted in elements are all zeroable.
6602 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6603 for (int Shift = 1; Shift != Scale; ++Shift)
6604 for (bool Left : {true, false})
6605 if (CheckZeros(Shift, Scale, Left))
6606 for (SDValue V : {V1, V2})
6607 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6614 /// \brief Lower a vector shuffle as a zero or any extension.
6616 /// Given a specific number of elements, element bit width, and extension
6617 /// stride, produce either a zero or any extension based on the available
6618 /// features of the subtarget.
6619 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6620 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6621 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6622 assert(Scale > 1 && "Need a scale to extend.");
6623 int NumElements = VT.getVectorNumElements();
6624 int EltBits = VT.getScalarSizeInBits();
6625 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6626 "Only 8, 16, and 32 bit elements can be extended.");
6627 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6629 // Found a valid zext mask! Try various lowering strategies based on the
6630 // input type and available ISA extensions.
6631 if (Subtarget->hasSSE41()) {
6632 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6633 NumElements / Scale);
6634 return DAG.getNode(ISD::BITCAST, DL, VT,
6635 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6638 // For any extends we can cheat for larger element sizes and use shuffle
6639 // instructions that can fold with a load and/or copy.
6640 if (AnyExt && EltBits == 32) {
6641 int PSHUFDMask[4] = {0, -1, 1, -1};
6643 ISD::BITCAST, DL, VT,
6644 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6645 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6646 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6648 if (AnyExt && EltBits == 16 && Scale > 2) {
6649 int PSHUFDMask[4] = {0, -1, 0, -1};
6650 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6651 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6652 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6653 int PSHUFHWMask[4] = {1, -1, -1, -1};
6655 ISD::BITCAST, DL, VT,
6656 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6657 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6658 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6661 // If this would require more than 2 unpack instructions to expand, use
6662 // pshufb when available. We can only use more than 2 unpack instructions
6663 // when zero extending i8 elements which also makes it easier to use pshufb.
6664 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6665 assert(NumElements == 16 && "Unexpected byte vector width!");
6666 SDValue PSHUFBMask[16];
6667 for (int i = 0; i < 16; ++i)
6669 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6670 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6671 return DAG.getNode(ISD::BITCAST, DL, VT,
6672 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6673 DAG.getNode(ISD::BUILD_VECTOR, DL,
6674 MVT::v16i8, PSHUFBMask)));
6677 // Otherwise emit a sequence of unpacks.
6679 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6680 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6681 : getZeroVector(InputVT, Subtarget, DAG, DL);
6682 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6683 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6687 } while (Scale > 1);
6688 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6691 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6693 /// This routine will try to do everything in its power to cleverly lower
6694 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6695 /// check for the profitability of this lowering, it tries to aggressively
6696 /// match this pattern. It will use all of the micro-architectural details it
6697 /// can to emit an efficient lowering. It handles both blends with all-zero
6698 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6699 /// masking out later).
6701 /// The reason we have dedicated lowering for zext-style shuffles is that they
6702 /// are both incredibly common and often quite performance sensitive.
6703 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6704 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6705 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6706 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6708 int Bits = VT.getSizeInBits();
6709 int NumElements = VT.getVectorNumElements();
6710 assert(VT.getScalarSizeInBits() <= 32 &&
6711 "Exceeds 32-bit integer zero extension limit");
6712 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6714 // Define a helper function to check a particular ext-scale and lower to it if
6716 auto Lower = [&](int Scale) -> SDValue {
6719 for (int i = 0; i < NumElements; ++i) {
6721 continue; // Valid anywhere but doesn't tell us anything.
6722 if (i % Scale != 0) {
6723 // Each of the extended elements need to be zeroable.
6727 // We no longer are in the anyext case.
6732 // Each of the base elements needs to be consecutive indices into the
6733 // same input vector.
6734 SDValue V = Mask[i] < NumElements ? V1 : V2;
6737 else if (InputV != V)
6738 return SDValue(); // Flip-flopping inputs.
6740 if (Mask[i] % NumElements != i / Scale)
6741 return SDValue(); // Non-consecutive strided elements.
6744 // If we fail to find an input, we have a zero-shuffle which should always
6745 // have already been handled.
6746 // FIXME: Maybe handle this here in case during blending we end up with one?
6750 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6751 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6754 // The widest scale possible for extending is to a 64-bit integer.
6755 assert(Bits % 64 == 0 &&
6756 "The number of bits in a vector must be divisible by 64 on x86!");
6757 int NumExtElements = Bits / 64;
6759 // Each iteration, try extending the elements half as much, but into twice as
6761 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6762 assert(NumElements % NumExtElements == 0 &&
6763 "The input vector size must be divisible by the extended size.");
6764 if (SDValue V = Lower(NumElements / NumExtElements))
6768 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6772 // Returns one of the source operands if the shuffle can be reduced to a
6773 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6774 auto CanZExtLowHalf = [&]() {
6775 for (int i = NumElements / 2; i != NumElements; ++i)
6778 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6780 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6785 if (SDValue V = CanZExtLowHalf()) {
6786 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6787 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6788 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6791 // No viable ext lowering found.
6795 /// \brief Try to get a scalar value for a specific element of a vector.
6797 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6798 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6799 SelectionDAG &DAG) {
6800 MVT VT = V.getSimpleValueType();
6801 MVT EltVT = VT.getVectorElementType();
6802 while (V.getOpcode() == ISD::BITCAST)
6803 V = V.getOperand(0);
6804 // If the bitcasts shift the element size, we can't extract an equivalent
6806 MVT NewVT = V.getSimpleValueType();
6807 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6810 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6811 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6812 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6817 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6819 /// This is particularly important because the set of instructions varies
6820 /// significantly based on whether the operand is a load or not.
6821 static bool isShuffleFoldableLoad(SDValue V) {
6822 while (V.getOpcode() == ISD::BITCAST)
6823 V = V.getOperand(0);
6825 return ISD::isNON_EXTLoad(V.getNode());
6828 /// \brief Try to lower insertion of a single element into a zero vector.
6830 /// This is a common pattern that we have especially efficient patterns to lower
6831 /// across all subtarget feature sets.
6832 static SDValue lowerVectorShuffleAsElementInsertion(
6833 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6834 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6835 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6837 MVT EltVT = VT.getVectorElementType();
6839 int V2Index = std::find_if(Mask.begin(), Mask.end(),
6840 [&Mask](int M) { return M >= (int)Mask.size(); }) -
6842 bool IsV1Zeroable = true;
6843 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6844 if (i != V2Index && !Zeroable[i]) {
6845 IsV1Zeroable = false;
6849 // Check for a single input from a SCALAR_TO_VECTOR node.
6850 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6851 // all the smarts here sunk into that routine. However, the current
6852 // lowering of BUILD_VECTOR makes that nearly impossible until the old
6853 // vector shuffle lowering is dead.
6854 if (SDValue V2S = getScalarValueForVectorElement(
6855 V2, Mask[V2Index] - Mask.size(), DAG)) {
6856 // We need to zext the scalar if it is smaller than an i32.
6857 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6858 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6859 // Using zext to expand a narrow element won't work for non-zero
6864 // Zero-extend directly to i32.
6866 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6868 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6869 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6870 EltVT == MVT::i16) {
6871 // Either not inserting from the low element of the input or the input
6872 // element size is too small to use VZEXT_MOVL to clear the high bits.
6876 if (!IsV1Zeroable) {
6877 // If V1 can't be treated as a zero vector we have fewer options to lower
6878 // this. We can't support integer vectors or non-zero targets cheaply, and
6879 // the V1 elements can't be permuted in any way.
6880 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6881 if (!VT.isFloatingPoint() || V2Index != 0)
6883 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6884 V1Mask[V2Index] = -1;
6885 if (!isNoopShuffleMask(V1Mask))
6887 // This is essentially a special case blend operation, but if we have
6888 // general purpose blend operations, they are always faster. Bail and let
6889 // the rest of the lowering handle these as blends.
6890 if (Subtarget->hasSSE41())
6893 // Otherwise, use MOVSD or MOVSS.
6894 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6895 "Only two types of floating point element types to handle!");
6896 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6900 // This lowering only works for the low element with floating point vectors.
6901 if (VT.isFloatingPoint() && V2Index != 0)
6904 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6906 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6909 // If we have 4 or fewer lanes we can cheaply shuffle the element into
6910 // the desired position. Otherwise it is more efficient to do a vector
6911 // shift left. We know that we can do a vector shift left because all
6912 // the inputs are zero.
6913 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6914 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6915 V2Shuffle[V2Index] = 0;
6916 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6918 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6920 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6922 V2Index * EltVT.getSizeInBits()/8,
6923 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6924 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6930 /// \brief Try to lower broadcast of a single element.
6932 /// For convenience, this code also bundles all of the subtarget feature set
6933 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6934 /// a convenient way to factor it out.
6935 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6937 const X86Subtarget *Subtarget,
6938 SelectionDAG &DAG) {
6939 if (!Subtarget->hasAVX())
6941 if (VT.isInteger() && !Subtarget->hasAVX2())
6944 // Check that the mask is a broadcast.
6945 int BroadcastIdx = -1;
6947 if (M >= 0 && BroadcastIdx == -1)
6949 else if (M >= 0 && M != BroadcastIdx)
6952 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6953 "a sorted mask where the broadcast "
6956 // Go up the chain of (vector) values to try and find a scalar load that
6957 // we can combine with the broadcast.
6959 switch (V.getOpcode()) {
6960 case ISD::CONCAT_VECTORS: {
6961 int OperandSize = Mask.size() / V.getNumOperands();
6962 V = V.getOperand(BroadcastIdx / OperandSize);
6963 BroadcastIdx %= OperandSize;
6967 case ISD::INSERT_SUBVECTOR: {
6968 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6969 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6973 int BeginIdx = (int)ConstantIdx->getZExtValue();
6975 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6976 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6977 BroadcastIdx -= BeginIdx;
6988 // Check if this is a broadcast of a scalar. We special case lowering
6989 // for scalars so that we can more effectively fold with loads.
6990 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6991 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6992 V = V.getOperand(BroadcastIdx);
6994 // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6996 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6998 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6999 // We can't broadcast from a vector register w/o AVX2, and we can only
7000 // broadcast from the zero-element of a vector register.
7004 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7007 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7008 // INSERTPS when the V1 elements are already in the correct locations
7009 // because otherwise we can just always use two SHUFPS instructions which
7010 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7011 // perform INSERTPS if a single V1 element is out of place and all V2
7012 // elements are zeroable.
7013 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7015 SelectionDAG &DAG) {
7016 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7017 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7018 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7019 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7021 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7024 int V1DstIndex = -1;
7025 int V2DstIndex = -1;
7026 bool V1UsedInPlace = false;
7028 for (int i = 0; i < 4; ++i) {
7029 // Synthesize a zero mask from the zeroable elements (includes undefs).
7035 // Flag if we use any V1 inputs in place.
7037 V1UsedInPlace = true;
7041 // We can only insert a single non-zeroable element.
7042 if (V1DstIndex != -1 || V2DstIndex != -1)
7046 // V1 input out of place for insertion.
7049 // V2 input for insertion.
7054 // Don't bother if we have no (non-zeroable) element for insertion.
7055 if (V1DstIndex == -1 && V2DstIndex == -1)
7058 // Determine element insertion src/dst indices. The src index is from the
7059 // start of the inserted vector, not the start of the concatenated vector.
7060 unsigned V2SrcIndex = 0;
7061 if (V1DstIndex != -1) {
7062 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7063 // and don't use the original V2 at all.
7064 V2SrcIndex = Mask[V1DstIndex];
7065 V2DstIndex = V1DstIndex;
7068 V2SrcIndex = Mask[V2DstIndex] - 4;
7071 // If no V1 inputs are used in place, then the result is created only from
7072 // the zero mask and the V2 insertion - so remove V1 dependency.
7074 V1 = DAG.getUNDEF(MVT::v4f32);
7076 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7077 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7079 // Insert the V2 element into the desired position.
7081 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7082 DAG.getConstant(InsertPSMask, MVT::i8));
7085 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7086 /// UNPCK instruction.
7088 /// This specifically targets cases where we end up with alternating between
7089 /// the two inputs, and so can permute them into something that feeds a single
7090 /// UNPCK instruction. Note that this routine only targets integer vectors
7091 /// because for floating point vectors we have a generalized SHUFPS lowering
7092 /// strategy that handles everything that doesn't *exactly* match an unpack,
7093 /// making this clever lowering unnecessary.
7094 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7095 SDValue V2, ArrayRef<int> Mask,
7096 SelectionDAG &DAG) {
7097 assert(!VT.isFloatingPoint() &&
7098 "This routine only supports integer vectors.");
7099 assert(!isSingleInputShuffleMask(Mask) &&
7100 "This routine should only be used when blending two inputs.");
7101 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7103 int Size = Mask.size();
7105 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7106 return M >= 0 && M % Size < Size / 2;
7108 int NumHiInputs = std::count_if(
7109 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7111 bool UnpackLo = NumLoInputs >= NumHiInputs;
7113 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7114 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7115 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7117 for (int i = 0; i < Size; ++i) {
7121 // Each element of the unpack contains Scale elements from this mask.
7122 int UnpackIdx = i / Scale;
7124 // We only handle the case where V1 feeds the first slots of the unpack.
7125 // We rely on canonicalization to ensure this is the case.
7126 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7129 // Setup the mask for this input. The indexing is tricky as we have to
7130 // handle the unpack stride.
7131 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7132 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7136 // If we will have to shuffle both inputs to use the unpack, check whether
7137 // we can just unpack first and shuffle the result. If so, skip this unpack.
7138 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7139 !isNoopShuffleMask(V2Mask))
7142 // Shuffle the inputs into place.
7143 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7144 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7146 // Cast the inputs to the type we will use to unpack them.
7147 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7148 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7150 // Unpack the inputs and cast the result back to the desired type.
7151 return DAG.getNode(ISD::BITCAST, DL, VT,
7152 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7153 DL, UnpackVT, V1, V2));
7156 // We try each unpack from the largest to the smallest to try and find one
7157 // that fits this mask.
7158 int OrigNumElements = VT.getVectorNumElements();
7159 int OrigScalarSize = VT.getScalarSizeInBits();
7160 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7161 int Scale = ScalarSize / OrigScalarSize;
7162 int NumElements = OrigNumElements / Scale;
7163 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7164 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7168 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7170 if (NumLoInputs == 0 || NumHiInputs == 0) {
7171 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7172 "We have to have *some* inputs!");
7173 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7175 // FIXME: We could consider the total complexity of the permute of each
7176 // possible unpacking. Or at the least we should consider how many
7177 // half-crossings are created.
7178 // FIXME: We could consider commuting the unpacks.
7180 SmallVector<int, 32> PermMask;
7181 PermMask.assign(Size, -1);
7182 for (int i = 0; i < Size; ++i) {
7186 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7189 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7191 return DAG.getVectorShuffle(
7192 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7194 DAG.getUNDEF(VT), PermMask);
7200 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7202 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7203 /// support for floating point shuffles but not integer shuffles. These
7204 /// instructions will incur a domain crossing penalty on some chips though so
7205 /// it is better to avoid lowering through this for integer vectors where
7207 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7208 const X86Subtarget *Subtarget,
7209 SelectionDAG &DAG) {
7211 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7212 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7213 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7215 ArrayRef<int> Mask = SVOp->getMask();
7216 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7218 if (isSingleInputShuffleMask(Mask)) {
7219 // Use low duplicate instructions for masks that match their pattern.
7220 if (Subtarget->hasSSE3())
7221 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7222 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7224 // Straight shuffle of a single input vector. Simulate this by using the
7225 // single input as both of the "inputs" to this instruction..
7226 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7228 if (Subtarget->hasAVX()) {
7229 // If we have AVX, we can use VPERMILPS which will allow folding a load
7230 // into the shuffle.
7231 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7232 DAG.getConstant(SHUFPDMask, MVT::i8));
7235 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7236 DAG.getConstant(SHUFPDMask, MVT::i8));
7238 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7239 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7241 // If we have a single input, insert that into V1 if we can do so cheaply.
7242 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7243 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7244 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7246 // Try inverting the insertion since for v2 masks it is easy to do and we
7247 // can't reliably sort the mask one way or the other.
7248 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7249 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7250 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7251 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7255 // Try to use one of the special instruction patterns to handle two common
7256 // blend patterns if a zero-blend above didn't work.
7257 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7258 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7259 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7260 // We can either use a special instruction to load over the low double or
7261 // to move just the low double.
7263 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7265 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7267 if (Subtarget->hasSSE41())
7268 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7272 // Use dedicated unpack instructions for masks that match their pattern.
7273 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7274 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7275 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7276 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7278 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7279 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7280 DAG.getConstant(SHUFPDMask, MVT::i8));
7283 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7285 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7286 /// the integer unit to minimize domain crossing penalties. However, for blends
7287 /// it falls back to the floating point shuffle operation with appropriate bit
7289 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7290 const X86Subtarget *Subtarget,
7291 SelectionDAG &DAG) {
7293 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7294 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7295 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7296 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7297 ArrayRef<int> Mask = SVOp->getMask();
7298 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7300 if (isSingleInputShuffleMask(Mask)) {
7301 // Check for being able to broadcast a single element.
7302 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7303 Mask, Subtarget, DAG))
7306 // Straight shuffle of a single input vector. For everything from SSE2
7307 // onward this has a single fast instruction with no scary immediates.
7308 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7309 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7310 int WidenedMask[4] = {
7311 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7312 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7314 ISD::BITCAST, DL, MVT::v2i64,
7315 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7316 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7318 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7319 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7320 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7321 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7323 // If we have a blend of two PACKUS operations an the blend aligns with the
7324 // low and half halves, we can just merge the PACKUS operations. This is
7325 // particularly important as it lets us merge shuffles that this routine itself
7327 auto GetPackNode = [](SDValue V) {
7328 while (V.getOpcode() == ISD::BITCAST)
7329 V = V.getOperand(0);
7331 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7333 if (SDValue V1Pack = GetPackNode(V1))
7334 if (SDValue V2Pack = GetPackNode(V2))
7335 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7336 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7337 Mask[0] == 0 ? V1Pack.getOperand(0)
7338 : V1Pack.getOperand(1),
7339 Mask[1] == 2 ? V2Pack.getOperand(0)
7340 : V2Pack.getOperand(1)));
7342 // Try to use shift instructions.
7344 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7347 // When loading a scalar and then shuffling it into a vector we can often do
7348 // the insertion cheaply.
7349 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7350 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7352 // Try inverting the insertion since for v2 masks it is easy to do and we
7353 // can't reliably sort the mask one way or the other.
7354 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7355 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7356 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7359 // We have different paths for blend lowering, but they all must use the
7360 // *exact* same predicate.
7361 bool IsBlendSupported = Subtarget->hasSSE41();
7362 if (IsBlendSupported)
7363 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7367 // Use dedicated unpack instructions for masks that match their pattern.
7368 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7369 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7370 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7371 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7373 // Try to use byte rotation instructions.
7374 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7375 if (Subtarget->hasSSSE3())
7376 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7377 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7380 // If we have direct support for blends, we should lower by decomposing into
7381 // a permute. That will be faster than the domain cross.
7382 if (IsBlendSupported)
7383 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7386 // We implement this with SHUFPD which is pretty lame because it will likely
7387 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7388 // However, all the alternatives are still more cycles and newer chips don't
7389 // have this problem. It would be really nice if x86 had better shuffles here.
7390 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7391 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7392 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7393 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7396 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7398 /// This is used to disable more specialized lowerings when the shufps lowering
7399 /// will happen to be efficient.
7400 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7401 // This routine only handles 128-bit shufps.
7402 assert(Mask.size() == 4 && "Unsupported mask size!");
7404 // To lower with a single SHUFPS we need to have the low half and high half
7405 // each requiring a single input.
7406 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7408 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7414 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7416 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7417 /// It makes no assumptions about whether this is the *best* lowering, it simply
7419 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7420 ArrayRef<int> Mask, SDValue V1,
7421 SDValue V2, SelectionDAG &DAG) {
7422 SDValue LowV = V1, HighV = V2;
7423 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7426 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7428 if (NumV2Elements == 1) {
7430 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7433 // Compute the index adjacent to V2Index and in the same half by toggling
7435 int V2AdjIndex = V2Index ^ 1;
7437 if (Mask[V2AdjIndex] == -1) {
7438 // Handles all the cases where we have a single V2 element and an undef.
7439 // This will only ever happen in the high lanes because we commute the
7440 // vector otherwise.
7442 std::swap(LowV, HighV);
7443 NewMask[V2Index] -= 4;
7445 // Handle the case where the V2 element ends up adjacent to a V1 element.
7446 // To make this work, blend them together as the first step.
7447 int V1Index = V2AdjIndex;
7448 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7449 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7450 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7452 // Now proceed to reconstruct the final blend as we have the necessary
7453 // high or low half formed.
7460 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7461 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7463 } else if (NumV2Elements == 2) {
7464 if (Mask[0] < 4 && Mask[1] < 4) {
7465 // Handle the easy case where we have V1 in the low lanes and V2 in the
7469 } else if (Mask[2] < 4 && Mask[3] < 4) {
7470 // We also handle the reversed case because this utility may get called
7471 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7472 // arrange things in the right direction.
7478 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7479 // trying to place elements directly, just blend them and set up the final
7480 // shuffle to place them.
7482 // The first two blend mask elements are for V1, the second two are for
7484 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7485 Mask[2] < 4 ? Mask[2] : Mask[3],
7486 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7487 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7488 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7489 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7491 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7494 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7495 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7496 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7497 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7500 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7501 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7504 /// \brief Lower 4-lane 32-bit floating point shuffles.
7506 /// Uses instructions exclusively from the floating point unit to minimize
7507 /// domain crossing penalties, as these are sufficient to implement all v4f32
7509 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7510 const X86Subtarget *Subtarget,
7511 SelectionDAG &DAG) {
7513 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7514 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7515 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7516 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7517 ArrayRef<int> Mask = SVOp->getMask();
7518 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7521 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7523 if (NumV2Elements == 0) {
7524 // Check for being able to broadcast a single element.
7525 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7526 Mask, Subtarget, DAG))
7529 // Use even/odd duplicate instructions for masks that match their pattern.
7530 if (Subtarget->hasSSE3()) {
7531 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7532 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7533 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7534 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7537 if (Subtarget->hasAVX()) {
7538 // If we have AVX, we can use VPERMILPS which will allow folding a load
7539 // into the shuffle.
7540 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7541 getV4X86ShuffleImm8ForMask(Mask, DAG));
7544 // Otherwise, use a straight shuffle of a single input vector. We pass the
7545 // input vector to both operands to simulate this with a SHUFPS.
7546 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7547 getV4X86ShuffleImm8ForMask(Mask, DAG));
7550 // There are special ways we can lower some single-element blends. However, we
7551 // have custom ways we can lower more complex single-element blends below that
7552 // we defer to if both this and BLENDPS fail to match, so restrict this to
7553 // when the V2 input is targeting element 0 of the mask -- that is the fast
7555 if (NumV2Elements == 1 && Mask[0] >= 4)
7556 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7557 Mask, Subtarget, DAG))
7560 if (Subtarget->hasSSE41()) {
7561 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7565 // Use INSERTPS if we can complete the shuffle efficiently.
7566 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7569 if (!isSingleSHUFPSMask(Mask))
7570 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7571 DL, MVT::v4f32, V1, V2, Mask, DAG))
7575 // Use dedicated unpack instructions for masks that match their pattern.
7576 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7577 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7578 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7579 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7580 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7581 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7582 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7583 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7585 // Otherwise fall back to a SHUFPS lowering strategy.
7586 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7589 /// \brief Lower 4-lane i32 vector shuffles.
7591 /// We try to handle these with integer-domain shuffles where we can, but for
7592 /// blends we use the floating point domain blend instructions.
7593 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7594 const X86Subtarget *Subtarget,
7595 SelectionDAG &DAG) {
7597 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7598 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7599 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7600 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7601 ArrayRef<int> Mask = SVOp->getMask();
7602 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7604 // Whenever we can lower this as a zext, that instruction is strictly faster
7605 // than any alternative. It also allows us to fold memory operands into the
7606 // shuffle in many cases.
7607 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7608 Mask, Subtarget, DAG))
7612 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7614 if (NumV2Elements == 0) {
7615 // Check for being able to broadcast a single element.
7616 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7617 Mask, Subtarget, DAG))
7620 // Straight shuffle of a single input vector. For everything from SSE2
7621 // onward this has a single fast instruction with no scary immediates.
7622 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7623 // but we aren't actually going to use the UNPCK instruction because doing
7624 // so prevents folding a load into this instruction or making a copy.
7625 const int UnpackLoMask[] = {0, 0, 1, 1};
7626 const int UnpackHiMask[] = {2, 2, 3, 3};
7627 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7628 Mask = UnpackLoMask;
7629 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7630 Mask = UnpackHiMask;
7632 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7633 getV4X86ShuffleImm8ForMask(Mask, DAG));
7636 // Try to use shift instructions.
7638 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7641 // There are special ways we can lower some single-element blends.
7642 if (NumV2Elements == 1)
7643 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7644 Mask, Subtarget, DAG))
7647 // We have different paths for blend lowering, but they all must use the
7648 // *exact* same predicate.
7649 bool IsBlendSupported = Subtarget->hasSSE41();
7650 if (IsBlendSupported)
7651 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7655 if (SDValue Masked =
7656 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7659 // Use dedicated unpack instructions for masks that match their pattern.
7660 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7661 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7662 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7663 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7664 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7665 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7666 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7667 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7669 // Try to use byte rotation instructions.
7670 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7671 if (Subtarget->hasSSSE3())
7672 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7673 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7676 // If we have direct support for blends, we should lower by decomposing into
7677 // a permute. That will be faster than the domain cross.
7678 if (IsBlendSupported)
7679 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7682 // Try to lower by permuting the inputs into an unpack instruction.
7683 if (SDValue Unpack =
7684 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7687 // We implement this with SHUFPS because it can blend from two vectors.
7688 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7689 // up the inputs, bypassing domain shift penalties that we would encur if we
7690 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7692 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7693 DAG.getVectorShuffle(
7695 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7696 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7699 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7700 /// shuffle lowering, and the most complex part.
7702 /// The lowering strategy is to try to form pairs of input lanes which are
7703 /// targeted at the same half of the final vector, and then use a dword shuffle
7704 /// to place them onto the right half, and finally unpack the paired lanes into
7705 /// their final position.
7707 /// The exact breakdown of how to form these dword pairs and align them on the
7708 /// correct sides is really tricky. See the comments within the function for
7709 /// more of the details.
7711 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7712 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7713 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7714 /// vector, form the analogous 128-bit 8-element Mask.
7715 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7716 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7717 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7718 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7719 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7721 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7722 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7723 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7725 SmallVector<int, 4> LoInputs;
7726 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7727 [](int M) { return M >= 0; });
7728 std::sort(LoInputs.begin(), LoInputs.end());
7729 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7730 SmallVector<int, 4> HiInputs;
7731 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7732 [](int M) { return M >= 0; });
7733 std::sort(HiInputs.begin(), HiInputs.end());
7734 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7736 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7737 int NumHToL = LoInputs.size() - NumLToL;
7739 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7740 int NumHToH = HiInputs.size() - NumLToH;
7741 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7742 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7743 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7744 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7746 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7747 // such inputs we can swap two of the dwords across the half mark and end up
7748 // with <=2 inputs to each half in each half. Once there, we can fall through
7749 // to the generic code below. For example:
7751 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7752 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7754 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7755 // and an existing 2-into-2 on the other half. In this case we may have to
7756 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7757 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7758 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7759 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7760 // half than the one we target for fixing) will be fixed when we re-enter this
7761 // path. We will also combine away any sequence of PSHUFD instructions that
7762 // result into a single instruction. Here is an example of the tricky case:
7764 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7765 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7767 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7769 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7770 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7772 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7773 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7775 // The result is fine to be handled by the generic logic.
7776 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7777 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7778 int AOffset, int BOffset) {
7779 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7780 "Must call this with A having 3 or 1 inputs from the A half.");
7781 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7782 "Must call this with B having 1 or 3 inputs from the B half.");
7783 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7784 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7786 // Compute the index of dword with only one word among the three inputs in
7787 // a half by taking the sum of the half with three inputs and subtracting
7788 // the sum of the actual three inputs. The difference is the remaining
7791 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7792 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7793 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7794 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7795 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7796 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7797 int TripleNonInputIdx =
7798 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7799 TripleDWord = TripleNonInputIdx / 2;
7801 // We use xor with one to compute the adjacent DWord to whichever one the
7803 OneInputDWord = (OneInput / 2) ^ 1;
7805 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7806 // and BToA inputs. If there is also such a problem with the BToB and AToB
7807 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7808 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7809 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7810 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7811 // Compute how many inputs will be flipped by swapping these DWords. We
7813 // to balance this to ensure we don't form a 3-1 shuffle in the other
7815 int NumFlippedAToBInputs =
7816 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7817 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7818 int NumFlippedBToBInputs =
7819 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7820 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7821 if ((NumFlippedAToBInputs == 1 &&
7822 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7823 (NumFlippedBToBInputs == 1 &&
7824 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7825 // We choose whether to fix the A half or B half based on whether that
7826 // half has zero flipped inputs. At zero, we may not be able to fix it
7827 // with that half. We also bias towards fixing the B half because that
7828 // will more commonly be the high half, and we have to bias one way.
7829 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7830 ArrayRef<int> Inputs) {
7831 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7832 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7833 PinnedIdx ^ 1) != Inputs.end();
7834 // Determine whether the free index is in the flipped dword or the
7835 // unflipped dword based on where the pinned index is. We use this bit
7836 // in an xor to conditionally select the adjacent dword.
7837 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7838 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7839 FixFreeIdx) != Inputs.end();
7840 if (IsFixIdxInput == IsFixFreeIdxInput)
7842 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7843 FixFreeIdx) != Inputs.end();
7844 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7845 "We need to be changing the number of flipped inputs!");
7846 int PSHUFHalfMask[] = {0, 1, 2, 3};
7847 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7848 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7850 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7853 if (M != -1 && M == FixIdx)
7855 else if (M != -1 && M == FixFreeIdx)
7858 if (NumFlippedBToBInputs != 0) {
7860 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7861 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7863 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7865 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7866 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7871 int PSHUFDMask[] = {0, 1, 2, 3};
7872 PSHUFDMask[ADWord] = BDWord;
7873 PSHUFDMask[BDWord] = ADWord;
7874 V = DAG.getNode(ISD::BITCAST, DL, VT,
7875 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7876 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7877 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7879 // Adjust the mask to match the new locations of A and B.
7881 if (M != -1 && M/2 == ADWord)
7882 M = 2 * BDWord + M % 2;
7883 else if (M != -1 && M/2 == BDWord)
7884 M = 2 * ADWord + M % 2;
7886 // Recurse back into this routine to re-compute state now that this isn't
7887 // a 3 and 1 problem.
7888 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7891 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7892 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7893 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7894 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7896 // At this point there are at most two inputs to the low and high halves from
7897 // each half. That means the inputs can always be grouped into dwords and
7898 // those dwords can then be moved to the correct half with a dword shuffle.
7899 // We use at most one low and one high word shuffle to collect these paired
7900 // inputs into dwords, and finally a dword shuffle to place them.
7901 int PSHUFLMask[4] = {-1, -1, -1, -1};
7902 int PSHUFHMask[4] = {-1, -1, -1, -1};
7903 int PSHUFDMask[4] = {-1, -1, -1, -1};
7905 // First fix the masks for all the inputs that are staying in their
7906 // original halves. This will then dictate the targets of the cross-half
7908 auto fixInPlaceInputs =
7909 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7910 MutableArrayRef<int> SourceHalfMask,
7911 MutableArrayRef<int> HalfMask, int HalfOffset) {
7912 if (InPlaceInputs.empty())
7914 if (InPlaceInputs.size() == 1) {
7915 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7916 InPlaceInputs[0] - HalfOffset;
7917 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7920 if (IncomingInputs.empty()) {
7921 // Just fix all of the in place inputs.
7922 for (int Input : InPlaceInputs) {
7923 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7924 PSHUFDMask[Input / 2] = Input / 2;
7929 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7930 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7931 InPlaceInputs[0] - HalfOffset;
7932 // Put the second input next to the first so that they are packed into
7933 // a dword. We find the adjacent index by toggling the low bit.
7934 int AdjIndex = InPlaceInputs[0] ^ 1;
7935 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7936 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7937 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7939 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7940 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7942 // Now gather the cross-half inputs and place them into a free dword of
7943 // their target half.
7944 // FIXME: This operation could almost certainly be simplified dramatically to
7945 // look more like the 3-1 fixing operation.
7946 auto moveInputsToRightHalf = [&PSHUFDMask](
7947 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7948 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7949 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7951 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7952 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7954 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7956 int LowWord = Word & ~1;
7957 int HighWord = Word | 1;
7958 return isWordClobbered(SourceHalfMask, LowWord) ||
7959 isWordClobbered(SourceHalfMask, HighWord);
7962 if (IncomingInputs.empty())
7965 if (ExistingInputs.empty()) {
7966 // Map any dwords with inputs from them into the right half.
7967 for (int Input : IncomingInputs) {
7968 // If the source half mask maps over the inputs, turn those into
7969 // swaps and use the swapped lane.
7970 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7971 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7972 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7973 Input - SourceOffset;
7974 // We have to swap the uses in our half mask in one sweep.
7975 for (int &M : HalfMask)
7976 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7978 else if (M == Input)
7979 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7981 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7982 Input - SourceOffset &&
7983 "Previous placement doesn't match!");
7985 // Note that this correctly re-maps both when we do a swap and when
7986 // we observe the other side of the swap above. We rely on that to
7987 // avoid swapping the members of the input list directly.
7988 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7991 // Map the input's dword into the correct half.
7992 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7993 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7995 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7997 "Previous placement doesn't match!");
8000 // And just directly shift any other-half mask elements to be same-half
8001 // as we will have mirrored the dword containing the element into the
8002 // same position within that half.
8003 for (int &M : HalfMask)
8004 if (M >= SourceOffset && M < SourceOffset + 4) {
8005 M = M - SourceOffset + DestOffset;
8006 assert(M >= 0 && "This should never wrap below zero!");
8011 // Ensure we have the input in a viable dword of its current half. This
8012 // is particularly tricky because the original position may be clobbered
8013 // by inputs being moved and *staying* in that half.
8014 if (IncomingInputs.size() == 1) {
8015 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8016 int InputFixed = std::find(std::begin(SourceHalfMask),
8017 std::end(SourceHalfMask), -1) -
8018 std::begin(SourceHalfMask) + SourceOffset;
8019 SourceHalfMask[InputFixed - SourceOffset] =
8020 IncomingInputs[0] - SourceOffset;
8021 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8023 IncomingInputs[0] = InputFixed;
8025 } else if (IncomingInputs.size() == 2) {
8026 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8027 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8028 // We have two non-adjacent or clobbered inputs we need to extract from
8029 // the source half. To do this, we need to map them into some adjacent
8030 // dword slot in the source mask.
8031 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8032 IncomingInputs[1] - SourceOffset};
8034 // If there is a free slot in the source half mask adjacent to one of
8035 // the inputs, place the other input in it. We use (Index XOR 1) to
8036 // compute an adjacent index.
8037 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8038 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8039 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8040 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8041 InputsFixed[1] = InputsFixed[0] ^ 1;
8042 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8043 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8044 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8045 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8046 InputsFixed[0] = InputsFixed[1] ^ 1;
8047 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8048 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8049 // The two inputs are in the same DWord but it is clobbered and the
8050 // adjacent DWord isn't used at all. Move both inputs to the free
8052 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8053 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8054 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8055 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8057 // The only way we hit this point is if there is no clobbering
8058 // (because there are no off-half inputs to this half) and there is no
8059 // free slot adjacent to one of the inputs. In this case, we have to
8060 // swap an input with a non-input.
8061 for (int i = 0; i < 4; ++i)
8062 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8063 "We can't handle any clobbers here!");
8064 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8065 "Cannot have adjacent inputs here!");
8067 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8068 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8070 // We also have to update the final source mask in this case because
8071 // it may need to undo the above swap.
8072 for (int &M : FinalSourceHalfMask)
8073 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8074 M = InputsFixed[1] + SourceOffset;
8075 else if (M == InputsFixed[1] + SourceOffset)
8076 M = (InputsFixed[0] ^ 1) + SourceOffset;
8078 InputsFixed[1] = InputsFixed[0] ^ 1;
8081 // Point everything at the fixed inputs.
8082 for (int &M : HalfMask)
8083 if (M == IncomingInputs[0])
8084 M = InputsFixed[0] + SourceOffset;
8085 else if (M == IncomingInputs[1])
8086 M = InputsFixed[1] + SourceOffset;
8088 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8089 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8092 llvm_unreachable("Unhandled input size!");
8095 // Now hoist the DWord down to the right half.
8096 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8097 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8098 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8099 for (int &M : HalfMask)
8100 for (int Input : IncomingInputs)
8102 M = FreeDWord * 2 + Input % 2;
8104 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8105 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8106 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8107 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8109 // Now enact all the shuffles we've computed to move the inputs into their
8111 if (!isNoopShuffleMask(PSHUFLMask))
8112 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8113 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8114 if (!isNoopShuffleMask(PSHUFHMask))
8115 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8116 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8117 if (!isNoopShuffleMask(PSHUFDMask))
8118 V = DAG.getNode(ISD::BITCAST, DL, VT,
8119 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8120 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8121 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8123 // At this point, each half should contain all its inputs, and we can then
8124 // just shuffle them into their final position.
8125 assert(std::count_if(LoMask.begin(), LoMask.end(),
8126 [](int M) { return M >= 4; }) == 0 &&
8127 "Failed to lift all the high half inputs to the low mask!");
8128 assert(std::count_if(HiMask.begin(), HiMask.end(),
8129 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8130 "Failed to lift all the low half inputs to the high mask!");
8132 // Do a half shuffle for the low mask.
8133 if (!isNoopShuffleMask(LoMask))
8134 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8135 getV4X86ShuffleImm8ForMask(LoMask, DAG));
8137 // Do a half shuffle with the high mask after shifting its values down.
8138 for (int &M : HiMask)
8141 if (!isNoopShuffleMask(HiMask))
8142 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8143 getV4X86ShuffleImm8ForMask(HiMask, DAG));
8148 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8149 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8150 SDValue V2, ArrayRef<int> Mask,
8151 SelectionDAG &DAG, bool &V1InUse,
8153 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8159 int Size = Mask.size();
8160 int Scale = 16 / Size;
8161 for (int i = 0; i < 16; ++i) {
8162 if (Mask[i / Scale] == -1) {
8163 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8165 const int ZeroMask = 0x80;
8166 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8168 int V2Idx = Mask[i / Scale] < Size
8170 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8171 if (Zeroable[i / Scale])
8172 V1Idx = V2Idx = ZeroMask;
8173 V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8174 V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8175 V1InUse |= (ZeroMask != V1Idx);
8176 V2InUse |= (ZeroMask != V2Idx);
8181 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8182 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8183 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8185 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8186 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8187 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8189 // If we need shuffled inputs from both, blend the two.
8191 if (V1InUse && V2InUse)
8192 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8194 V = V1InUse ? V1 : V2;
8196 // Cast the result back to the correct type.
8197 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8200 /// \brief Generic lowering of 8-lane i16 shuffles.
8202 /// This handles both single-input shuffles and combined shuffle/blends with
8203 /// two inputs. The single input shuffles are immediately delegated to
8204 /// a dedicated lowering routine.
8206 /// The blends are lowered in one of three fundamental ways. If there are few
8207 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8208 /// of the input is significantly cheaper when lowered as an interleaving of
8209 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8210 /// halves of the inputs separately (making them have relatively few inputs)
8211 /// and then concatenate them.
8212 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8213 const X86Subtarget *Subtarget,
8214 SelectionDAG &DAG) {
8216 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8217 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8218 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8219 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8220 ArrayRef<int> OrigMask = SVOp->getMask();
8221 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8222 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8223 MutableArrayRef<int> Mask(MaskStorage);
8225 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8227 // Whenever we can lower this as a zext, that instruction is strictly faster
8228 // than any alternative.
8229 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8230 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8233 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8235 auto isV2 = [](int M) { return M >= 8; };
8237 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8239 if (NumV2Inputs == 0) {
8240 // Check for being able to broadcast a single element.
8241 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8242 Mask, Subtarget, DAG))
8245 // Try to use shift instructions.
8247 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8250 // Use dedicated unpack instructions for masks that match their pattern.
8251 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8252 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8253 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8254 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8256 // Try to use byte rotation instructions.
8257 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8258 Mask, Subtarget, DAG))
8261 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8265 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8266 "All single-input shuffles should be canonicalized to be V1-input "
8269 // Try to use shift instructions.
8271 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8274 // There are special ways we can lower some single-element blends.
8275 if (NumV2Inputs == 1)
8276 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8277 Mask, Subtarget, DAG))
8280 // We have different paths for blend lowering, but they all must use the
8281 // *exact* same predicate.
8282 bool IsBlendSupported = Subtarget->hasSSE41();
8283 if (IsBlendSupported)
8284 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8288 if (SDValue Masked =
8289 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8292 // Use dedicated unpack instructions for masks that match their pattern.
8293 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8294 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8295 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8296 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8298 // Try to use byte rotation instructions.
8299 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8300 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8303 if (SDValue BitBlend =
8304 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8307 if (SDValue Unpack =
8308 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8311 // If we can't directly blend but can use PSHUFB, that will be better as it
8312 // can both shuffle and set up the inefficient blend.
8313 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8314 bool V1InUse, V2InUse;
8315 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8319 // We can always bit-blend if we have to so the fallback strategy is to
8320 // decompose into single-input permutes and blends.
8321 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8325 /// \brief Check whether a compaction lowering can be done by dropping even
8326 /// elements and compute how many times even elements must be dropped.
8328 /// This handles shuffles which take every Nth element where N is a power of
8329 /// two. Example shuffle masks:
8331 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8332 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8333 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8334 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8335 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8336 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8338 /// Any of these lanes can of course be undef.
8340 /// This routine only supports N <= 3.
8341 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8344 /// \returns N above, or the number of times even elements must be dropped if
8345 /// there is such a number. Otherwise returns zero.
8346 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8347 // Figure out whether we're looping over two inputs or just one.
8348 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8350 // The modulus for the shuffle vector entries is based on whether this is
8351 // a single input or not.
8352 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8353 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8354 "We should only be called with masks with a power-of-2 size!");
8356 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8358 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8359 // and 2^3 simultaneously. This is because we may have ambiguity with
8360 // partially undef inputs.
8361 bool ViableForN[3] = {true, true, true};
8363 for (int i = 0, e = Mask.size(); i < e; ++i) {
8364 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8369 bool IsAnyViable = false;
8370 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8371 if (ViableForN[j]) {
8374 // The shuffle mask must be equal to (i * 2^N) % M.
8375 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8378 ViableForN[j] = false;
8380 // Early exit if we exhaust the possible powers of two.
8385 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8389 // Return 0 as there is no viable power of two.
8393 /// \brief Generic lowering of v16i8 shuffles.
8395 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8396 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8397 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8398 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8400 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8401 const X86Subtarget *Subtarget,
8402 SelectionDAG &DAG) {
8404 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8405 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8406 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8407 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8408 ArrayRef<int> Mask = SVOp->getMask();
8409 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8411 // Try to use shift instructions.
8413 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8416 // Try to use byte rotation instructions.
8417 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8418 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8421 // Try to use a zext lowering.
8422 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8423 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8427 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8429 // For single-input shuffles, there are some nicer lowering tricks we can use.
8430 if (NumV2Elements == 0) {
8431 // Check for being able to broadcast a single element.
8432 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8433 Mask, Subtarget, DAG))
8436 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8437 // Notably, this handles splat and partial-splat shuffles more efficiently.
8438 // However, it only makes sense if the pre-duplication shuffle simplifies
8439 // things significantly. Currently, this means we need to be able to
8440 // express the pre-duplication shuffle as an i16 shuffle.
8442 // FIXME: We should check for other patterns which can be widened into an
8443 // i16 shuffle as well.
8444 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8445 for (int i = 0; i < 16; i += 2)
8446 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8451 auto tryToWidenViaDuplication = [&]() -> SDValue {
8452 if (!canWidenViaDuplication(Mask))
8454 SmallVector<int, 4> LoInputs;
8455 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8456 [](int M) { return M >= 0 && M < 8; });
8457 std::sort(LoInputs.begin(), LoInputs.end());
8458 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8460 SmallVector<int, 4> HiInputs;
8461 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8462 [](int M) { return M >= 8; });
8463 std::sort(HiInputs.begin(), HiInputs.end());
8464 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8467 bool TargetLo = LoInputs.size() >= HiInputs.size();
8468 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8469 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8471 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8472 SmallDenseMap<int, int, 8> LaneMap;
8473 for (int I : InPlaceInputs) {
8474 PreDupI16Shuffle[I/2] = I/2;
8477 int j = TargetLo ? 0 : 4, je = j + 4;
8478 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8479 // Check if j is already a shuffle of this input. This happens when
8480 // there are two adjacent bytes after we move the low one.
8481 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8482 // If we haven't yet mapped the input, search for a slot into which
8484 while (j < je && PreDupI16Shuffle[j] != -1)
8488 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8491 // Map this input with the i16 shuffle.
8492 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8495 // Update the lane map based on the mapping we ended up with.
8496 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8499 ISD::BITCAST, DL, MVT::v16i8,
8500 DAG.getVectorShuffle(MVT::v8i16, DL,
8501 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8502 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8504 // Unpack the bytes to form the i16s that will be shuffled into place.
8505 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8506 MVT::v16i8, V1, V1);
8508 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8509 for (int i = 0; i < 16; ++i)
8510 if (Mask[i] != -1) {
8511 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8512 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8513 if (PostDupI16Shuffle[i / 2] == -1)
8514 PostDupI16Shuffle[i / 2] = MappedMask;
8516 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8517 "Conflicting entrties in the original shuffle!");
8520 ISD::BITCAST, DL, MVT::v16i8,
8521 DAG.getVectorShuffle(MVT::v8i16, DL,
8522 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8523 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8525 if (SDValue V = tryToWidenViaDuplication())
8529 // Use dedicated unpack instructions for masks that match their pattern.
8530 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8531 0, 16, 1, 17, 2, 18, 3, 19,
8533 4, 20, 5, 21, 6, 22, 7, 23}))
8534 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8535 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8536 8, 24, 9, 25, 10, 26, 11, 27,
8538 12, 28, 13, 29, 14, 30, 15, 31}))
8539 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8541 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8542 // with PSHUFB. It is important to do this before we attempt to generate any
8543 // blends but after all of the single-input lowerings. If the single input
8544 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8545 // want to preserve that and we can DAG combine any longer sequences into
8546 // a PSHUFB in the end. But once we start blending from multiple inputs,
8547 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8548 // and there are *very* few patterns that would actually be faster than the
8549 // PSHUFB approach because of its ability to zero lanes.
8551 // FIXME: The only exceptions to the above are blends which are exact
8552 // interleavings with direct instructions supporting them. We currently don't
8553 // handle those well here.
8554 if (Subtarget->hasSSSE3()) {
8555 bool V1InUse = false;
8556 bool V2InUse = false;
8558 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8559 DAG, V1InUse, V2InUse);
8561 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8562 // do so. This avoids using them to handle blends-with-zero which is
8563 // important as a single pshufb is significantly faster for that.
8564 if (V1InUse && V2InUse) {
8565 if (Subtarget->hasSSE41())
8566 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8567 Mask, Subtarget, DAG))
8570 // We can use an unpack to do the blending rather than an or in some
8571 // cases. Even though the or may be (very minorly) more efficient, we
8572 // preference this lowering because there are common cases where part of
8573 // the complexity of the shuffles goes away when we do the final blend as
8575 // FIXME: It might be worth trying to detect if the unpack-feeding
8576 // shuffles will both be pshufb, in which case we shouldn't bother with
8578 if (SDValue Unpack =
8579 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8586 // There are special ways we can lower some single-element blends.
8587 if (NumV2Elements == 1)
8588 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8589 Mask, Subtarget, DAG))
8592 if (SDValue BitBlend =
8593 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8596 // Check whether a compaction lowering can be done. This handles shuffles
8597 // which take every Nth element for some even N. See the helper function for
8600 // We special case these as they can be particularly efficiently handled with
8601 // the PACKUSB instruction on x86 and they show up in common patterns of
8602 // rearranging bytes to truncate wide elements.
8603 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8604 // NumEvenDrops is the power of two stride of the elements. Another way of
8605 // thinking about it is that we need to drop the even elements this many
8606 // times to get the original input.
8607 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8609 // First we need to zero all the dropped bytes.
8610 assert(NumEvenDrops <= 3 &&
8611 "No support for dropping even elements more than 3 times.");
8612 // We use the mask type to pick which bytes are preserved based on how many
8613 // elements are dropped.
8614 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8615 SDValue ByteClearMask =
8616 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8617 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8618 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8620 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8622 // Now pack things back together.
8623 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8624 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8625 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8626 for (int i = 1; i < NumEvenDrops; ++i) {
8627 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8628 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8634 // Handle multi-input cases by blending single-input shuffles.
8635 if (NumV2Elements > 0)
8636 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8639 // The fallback path for single-input shuffles widens this into two v8i16
8640 // vectors with unpacks, shuffles those, and then pulls them back together
8644 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8645 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8646 for (int i = 0; i < 16; ++i)
8648 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8650 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8652 SDValue VLoHalf, VHiHalf;
8653 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8654 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8656 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8657 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8658 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8659 [](int M) { return M >= 0 && M % 2 == 1; })) {
8660 // Use a mask to drop the high bytes.
8661 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8662 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8663 DAG.getConstant(0x00FF, MVT::v8i16));
8665 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8666 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8668 // Squash the masks to point directly into VLoHalf.
8669 for (int &M : LoBlendMask)
8672 for (int &M : HiBlendMask)
8676 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8677 // VHiHalf so that we can blend them as i16s.
8678 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8679 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8680 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8681 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8684 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8685 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8687 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8690 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8692 /// This routine breaks down the specific type of 128-bit shuffle and
8693 /// dispatches to the lowering routines accordingly.
8694 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8695 MVT VT, const X86Subtarget *Subtarget,
8696 SelectionDAG &DAG) {
8697 switch (VT.SimpleTy) {
8699 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8701 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8703 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8705 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8707 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8709 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8712 llvm_unreachable("Unimplemented!");
8716 /// \brief Helper function to test whether a shuffle mask could be
8717 /// simplified by widening the elements being shuffled.
8719 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8720 /// leaves it in an unspecified state.
8722 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8723 /// shuffle masks. The latter have the special property of a '-2' representing
8724 /// a zero-ed lane of a vector.
8725 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8726 SmallVectorImpl<int> &WidenedMask) {
8727 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8728 // If both elements are undef, its trivial.
8729 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8730 WidenedMask.push_back(SM_SentinelUndef);
8734 // Check for an undef mask and a mask value properly aligned to fit with
8735 // a pair of values. If we find such a case, use the non-undef mask's value.
8736 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8737 WidenedMask.push_back(Mask[i + 1] / 2);
8740 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8741 WidenedMask.push_back(Mask[i] / 2);
8745 // When zeroing, we need to spread the zeroing across both lanes to widen.
8746 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8747 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8748 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8749 WidenedMask.push_back(SM_SentinelZero);
8755 // Finally check if the two mask values are adjacent and aligned with
8757 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8758 WidenedMask.push_back(Mask[i] / 2);
8762 // Otherwise we can't safely widen the elements used in this shuffle.
8765 assert(WidenedMask.size() == Mask.size() / 2 &&
8766 "Incorrect size of mask after widening the elements!");
8771 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8773 /// This routine just extracts two subvectors, shuffles them independently, and
8774 /// then concatenates them back together. This should work effectively with all
8775 /// AVX vector shuffle types.
8776 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8777 SDValue V2, ArrayRef<int> Mask,
8778 SelectionDAG &DAG) {
8779 assert(VT.getSizeInBits() >= 256 &&
8780 "Only for 256-bit or wider vector shuffles!");
8781 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8782 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8784 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8785 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8787 int NumElements = VT.getVectorNumElements();
8788 int SplitNumElements = NumElements / 2;
8789 MVT ScalarVT = VT.getScalarType();
8790 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8792 // Rather than splitting build-vectors, just build two narrower build
8793 // vectors. This helps shuffling with splats and zeros.
8794 auto SplitVector = [&](SDValue V) {
8795 while (V.getOpcode() == ISD::BITCAST)
8796 V = V->getOperand(0);
8798 MVT OrigVT = V.getSimpleValueType();
8799 int OrigNumElements = OrigVT.getVectorNumElements();
8800 int OrigSplitNumElements = OrigNumElements / 2;
8801 MVT OrigScalarVT = OrigVT.getScalarType();
8802 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8806 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8808 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8809 DAG.getIntPtrConstant(0));
8810 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8811 DAG.getIntPtrConstant(OrigSplitNumElements));
8814 SmallVector<SDValue, 16> LoOps, HiOps;
8815 for (int i = 0; i < OrigSplitNumElements; ++i) {
8816 LoOps.push_back(BV->getOperand(i));
8817 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8819 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8820 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8822 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8823 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8826 SDValue LoV1, HiV1, LoV2, HiV2;
8827 std::tie(LoV1, HiV1) = SplitVector(V1);
8828 std::tie(LoV2, HiV2) = SplitVector(V2);
8830 // Now create two 4-way blends of these half-width vectors.
8831 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8832 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8833 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8834 for (int i = 0; i < SplitNumElements; ++i) {
8835 int M = HalfMask[i];
8836 if (M >= NumElements) {
8837 if (M >= NumElements + SplitNumElements)
8841 V2BlendMask.push_back(M - NumElements);
8842 V1BlendMask.push_back(-1);
8843 BlendMask.push_back(SplitNumElements + i);
8844 } else if (M >= 0) {
8845 if (M >= SplitNumElements)
8849 V2BlendMask.push_back(-1);
8850 V1BlendMask.push_back(M);
8851 BlendMask.push_back(i);
8853 V2BlendMask.push_back(-1);
8854 V1BlendMask.push_back(-1);
8855 BlendMask.push_back(-1);
8859 // Because the lowering happens after all combining takes place, we need to
8860 // manually combine these blend masks as much as possible so that we create
8861 // a minimal number of high-level vector shuffle nodes.
8863 // First try just blending the halves of V1 or V2.
8864 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8865 return DAG.getUNDEF(SplitVT);
8866 if (!UseLoV2 && !UseHiV2)
8867 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8868 if (!UseLoV1 && !UseHiV1)
8869 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8871 SDValue V1Blend, V2Blend;
8872 if (UseLoV1 && UseHiV1) {
8874 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8876 // We only use half of V1 so map the usage down into the final blend mask.
8877 V1Blend = UseLoV1 ? LoV1 : HiV1;
8878 for (int i = 0; i < SplitNumElements; ++i)
8879 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8880 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8882 if (UseLoV2 && UseHiV2) {
8884 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8886 // We only use half of V2 so map the usage down into the final blend mask.
8887 V2Blend = UseLoV2 ? LoV2 : HiV2;
8888 for (int i = 0; i < SplitNumElements; ++i)
8889 if (BlendMask[i] >= SplitNumElements)
8890 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8892 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8894 SDValue Lo = HalfBlend(LoMask);
8895 SDValue Hi = HalfBlend(HiMask);
8896 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8899 /// \brief Either split a vector in halves or decompose the shuffles and the
8902 /// This is provided as a good fallback for many lowerings of non-single-input
8903 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8904 /// between splitting the shuffle into 128-bit components and stitching those
8905 /// back together vs. extracting the single-input shuffles and blending those
8907 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8908 SDValue V2, ArrayRef<int> Mask,
8909 SelectionDAG &DAG) {
8910 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8911 "lower single-input shuffles as it "
8912 "could then recurse on itself.");
8913 int Size = Mask.size();
8915 // If this can be modeled as a broadcast of two elements followed by a blend,
8916 // prefer that lowering. This is especially important because broadcasts can
8917 // often fold with memory operands.
8918 auto DoBothBroadcast = [&] {
8919 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8922 if (V2BroadcastIdx == -1)
8923 V2BroadcastIdx = M - Size;
8924 else if (M - Size != V2BroadcastIdx)
8926 } else if (M >= 0) {
8927 if (V1BroadcastIdx == -1)
8929 else if (M != V1BroadcastIdx)
8934 if (DoBothBroadcast())
8935 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8938 // If the inputs all stem from a single 128-bit lane of each input, then we
8939 // split them rather than blending because the split will decompose to
8940 // unusually few instructions.
8941 int LaneCount = VT.getSizeInBits() / 128;
8942 int LaneSize = Size / LaneCount;
8943 SmallBitVector LaneInputs[2];
8944 LaneInputs[0].resize(LaneCount, false);
8945 LaneInputs[1].resize(LaneCount, false);
8946 for (int i = 0; i < Size; ++i)
8948 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8949 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8950 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8952 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8953 // that the decomposed single-input shuffles don't end up here.
8954 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8957 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8958 /// a permutation and blend of those lanes.
8960 /// This essentially blends the out-of-lane inputs to each lane into the lane
8961 /// from a permuted copy of the vector. This lowering strategy results in four
8962 /// instructions in the worst case for a single-input cross lane shuffle which
8963 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8964 /// of. Special cases for each particular shuffle pattern should be handled
8965 /// prior to trying this lowering.
8966 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8967 SDValue V1, SDValue V2,
8969 SelectionDAG &DAG) {
8970 // FIXME: This should probably be generalized for 512-bit vectors as well.
8971 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8972 int LaneSize = Mask.size() / 2;
8974 // If there are only inputs from one 128-bit lane, splitting will in fact be
8975 // less expensive. The flags track whether the given lane contains an element
8976 // that crosses to another lane.
8977 bool LaneCrossing[2] = {false, false};
8978 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8979 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8980 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8981 if (!LaneCrossing[0] || !LaneCrossing[1])
8982 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8984 if (isSingleInputShuffleMask(Mask)) {
8985 SmallVector<int, 32> FlippedBlendMask;
8986 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8987 FlippedBlendMask.push_back(
8988 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8990 : Mask[i] % LaneSize +
8991 (i / LaneSize) * LaneSize + Size));
8993 // Flip the vector, and blend the results which should now be in-lane. The
8994 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8995 // 5 for the high source. The value 3 selects the high half of source 2 and
8996 // the value 2 selects the low half of source 2. We only use source 2 to
8997 // allow folding it into a memory operand.
8998 unsigned PERMMask = 3 | 2 << 4;
8999 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9000 V1, DAG.getConstant(PERMMask, MVT::i8));
9001 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9004 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9005 // will be handled by the above logic and a blend of the results, much like
9006 // other patterns in AVX.
9007 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9010 /// \brief Handle lowering 2-lane 128-bit shuffles.
9011 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9012 SDValue V2, ArrayRef<int> Mask,
9013 const X86Subtarget *Subtarget,
9014 SelectionDAG &DAG) {
9015 // Blends are faster and handle all the non-lane-crossing cases.
9016 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9020 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9021 VT.getVectorNumElements() / 2);
9022 // Check for patterns which can be matched with a single insert of a 128-bit
9024 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9025 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9026 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9027 DAG.getIntPtrConstant(0));
9028 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9029 OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9030 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9032 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9033 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9034 DAG.getIntPtrConstant(0));
9035 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9036 DAG.getIntPtrConstant(2));
9037 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9040 // Otherwise form a 128-bit permutation.
9041 // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9042 int MaskLO = Mask[0];
9043 if (MaskLO == SM_SentinelUndef)
9044 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9046 int MaskHI = Mask[2];
9047 if (MaskHI == SM_SentinelUndef)
9048 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9050 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9051 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9052 DAG.getConstant(PermMask, MVT::i8));
9055 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9056 /// shuffling each lane.
9058 /// This will only succeed when the result of fixing the 128-bit lanes results
9059 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9060 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9061 /// the lane crosses early and then use simpler shuffles within each lane.
9063 /// FIXME: It might be worthwhile at some point to support this without
9064 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9065 /// in x86 only floating point has interesting non-repeating shuffles, and even
9066 /// those are still *marginally* more expensive.
9067 static SDValue lowerVectorShuffleByMerging128BitLanes(
9068 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9069 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9070 assert(!isSingleInputShuffleMask(Mask) &&
9071 "This is only useful with multiple inputs.");
9073 int Size = Mask.size();
9074 int LaneSize = 128 / VT.getScalarSizeInBits();
9075 int NumLanes = Size / LaneSize;
9076 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9078 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9079 // check whether the in-128-bit lane shuffles share a repeating pattern.
9080 SmallVector<int, 4> Lanes;
9081 Lanes.resize(NumLanes, -1);
9082 SmallVector<int, 4> InLaneMask;
9083 InLaneMask.resize(LaneSize, -1);
9084 for (int i = 0; i < Size; ++i) {
9088 int j = i / LaneSize;
9091 // First entry we've seen for this lane.
9092 Lanes[j] = Mask[i] / LaneSize;
9093 } else if (Lanes[j] != Mask[i] / LaneSize) {
9094 // This doesn't match the lane selected previously!
9098 // Check that within each lane we have a consistent shuffle mask.
9099 int k = i % LaneSize;
9100 if (InLaneMask[k] < 0) {
9101 InLaneMask[k] = Mask[i] % LaneSize;
9102 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9103 // This doesn't fit a repeating in-lane mask.
9108 // First shuffle the lanes into place.
9109 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9110 VT.getSizeInBits() / 64);
9111 SmallVector<int, 8> LaneMask;
9112 LaneMask.resize(NumLanes * 2, -1);
9113 for (int i = 0; i < NumLanes; ++i)
9114 if (Lanes[i] >= 0) {
9115 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9116 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9119 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9120 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9121 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9123 // Cast it back to the type we actually want.
9124 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9126 // Now do a simple shuffle that isn't lane crossing.
9127 SmallVector<int, 8> NewMask;
9128 NewMask.resize(Size, -1);
9129 for (int i = 0; i < Size; ++i)
9131 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9132 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9133 "Must not introduce lane crosses at this point!");
9135 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9138 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9141 /// This returns true if the elements from a particular input are already in the
9142 /// slot required by the given mask and require no permutation.
9143 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9144 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9145 int Size = Mask.size();
9146 for (int i = 0; i < Size; ++i)
9147 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9153 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9155 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9156 /// isn't available.
9157 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9158 const X86Subtarget *Subtarget,
9159 SelectionDAG &DAG) {
9161 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9162 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9163 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9164 ArrayRef<int> Mask = SVOp->getMask();
9165 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9167 SmallVector<int, 4> WidenedMask;
9168 if (canWidenShuffleElements(Mask, WidenedMask))
9169 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9172 if (isSingleInputShuffleMask(Mask)) {
9173 // Check for being able to broadcast a single element.
9174 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9175 Mask, Subtarget, DAG))
9178 // Use low duplicate instructions for masks that match their pattern.
9179 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9180 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9182 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9183 // Non-half-crossing single input shuffles can be lowerid with an
9184 // interleaved permutation.
9185 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9186 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9187 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9188 DAG.getConstant(VPERMILPMask, MVT::i8));
9191 // With AVX2 we have direct support for this permutation.
9192 if (Subtarget->hasAVX2())
9193 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9194 getV4X86ShuffleImm8ForMask(Mask, DAG));
9196 // Otherwise, fall back.
9197 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9201 // X86 has dedicated unpack instructions that can handle specific blend
9202 // operations: UNPCKH and UNPCKL.
9203 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9204 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9205 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9206 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9207 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9208 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9209 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9210 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9212 // If we have a single input to the zero element, insert that into V1 if we
9213 // can do so cheaply.
9215 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9216 if (NumV2Elements == 1 && Mask[0] >= 4)
9217 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9218 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9221 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9225 // Check if the blend happens to exactly fit that of SHUFPD.
9226 if ((Mask[0] == -1 || Mask[0] < 2) &&
9227 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9228 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9229 (Mask[3] == -1 || Mask[3] >= 6)) {
9230 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9231 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9232 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9233 DAG.getConstant(SHUFPDMask, MVT::i8));
9235 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9236 (Mask[1] == -1 || Mask[1] < 2) &&
9237 (Mask[2] == -1 || Mask[2] >= 6) &&
9238 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9239 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9240 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9241 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9242 DAG.getConstant(SHUFPDMask, MVT::i8));
9245 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9246 // shuffle. However, if we have AVX2 and either inputs are already in place,
9247 // we will be able to shuffle even across lanes the other input in a single
9248 // instruction so skip this pattern.
9249 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9250 isShuffleMaskInputInPlace(1, Mask))))
9251 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9252 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9255 // If we have AVX2 then we always want to lower with a blend because an v4 we
9256 // can fully permute the elements.
9257 if (Subtarget->hasAVX2())
9258 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9261 // Otherwise fall back on generic lowering.
9262 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9265 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9267 /// This routine is only called when we have AVX2 and thus a reasonable
9268 /// instruction set for v4i64 shuffling..
9269 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9270 const X86Subtarget *Subtarget,
9271 SelectionDAG &DAG) {
9273 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9274 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9275 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9276 ArrayRef<int> Mask = SVOp->getMask();
9277 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9278 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9280 SmallVector<int, 4> WidenedMask;
9281 if (canWidenShuffleElements(Mask, WidenedMask))
9282 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9285 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9289 // Check for being able to broadcast a single element.
9290 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9291 Mask, Subtarget, DAG))
9294 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9295 // use lower latency instructions that will operate on both 128-bit lanes.
9296 SmallVector<int, 2> RepeatedMask;
9297 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9298 if (isSingleInputShuffleMask(Mask)) {
9299 int PSHUFDMask[] = {-1, -1, -1, -1};
9300 for (int i = 0; i < 2; ++i)
9301 if (RepeatedMask[i] >= 0) {
9302 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9303 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9306 ISD::BITCAST, DL, MVT::v4i64,
9307 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9308 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9309 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9313 // AVX2 provides a direct instruction for permuting a single input across
9315 if (isSingleInputShuffleMask(Mask))
9316 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9317 getV4X86ShuffleImm8ForMask(Mask, DAG));
9319 // Try to use shift instructions.
9321 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9324 // Use dedicated unpack instructions for masks that match their pattern.
9325 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9326 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9327 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9328 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9329 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9330 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9331 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9332 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9334 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9335 // shuffle. However, if we have AVX2 and either inputs are already in place,
9336 // we will be able to shuffle even across lanes the other input in a single
9337 // instruction so skip this pattern.
9338 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9339 isShuffleMaskInputInPlace(1, Mask))))
9340 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9341 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9344 // Otherwise fall back on generic blend lowering.
9345 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9349 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9351 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9352 /// isn't available.
9353 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9354 const X86Subtarget *Subtarget,
9355 SelectionDAG &DAG) {
9357 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9358 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9359 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9360 ArrayRef<int> Mask = SVOp->getMask();
9361 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9363 // If we have a single input to the zero element, insert that into V1 if we
9364 // can do so cheaply.
9366 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 8; });
9367 if (NumV2Elements == 1 && Mask[0] >= 8)
9368 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9369 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9372 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9376 // Check for being able to broadcast a single element.
9377 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9378 Mask, Subtarget, DAG))
9381 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9382 // options to efficiently lower the shuffle.
9383 SmallVector<int, 4> RepeatedMask;
9384 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9385 assert(RepeatedMask.size() == 4 &&
9386 "Repeated masks must be half the mask width!");
9388 // Use even/odd duplicate instructions for masks that match their pattern.
9389 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9390 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9391 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9392 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9394 if (isSingleInputShuffleMask(Mask))
9395 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9396 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9398 // Use dedicated unpack instructions for masks that match their pattern.
9399 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9400 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9401 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9402 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9403 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9404 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9405 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9406 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9408 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9409 // have already handled any direct blends. We also need to squash the
9410 // repeated mask into a simulated v4f32 mask.
9411 for (int i = 0; i < 4; ++i)
9412 if (RepeatedMask[i] >= 8)
9413 RepeatedMask[i] -= 4;
9414 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9417 // If we have a single input shuffle with different shuffle patterns in the
9418 // two 128-bit lanes use the variable mask to VPERMILPS.
9419 if (isSingleInputShuffleMask(Mask)) {
9420 SDValue VPermMask[8];
9421 for (int i = 0; i < 8; ++i)
9422 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9423 : DAG.getConstant(Mask[i], MVT::i32);
9424 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9426 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9427 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9429 if (Subtarget->hasAVX2())
9430 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9431 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9432 DAG.getNode(ISD::BUILD_VECTOR, DL,
9433 MVT::v8i32, VPermMask)),
9436 // Otherwise, fall back.
9437 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9441 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9443 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9444 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9447 // If we have AVX2 then we always want to lower with a blend because at v8 we
9448 // can fully permute the elements.
9449 if (Subtarget->hasAVX2())
9450 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9453 // Otherwise fall back on generic lowering.
9454 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9457 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9459 /// This routine is only called when we have AVX2 and thus a reasonable
9460 /// instruction set for v8i32 shuffling..
9461 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9462 const X86Subtarget *Subtarget,
9463 SelectionDAG &DAG) {
9465 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9466 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9467 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9468 ArrayRef<int> Mask = SVOp->getMask();
9469 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9470 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9472 // Whenever we can lower this as a zext, that instruction is strictly faster
9473 // than any alternative. It also allows us to fold memory operands into the
9474 // shuffle in many cases.
9475 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9476 Mask, Subtarget, DAG))
9479 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9483 // Check for being able to broadcast a single element.
9484 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9485 Mask, Subtarget, DAG))
9488 // If the shuffle mask is repeated in each 128-bit lane we can use more
9489 // efficient instructions that mirror the shuffles across the two 128-bit
9491 SmallVector<int, 4> RepeatedMask;
9492 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9493 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9494 if (isSingleInputShuffleMask(Mask))
9495 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9496 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9498 // Use dedicated unpack instructions for masks that match their pattern.
9499 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9500 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9501 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9502 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9503 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9504 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9505 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9506 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9509 // Try to use shift instructions.
9511 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9514 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9515 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9518 // If the shuffle patterns aren't repeated but it is a single input, directly
9519 // generate a cross-lane VPERMD instruction.
9520 if (isSingleInputShuffleMask(Mask)) {
9521 SDValue VPermMask[8];
9522 for (int i = 0; i < 8; ++i)
9523 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9524 : DAG.getConstant(Mask[i], MVT::i32);
9526 X86ISD::VPERMV, DL, MVT::v8i32,
9527 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9530 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9532 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9533 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9536 // Otherwise fall back on generic blend lowering.
9537 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9541 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9543 /// This routine is only called when we have AVX2 and thus a reasonable
9544 /// instruction set for v16i16 shuffling..
9545 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9546 const X86Subtarget *Subtarget,
9547 SelectionDAG &DAG) {
9549 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9550 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9551 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9552 ArrayRef<int> Mask = SVOp->getMask();
9553 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9554 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9556 // Whenever we can lower this as a zext, that instruction is strictly faster
9557 // than any alternative. It also allows us to fold memory operands into the
9558 // shuffle in many cases.
9559 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9560 Mask, Subtarget, DAG))
9563 // Check for being able to broadcast a single element.
9564 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9565 Mask, Subtarget, DAG))
9568 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9572 // Use dedicated unpack instructions for masks that match their pattern.
9573 if (isShuffleEquivalent(V1, V2, Mask,
9574 {// First 128-bit lane:
9575 0, 16, 1, 17, 2, 18, 3, 19,
9576 // Second 128-bit lane:
9577 8, 24, 9, 25, 10, 26, 11, 27}))
9578 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9579 if (isShuffleEquivalent(V1, V2, Mask,
9580 {// First 128-bit lane:
9581 4, 20, 5, 21, 6, 22, 7, 23,
9582 // Second 128-bit lane:
9583 12, 28, 13, 29, 14, 30, 15, 31}))
9584 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9586 // Try to use shift instructions.
9588 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9591 // Try to use byte rotation instructions.
9592 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9593 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9596 if (isSingleInputShuffleMask(Mask)) {
9597 // There are no generalized cross-lane shuffle operations available on i16
9599 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9600 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9603 SmallVector<int, 8> RepeatedMask;
9604 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9605 // As this is a single-input shuffle, the repeated mask should be
9606 // a strictly valid v8i16 mask that we can pass through to the v8i16
9607 // lowering to handle even the v16 case.
9608 return lowerV8I16GeneralSingleInputVectorShuffle(
9609 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9612 SDValue PSHUFBMask[32];
9613 for (int i = 0; i < 16; ++i) {
9614 if (Mask[i] == -1) {
9615 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9619 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9620 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9621 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9622 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9625 ISD::BITCAST, DL, MVT::v16i16,
9627 X86ISD::PSHUFB, DL, MVT::v32i8,
9628 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9629 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9632 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9634 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9635 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9638 // Otherwise fall back on generic lowering.
9639 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9642 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9644 /// This routine is only called when we have AVX2 and thus a reasonable
9645 /// instruction set for v32i8 shuffling..
9646 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9647 const X86Subtarget *Subtarget,
9648 SelectionDAG &DAG) {
9650 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9651 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9652 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9653 ArrayRef<int> Mask = SVOp->getMask();
9654 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9655 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9657 // Whenever we can lower this as a zext, that instruction is strictly faster
9658 // than any alternative. It also allows us to fold memory operands into the
9659 // shuffle in many cases.
9660 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9661 Mask, Subtarget, DAG))
9664 // Check for being able to broadcast a single element.
9665 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9666 Mask, Subtarget, DAG))
9669 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9673 // Use dedicated unpack instructions for masks that match their pattern.
9674 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9676 if (isShuffleEquivalent(
9678 {// First 128-bit lane:
9679 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9680 // Second 128-bit lane:
9681 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9682 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9683 if (isShuffleEquivalent(
9685 {// First 128-bit lane:
9686 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9687 // Second 128-bit lane:
9688 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9689 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9691 // Try to use shift instructions.
9693 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9696 // Try to use byte rotation instructions.
9697 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9698 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9701 if (isSingleInputShuffleMask(Mask)) {
9702 // There are no generalized cross-lane shuffle operations available on i8
9704 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9705 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9708 SDValue PSHUFBMask[32];
9709 for (int i = 0; i < 32; ++i)
9712 ? DAG.getUNDEF(MVT::i8)
9713 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9716 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9717 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9720 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9722 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9723 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9726 // Otherwise fall back on generic lowering.
9727 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9730 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9732 /// This routine either breaks down the specific type of a 256-bit x86 vector
9733 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9734 /// together based on the available instructions.
9735 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9736 MVT VT, const X86Subtarget *Subtarget,
9737 SelectionDAG &DAG) {
9739 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9740 ArrayRef<int> Mask = SVOp->getMask();
9742 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9743 // check for those subtargets here and avoid much of the subtarget querying in
9744 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9745 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9746 // floating point types there eventually, just immediately cast everything to
9747 // a float and operate entirely in that domain.
9748 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9749 int ElementBits = VT.getScalarSizeInBits();
9750 if (ElementBits < 32)
9751 // No floating point type available, decompose into 128-bit vectors.
9752 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9754 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9755 VT.getVectorNumElements());
9756 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9757 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9758 return DAG.getNode(ISD::BITCAST, DL, VT,
9759 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9762 switch (VT.SimpleTy) {
9764 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9766 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9768 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9770 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9772 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9774 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9777 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9781 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9782 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9783 const X86Subtarget *Subtarget,
9784 SelectionDAG &DAG) {
9786 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9787 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9788 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9789 ArrayRef<int> Mask = SVOp->getMask();
9790 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9792 // X86 has dedicated unpack instructions that can handle specific blend
9793 // operations: UNPCKH and UNPCKL.
9794 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9795 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9796 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9797 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9799 // FIXME: Implement direct support for this type!
9800 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9803 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9804 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9805 const X86Subtarget *Subtarget,
9806 SelectionDAG &DAG) {
9808 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9809 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9810 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9811 ArrayRef<int> Mask = SVOp->getMask();
9812 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9814 // Use dedicated unpack instructions for masks that match their pattern.
9815 if (isShuffleEquivalent(V1, V2, Mask,
9816 {// First 128-bit lane.
9817 0, 16, 1, 17, 4, 20, 5, 21,
9818 // Second 128-bit lane.
9819 8, 24, 9, 25, 12, 28, 13, 29}))
9820 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9821 if (isShuffleEquivalent(V1, V2, Mask,
9822 {// First 128-bit lane.
9823 2, 18, 3, 19, 6, 22, 7, 23,
9824 // Second 128-bit lane.
9825 10, 26, 11, 27, 14, 30, 15, 31}))
9826 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9828 // FIXME: Implement direct support for this type!
9829 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9832 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9833 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9834 const X86Subtarget *Subtarget,
9835 SelectionDAG &DAG) {
9837 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9838 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9839 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9840 ArrayRef<int> Mask = SVOp->getMask();
9841 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9843 // X86 has dedicated unpack instructions that can handle specific blend
9844 // operations: UNPCKH and UNPCKL.
9845 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9846 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9847 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9848 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9850 // FIXME: Implement direct support for this type!
9851 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9854 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9855 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9856 const X86Subtarget *Subtarget,
9857 SelectionDAG &DAG) {
9859 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9860 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9861 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9862 ArrayRef<int> Mask = SVOp->getMask();
9863 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9865 // Use dedicated unpack instructions for masks that match their pattern.
9866 if (isShuffleEquivalent(V1, V2, Mask,
9867 {// First 128-bit lane.
9868 0, 16, 1, 17, 4, 20, 5, 21,
9869 // Second 128-bit lane.
9870 8, 24, 9, 25, 12, 28, 13, 29}))
9871 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9872 if (isShuffleEquivalent(V1, V2, Mask,
9873 {// First 128-bit lane.
9874 2, 18, 3, 19, 6, 22, 7, 23,
9875 // Second 128-bit lane.
9876 10, 26, 11, 27, 14, 30, 15, 31}))
9877 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9879 // FIXME: Implement direct support for this type!
9880 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9883 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9884 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885 const X86Subtarget *Subtarget,
9886 SelectionDAG &DAG) {
9888 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9889 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9890 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9891 ArrayRef<int> Mask = SVOp->getMask();
9892 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9893 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9895 // FIXME: Implement direct support for this type!
9896 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9899 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9900 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9901 const X86Subtarget *Subtarget,
9902 SelectionDAG &DAG) {
9904 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9905 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9907 ArrayRef<int> Mask = SVOp->getMask();
9908 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9909 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9911 // FIXME: Implement direct support for this type!
9912 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9915 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9917 /// This routine either breaks down the specific type of a 512-bit x86 vector
9918 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9919 /// together based on the available instructions.
9920 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9921 MVT VT, const X86Subtarget *Subtarget,
9922 SelectionDAG &DAG) {
9924 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9925 ArrayRef<int> Mask = SVOp->getMask();
9926 assert(Subtarget->hasAVX512() &&
9927 "Cannot lower 512-bit vectors w/ basic ISA!");
9929 // Check for being able to broadcast a single element.
9930 if (SDValue Broadcast =
9931 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9934 // Dispatch to each element type for lowering. If we don't have supprot for
9935 // specific element type shuffles at 512 bits, immediately split them and
9936 // lower them. Each lowering routine of a given type is allowed to assume that
9937 // the requisite ISA extensions for that element type are available.
9938 switch (VT.SimpleTy) {
9940 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9942 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9944 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9946 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9948 if (Subtarget->hasBWI())
9949 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9952 if (Subtarget->hasBWI())
9953 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9957 llvm_unreachable("Not a valid 512-bit x86 vector type!");
9960 // Otherwise fall back on splitting.
9961 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9964 /// \brief Top-level lowering for x86 vector shuffles.
9966 /// This handles decomposition, canonicalization, and lowering of all x86
9967 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9968 /// above in helper routines. The canonicalization attempts to widen shuffles
9969 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9970 /// s.t. only one of the two inputs needs to be tested, etc.
9971 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9972 SelectionDAG &DAG) {
9973 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9974 ArrayRef<int> Mask = SVOp->getMask();
9975 SDValue V1 = Op.getOperand(0);
9976 SDValue V2 = Op.getOperand(1);
9977 MVT VT = Op.getSimpleValueType();
9978 int NumElements = VT.getVectorNumElements();
9981 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9983 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9984 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9985 if (V1IsUndef && V2IsUndef)
9986 return DAG.getUNDEF(VT);
9988 // When we create a shuffle node we put the UNDEF node to second operand,
9989 // but in some cases the first operand may be transformed to UNDEF.
9990 // In this case we should just commute the node.
9992 return DAG.getCommutedVectorShuffle(*SVOp);
9994 // Check for non-undef masks pointing at an undef vector and make the masks
9995 // undef as well. This makes it easier to match the shuffle based solely on
9999 if (M >= NumElements) {
10000 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10001 for (int &M : NewMask)
10002 if (M >= NumElements)
10004 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10007 // We actually see shuffles that are entirely re-arrangements of a set of
10008 // zero inputs. This mostly happens while decomposing complex shuffles into
10009 // simple ones. Directly lower these as a buildvector of zeros.
10010 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10011 if (Zeroable.all())
10012 return getZeroVector(VT, Subtarget, DAG, dl);
10014 // Try to collapse shuffles into using a vector type with fewer elements but
10015 // wider element types. We cap this to not form integers or floating point
10016 // elements wider than 64 bits, but it might be interesting to form i128
10017 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10018 SmallVector<int, 16> WidenedMask;
10019 if (VT.getScalarSizeInBits() < 64 &&
10020 canWidenShuffleElements(Mask, WidenedMask)) {
10021 MVT NewEltVT = VT.isFloatingPoint()
10022 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10023 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10024 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10025 // Make sure that the new vector type is legal. For example, v2f64 isn't
10027 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10028 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10029 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10030 return DAG.getNode(ISD::BITCAST, dl, VT,
10031 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10035 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10036 for (int M : SVOp->getMask())
10038 ++NumUndefElements;
10039 else if (M < NumElements)
10044 // Commute the shuffle as needed such that more elements come from V1 than
10045 // V2. This allows us to match the shuffle pattern strictly on how many
10046 // elements come from V1 without handling the symmetric cases.
10047 if (NumV2Elements > NumV1Elements)
10048 return DAG.getCommutedVectorShuffle(*SVOp);
10050 // When the number of V1 and V2 elements are the same, try to minimize the
10051 // number of uses of V2 in the low half of the vector. When that is tied,
10052 // ensure that the sum of indices for V1 is equal to or lower than the sum
10053 // indices for V2. When those are equal, try to ensure that the number of odd
10054 // indices for V1 is lower than the number of odd indices for V2.
10055 if (NumV1Elements == NumV2Elements) {
10056 int LowV1Elements = 0, LowV2Elements = 0;
10057 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10058 if (M >= NumElements)
10062 if (LowV2Elements > LowV1Elements) {
10063 return DAG.getCommutedVectorShuffle(*SVOp);
10064 } else if (LowV2Elements == LowV1Elements) {
10065 int SumV1Indices = 0, SumV2Indices = 0;
10066 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10067 if (SVOp->getMask()[i] >= NumElements)
10069 else if (SVOp->getMask()[i] >= 0)
10071 if (SumV2Indices < SumV1Indices) {
10072 return DAG.getCommutedVectorShuffle(*SVOp);
10073 } else if (SumV2Indices == SumV1Indices) {
10074 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10075 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10076 if (SVOp->getMask()[i] >= NumElements)
10077 NumV2OddIndices += i % 2;
10078 else if (SVOp->getMask()[i] >= 0)
10079 NumV1OddIndices += i % 2;
10080 if (NumV2OddIndices < NumV1OddIndices)
10081 return DAG.getCommutedVectorShuffle(*SVOp);
10086 // For each vector width, delegate to a specialized lowering routine.
10087 if (VT.getSizeInBits() == 128)
10088 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10090 if (VT.getSizeInBits() == 256)
10091 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10093 // Force AVX-512 vectors to be scalarized for now.
10094 // FIXME: Implement AVX-512 support!
10095 if (VT.getSizeInBits() == 512)
10096 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10098 llvm_unreachable("Unimplemented!");
10101 // This function assumes its argument is a BUILD_VECTOR of constants or
10102 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10104 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10105 unsigned &MaskValue) {
10107 unsigned NumElems = BuildVector->getNumOperands();
10108 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10109 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10110 unsigned NumElemsInLane = NumElems / NumLanes;
10112 // Blend for v16i16 should be symetric for the both lanes.
10113 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10114 SDValue EltCond = BuildVector->getOperand(i);
10115 SDValue SndLaneEltCond =
10116 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10118 int Lane1Cond = -1, Lane2Cond = -1;
10119 if (isa<ConstantSDNode>(EltCond))
10120 Lane1Cond = !isZero(EltCond);
10121 if (isa<ConstantSDNode>(SndLaneEltCond))
10122 Lane2Cond = !isZero(SndLaneEltCond);
10124 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10125 // Lane1Cond != 0, means we want the first argument.
10126 // Lane1Cond == 0, means we want the second argument.
10127 // The encoding of this argument is 0 for the first argument, 1
10128 // for the second. Therefore, invert the condition.
10129 MaskValue |= !Lane1Cond << i;
10130 else if (Lane1Cond < 0)
10131 MaskValue |= !Lane2Cond << i;
10138 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10139 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10140 const X86Subtarget *Subtarget,
10141 SelectionDAG &DAG) {
10142 SDValue Cond = Op.getOperand(0);
10143 SDValue LHS = Op.getOperand(1);
10144 SDValue RHS = Op.getOperand(2);
10146 MVT VT = Op.getSimpleValueType();
10148 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10150 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10152 // Only non-legal VSELECTs reach this lowering, convert those into generic
10153 // shuffles and re-use the shuffle lowering path for blends.
10154 SmallVector<int, 32> Mask;
10155 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10156 SDValue CondElt = CondBV->getOperand(i);
10158 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10160 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10163 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10164 // A vselect where all conditions and data are constants can be optimized into
10165 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10166 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10167 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10168 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10171 // Try to lower this to a blend-style vector shuffle. This can handle all
10172 // constant condition cases.
10173 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10176 // Variable blends are only legal from SSE4.1 onward.
10177 if (!Subtarget->hasSSE41())
10180 // Only some types will be legal on some subtargets. If we can emit a legal
10181 // VSELECT-matching blend, return Op, and but if we need to expand, return
10183 switch (Op.getSimpleValueType().SimpleTy) {
10185 // Most of the vector types have blends past SSE4.1.
10189 // The byte blends for AVX vectors were introduced only in AVX2.
10190 if (Subtarget->hasAVX2())
10197 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10198 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10201 // FIXME: We should custom lower this by fixing the condition and using i8
10207 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10208 MVT VT = Op.getSimpleValueType();
10211 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10214 if (VT.getSizeInBits() == 8) {
10215 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10216 Op.getOperand(0), Op.getOperand(1));
10217 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10218 DAG.getValueType(VT));
10219 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10222 if (VT.getSizeInBits() == 16) {
10223 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10224 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10226 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10227 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10228 DAG.getNode(ISD::BITCAST, dl,
10231 Op.getOperand(1)));
10232 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10233 Op.getOperand(0), Op.getOperand(1));
10234 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10235 DAG.getValueType(VT));
10236 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10239 if (VT == MVT::f32) {
10240 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10241 // the result back to FR32 register. It's only worth matching if the
10242 // result has a single use which is a store or a bitcast to i32. And in
10243 // the case of a store, it's not worth it if the index is a constant 0,
10244 // because a MOVSSmr can be used instead, which is smaller and faster.
10245 if (!Op.hasOneUse())
10247 SDNode *User = *Op.getNode()->use_begin();
10248 if ((User->getOpcode() != ISD::STORE ||
10249 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10250 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10251 (User->getOpcode() != ISD::BITCAST ||
10252 User->getValueType(0) != MVT::i32))
10254 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10255 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10258 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10261 if (VT == MVT::i32 || VT == MVT::i64) {
10262 // ExtractPS/pextrq works with constant index.
10263 if (isa<ConstantSDNode>(Op.getOperand(1)))
10269 /// Extract one bit from mask vector, like v16i1 or v8i1.
10270 /// AVX-512 feature.
10272 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10273 SDValue Vec = Op.getOperand(0);
10275 MVT VecVT = Vec.getSimpleValueType();
10276 SDValue Idx = Op.getOperand(1);
10277 MVT EltVT = Op.getSimpleValueType();
10279 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10280 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10281 "Unexpected vector type in ExtractBitFromMaskVector");
10283 // variable index can't be handled in mask registers,
10284 // extend vector to VR512
10285 if (!isa<ConstantSDNode>(Idx)) {
10286 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10287 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10288 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10289 ExtVT.getVectorElementType(), Ext, Idx);
10290 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10293 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10294 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10295 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10296 rc = getRegClassFor(MVT::v16i1);
10297 unsigned MaxSift = rc->getSize()*8 - 1;
10298 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10299 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10300 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10301 DAG.getConstant(MaxSift, MVT::i8));
10302 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10303 DAG.getIntPtrConstant(0));
10307 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10308 SelectionDAG &DAG) const {
10310 SDValue Vec = Op.getOperand(0);
10311 MVT VecVT = Vec.getSimpleValueType();
10312 SDValue Idx = Op.getOperand(1);
10314 if (Op.getSimpleValueType() == MVT::i1)
10315 return ExtractBitFromMaskVector(Op, DAG);
10317 if (!isa<ConstantSDNode>(Idx)) {
10318 if (VecVT.is512BitVector() ||
10319 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10320 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10323 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10324 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10325 MaskEltVT.getSizeInBits());
10327 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10328 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10329 getZeroVector(MaskVT, Subtarget, DAG, dl),
10330 Idx, DAG.getConstant(0, getPointerTy()));
10331 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10332 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10333 Perm, DAG.getConstant(0, getPointerTy()));
10338 // If this is a 256-bit vector result, first extract the 128-bit vector and
10339 // then extract the element from the 128-bit vector.
10340 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10342 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10343 // Get the 128-bit vector.
10344 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10345 MVT EltVT = VecVT.getVectorElementType();
10347 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10349 //if (IdxVal >= NumElems/2)
10350 // IdxVal -= NumElems/2;
10351 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10353 DAG.getConstant(IdxVal, MVT::i32));
10356 assert(VecVT.is128BitVector() && "Unexpected vector length");
10358 if (Subtarget->hasSSE41()) {
10359 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10364 MVT VT = Op.getSimpleValueType();
10365 // TODO: handle v16i8.
10366 if (VT.getSizeInBits() == 16) {
10367 SDValue Vec = Op.getOperand(0);
10368 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10370 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10371 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10372 DAG.getNode(ISD::BITCAST, dl,
10374 Op.getOperand(1)));
10375 // Transform it so it match pextrw which produces a 32-bit result.
10376 MVT EltVT = MVT::i32;
10377 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10378 Op.getOperand(0), Op.getOperand(1));
10379 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10380 DAG.getValueType(VT));
10381 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10384 if (VT.getSizeInBits() == 32) {
10385 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10389 // SHUFPS the element to the lowest double word, then movss.
10390 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10391 MVT VVT = Op.getOperand(0).getSimpleValueType();
10392 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10393 DAG.getUNDEF(VVT), Mask);
10394 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10395 DAG.getIntPtrConstant(0));
10398 if (VT.getSizeInBits() == 64) {
10399 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10400 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10401 // to match extract_elt for f64.
10402 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10406 // UNPCKHPD the element to the lowest double word, then movsd.
10407 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10408 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10409 int Mask[2] = { 1, -1 };
10410 MVT VVT = Op.getOperand(0).getSimpleValueType();
10411 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10412 DAG.getUNDEF(VVT), Mask);
10413 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10414 DAG.getIntPtrConstant(0));
10420 /// Insert one bit to mask vector, like v16i1 or v8i1.
10421 /// AVX-512 feature.
10423 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10425 SDValue Vec = Op.getOperand(0);
10426 SDValue Elt = Op.getOperand(1);
10427 SDValue Idx = Op.getOperand(2);
10428 MVT VecVT = Vec.getSimpleValueType();
10430 if (!isa<ConstantSDNode>(Idx)) {
10431 // Non constant index. Extend source and destination,
10432 // insert element and then truncate the result.
10433 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10434 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10435 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10436 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10437 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10438 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10441 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10442 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10443 if (Vec.getOpcode() == ISD::UNDEF)
10444 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10445 DAG.getConstant(IdxVal, MVT::i8));
10446 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10447 unsigned MaxSift = rc->getSize()*8 - 1;
10448 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10449 DAG.getConstant(MaxSift, MVT::i8));
10450 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10451 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10452 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10455 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10456 SelectionDAG &DAG) const {
10457 MVT VT = Op.getSimpleValueType();
10458 MVT EltVT = VT.getVectorElementType();
10460 if (EltVT == MVT::i1)
10461 return InsertBitToMaskVector(Op, DAG);
10464 SDValue N0 = Op.getOperand(0);
10465 SDValue N1 = Op.getOperand(1);
10466 SDValue N2 = Op.getOperand(2);
10467 if (!isa<ConstantSDNode>(N2))
10469 auto *N2C = cast<ConstantSDNode>(N2);
10470 unsigned IdxVal = N2C->getZExtValue();
10472 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10473 // into that, and then insert the subvector back into the result.
10474 if (VT.is256BitVector() || VT.is512BitVector()) {
10475 // Get the desired 128-bit vector chunk.
10476 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10478 // Insert the element into the desired chunk.
10479 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10480 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10482 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10483 DAG.getConstant(IdxIn128, MVT::i32));
10485 // Insert the changed part back into the bigger vector
10486 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10488 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10490 if (Subtarget->hasSSE41()) {
10491 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10493 if (VT == MVT::v8i16) {
10494 Opc = X86ISD::PINSRW;
10496 assert(VT == MVT::v16i8);
10497 Opc = X86ISD::PINSRB;
10500 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10502 if (N1.getValueType() != MVT::i32)
10503 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10504 if (N2.getValueType() != MVT::i32)
10505 N2 = DAG.getIntPtrConstant(IdxVal);
10506 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10509 if (EltVT == MVT::f32) {
10510 // Bits [7:6] of the constant are the source select. This will always be
10511 // zero here. The DAG Combiner may combine an extract_elt index into
10513 // bits. For example (insert (extract, 3), 2) could be matched by
10515 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10516 // Bits [5:4] of the constant are the destination select. This is the
10517 // value of the incoming immediate.
10518 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10519 // combine either bitwise AND or insert of float 0.0 to set these bits.
10520 N2 = DAG.getIntPtrConstant(IdxVal << 4);
10521 // Create this as a scalar to vector..
10522 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10523 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10526 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10527 // PINSR* works with constant index.
10532 if (EltVT == MVT::i8)
10535 if (EltVT.getSizeInBits() == 16) {
10536 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10537 // as its second argument.
10538 if (N1.getValueType() != MVT::i32)
10539 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10540 if (N2.getValueType() != MVT::i32)
10541 N2 = DAG.getIntPtrConstant(IdxVal);
10542 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10547 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10549 MVT OpVT = Op.getSimpleValueType();
10551 // If this is a 256-bit vector result, first insert into a 128-bit
10552 // vector and then insert into the 256-bit vector.
10553 if (!OpVT.is128BitVector()) {
10554 // Insert into a 128-bit vector.
10555 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10556 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10557 OpVT.getVectorNumElements() / SizeFactor);
10559 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10561 // Insert the 128-bit vector.
10562 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10565 if (OpVT == MVT::v1i64 &&
10566 Op.getOperand(0).getValueType() == MVT::i64)
10567 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10569 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10570 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10571 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10572 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10575 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10576 // a simple subregister reference or explicit instructions to grab
10577 // upper bits of a vector.
10578 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10579 SelectionDAG &DAG) {
10581 SDValue In = Op.getOperand(0);
10582 SDValue Idx = Op.getOperand(1);
10583 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10584 MVT ResVT = Op.getSimpleValueType();
10585 MVT InVT = In.getSimpleValueType();
10587 if (Subtarget->hasFp256()) {
10588 if (ResVT.is128BitVector() &&
10589 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10590 isa<ConstantSDNode>(Idx)) {
10591 return Extract128BitVector(In, IdxVal, DAG, dl);
10593 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10594 isa<ConstantSDNode>(Idx)) {
10595 return Extract256BitVector(In, IdxVal, DAG, dl);
10601 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10602 // simple superregister reference or explicit instructions to insert
10603 // the upper bits of a vector.
10604 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10605 SelectionDAG &DAG) {
10606 if (!Subtarget->hasAVX())
10610 SDValue Vec = Op.getOperand(0);
10611 SDValue SubVec = Op.getOperand(1);
10612 SDValue Idx = Op.getOperand(2);
10614 if (!isa<ConstantSDNode>(Idx))
10617 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10618 MVT OpVT = Op.getSimpleValueType();
10619 MVT SubVecVT = SubVec.getSimpleValueType();
10621 // Fold two 16-byte subvector loads into one 32-byte load:
10622 // (insert_subvector (insert_subvector undef, (load addr), 0),
10623 // (load addr + 16), Elts/2)
10625 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10626 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10627 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10628 !Subtarget->isUnalignedMem32Slow()) {
10629 SDValue SubVec2 = Vec.getOperand(1);
10630 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10631 if (Idx2->getZExtValue() == 0) {
10632 SDValue Ops[] = { SubVec2, SubVec };
10633 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10640 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10641 SubVecVT.is128BitVector())
10642 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10644 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10645 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10647 if (OpVT.getVectorElementType() == MVT::i1) {
10648 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10650 SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10651 SDValue Undef = DAG.getUNDEF(OpVT);
10652 unsigned NumElems = OpVT.getVectorNumElements();
10653 SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10655 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10656 // Zero upper bits of the Vec
10657 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10658 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10660 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10662 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10663 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10666 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10668 // Zero upper bits of the Vec2
10669 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10670 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10671 // Zero lower bits of the Vec
10672 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10673 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10674 // Merge them together
10675 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10681 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10682 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10683 // one of the above mentioned nodes. It has to be wrapped because otherwise
10684 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10685 // be used to form addressing mode. These wrapped nodes will be selected
10688 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10689 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
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 WrapperKind = X86ISD::WrapperRIP;
10700 else if (Subtarget->isPICStyleGOT())
10701 OpFlag = X86II::MO_GOTOFF;
10702 else if (Subtarget->isPICStyleStubPIC())
10703 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10705 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10706 CP->getAlignment(),
10707 CP->getOffset(), OpFlag);
10709 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10710 // With PIC, the address is actually $g + Offset.
10712 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10713 DAG.getNode(X86ISD::GlobalBaseReg,
10714 SDLoc(), getPointerTy()),
10721 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10722 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10724 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10725 // global base reg.
10726 unsigned char OpFlag = 0;
10727 unsigned WrapperKind = X86ISD::Wrapper;
10728 CodeModel::Model M = DAG.getTarget().getCodeModel();
10730 if (Subtarget->isPICStyleRIPRel() &&
10731 (M == CodeModel::Small || M == CodeModel::Kernel))
10732 WrapperKind = X86ISD::WrapperRIP;
10733 else if (Subtarget->isPICStyleGOT())
10734 OpFlag = X86II::MO_GOTOFF;
10735 else if (Subtarget->isPICStyleStubPIC())
10736 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10738 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10741 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10743 // With PIC, the address is actually $g + Offset.
10745 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10746 DAG.getNode(X86ISD::GlobalBaseReg,
10747 SDLoc(), getPointerTy()),
10754 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10755 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10757 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10758 // global base reg.
10759 unsigned char OpFlag = 0;
10760 unsigned WrapperKind = X86ISD::Wrapper;
10761 CodeModel::Model M = DAG.getTarget().getCodeModel();
10763 if (Subtarget->isPICStyleRIPRel() &&
10764 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10765 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10766 OpFlag = X86II::MO_GOTPCREL;
10767 WrapperKind = X86ISD::WrapperRIP;
10768 } else if (Subtarget->isPICStyleGOT()) {
10769 OpFlag = X86II::MO_GOT;
10770 } else if (Subtarget->isPICStyleStubPIC()) {
10771 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10772 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10773 OpFlag = X86II::MO_DARWIN_NONLAZY;
10776 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10779 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10781 // With PIC, the address is actually $g + Offset.
10782 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10783 !Subtarget->is64Bit()) {
10784 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10785 DAG.getNode(X86ISD::GlobalBaseReg,
10786 SDLoc(), getPointerTy()),
10790 // For symbols that require a load from a stub to get the address, emit the
10792 if (isGlobalStubReference(OpFlag))
10793 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10794 MachinePointerInfo::getGOT(), false, false, false, 0);
10800 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10801 // Create the TargetBlockAddressAddress node.
10802 unsigned char OpFlags =
10803 Subtarget->ClassifyBlockAddressReference();
10804 CodeModel::Model M = DAG.getTarget().getCodeModel();
10805 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10806 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10808 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10811 if (Subtarget->isPICStyleRIPRel() &&
10812 (M == CodeModel::Small || M == CodeModel::Kernel))
10813 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10815 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10817 // With PIC, the address is actually $g + Offset.
10818 if (isGlobalRelativeToPICBase(OpFlags)) {
10819 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10820 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10828 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10829 int64_t Offset, SelectionDAG &DAG) const {
10830 // Create the TargetGlobalAddress node, folding in the constant
10831 // offset if it is legal.
10832 unsigned char OpFlags =
10833 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10834 CodeModel::Model M = DAG.getTarget().getCodeModel();
10836 if (OpFlags == X86II::MO_NO_FLAG &&
10837 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10838 // A direct static reference to a global.
10839 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10842 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10845 if (Subtarget->isPICStyleRIPRel() &&
10846 (M == CodeModel::Small || M == CodeModel::Kernel))
10847 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10849 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10851 // With PIC, the address is actually $g + Offset.
10852 if (isGlobalRelativeToPICBase(OpFlags)) {
10853 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10854 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10858 // For globals that require a load from a stub to get the address, emit the
10860 if (isGlobalStubReference(OpFlags))
10861 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10862 MachinePointerInfo::getGOT(), false, false, false, 0);
10864 // If there was a non-zero offset that we didn't fold, create an explicit
10865 // addition for it.
10867 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10868 DAG.getConstant(Offset, getPointerTy()));
10874 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10875 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10876 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10877 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10881 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10882 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10883 unsigned char OperandFlags, bool LocalDynamic = false) {
10884 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10885 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10887 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10888 GA->getValueType(0),
10892 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10896 SDValue Ops[] = { Chain, TGA, *InFlag };
10897 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10899 SDValue Ops[] = { Chain, TGA };
10900 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10903 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10904 MFI->setAdjustsStack(true);
10905 MFI->setHasCalls(true);
10907 SDValue Flag = Chain.getValue(1);
10908 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10911 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10913 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10916 SDLoc dl(GA); // ? function entry point might be better
10917 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10918 DAG.getNode(X86ISD::GlobalBaseReg,
10919 SDLoc(), PtrVT), InFlag);
10920 InFlag = Chain.getValue(1);
10922 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10925 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10927 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10929 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10930 X86::RAX, X86II::MO_TLSGD);
10933 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10939 // Get the start address of the TLS block for this module.
10940 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10941 .getInfo<X86MachineFunctionInfo>();
10942 MFI->incNumLocalDynamicTLSAccesses();
10946 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10947 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10950 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10951 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10952 InFlag = Chain.getValue(1);
10953 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10954 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10957 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10961 unsigned char OperandFlags = X86II::MO_DTPOFF;
10962 unsigned WrapperKind = X86ISD::Wrapper;
10963 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10964 GA->getValueType(0),
10965 GA->getOffset(), OperandFlags);
10966 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10968 // Add x@dtpoff with the base.
10969 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10972 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10973 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10974 const EVT PtrVT, TLSModel::Model model,
10975 bool is64Bit, bool isPIC) {
10978 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10979 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10980 is64Bit ? 257 : 256));
10982 SDValue ThreadPointer =
10983 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10984 MachinePointerInfo(Ptr), false, false, false, 0);
10986 unsigned char OperandFlags = 0;
10987 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10989 unsigned WrapperKind = X86ISD::Wrapper;
10990 if (model == TLSModel::LocalExec) {
10991 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10992 } else if (model == TLSModel::InitialExec) {
10994 OperandFlags = X86II::MO_GOTTPOFF;
10995 WrapperKind = X86ISD::WrapperRIP;
10997 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11000 llvm_unreachable("Unexpected model");
11003 // emit "addl x@ntpoff,%eax" (local exec)
11004 // or "addl x@indntpoff,%eax" (initial exec)
11005 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11007 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11008 GA->getOffset(), OperandFlags);
11009 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11011 if (model == TLSModel::InitialExec) {
11012 if (isPIC && !is64Bit) {
11013 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11014 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11018 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11019 MachinePointerInfo::getGOT(), false, false, false, 0);
11022 // The address of the thread local variable is the add of the thread
11023 // pointer with the offset of the variable.
11024 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11028 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11030 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11031 const GlobalValue *GV = GA->getGlobal();
11033 if (Subtarget->isTargetELF()) {
11034 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11037 case TLSModel::GeneralDynamic:
11038 if (Subtarget->is64Bit())
11039 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11040 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11041 case TLSModel::LocalDynamic:
11042 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11043 Subtarget->is64Bit());
11044 case TLSModel::InitialExec:
11045 case TLSModel::LocalExec:
11046 return LowerToTLSExecModel(
11047 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11048 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11050 llvm_unreachable("Unknown TLS model.");
11053 if (Subtarget->isTargetDarwin()) {
11054 // Darwin only has one model of TLS. Lower to that.
11055 unsigned char OpFlag = 0;
11056 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11057 X86ISD::WrapperRIP : X86ISD::Wrapper;
11059 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11060 // global base reg.
11061 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11062 !Subtarget->is64Bit();
11064 OpFlag = X86II::MO_TLVP_PIC_BASE;
11066 OpFlag = X86II::MO_TLVP;
11068 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11069 GA->getValueType(0),
11070 GA->getOffset(), OpFlag);
11071 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11073 // With PIC32, the address is actually $g + Offset.
11075 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11076 DAG.getNode(X86ISD::GlobalBaseReg,
11077 SDLoc(), getPointerTy()),
11080 // Lowering the machine isd will make sure everything is in the right
11082 SDValue Chain = DAG.getEntryNode();
11083 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11084 SDValue Args[] = { Chain, Offset };
11085 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11087 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11088 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11089 MFI->setAdjustsStack(true);
11091 // And our return value (tls address) is in the standard call return value
11093 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11094 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11095 Chain.getValue(1));
11098 if (Subtarget->isTargetKnownWindowsMSVC() ||
11099 Subtarget->isTargetWindowsGNU()) {
11100 // Just use the implicit TLS architecture
11101 // Need to generate someting similar to:
11102 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11104 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11105 // mov rcx, qword [rdx+rcx*8]
11106 // mov eax, .tls$:tlsvar
11107 // [rax+rcx] contains the address
11108 // Windows 64bit: gs:0x58
11109 // Windows 32bit: fs:__tls_array
11112 SDValue Chain = DAG.getEntryNode();
11114 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11115 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11116 // use its literal value of 0x2C.
11117 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11118 ? Type::getInt8PtrTy(*DAG.getContext(),
11120 : Type::getInt32PtrTy(*DAG.getContext(),
11124 Subtarget->is64Bit()
11125 ? DAG.getIntPtrConstant(0x58)
11126 : (Subtarget->isTargetWindowsGNU()
11127 ? DAG.getIntPtrConstant(0x2C)
11128 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11130 SDValue ThreadPointer =
11131 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11132 MachinePointerInfo(Ptr), false, false, false, 0);
11134 // Load the _tls_index variable
11135 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11136 if (Subtarget->is64Bit())
11137 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11138 IDX, MachinePointerInfo(), MVT::i32,
11139 false, false, false, 0);
11141 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11142 false, false, false, 0);
11144 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11146 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11148 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11149 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11150 false, false, false, 0);
11152 // Get the offset of start of .tls section
11153 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11154 GA->getValueType(0),
11155 GA->getOffset(), X86II::MO_SECREL);
11156 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11158 // The address of the thread local variable is the add of the thread
11159 // pointer with the offset of the variable.
11160 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11163 llvm_unreachable("TLS not implemented for this target.");
11166 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11167 /// and take a 2 x i32 value to shift plus a shift amount.
11168 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11169 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11170 MVT VT = Op.getSimpleValueType();
11171 unsigned VTBits = VT.getSizeInBits();
11173 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11174 SDValue ShOpLo = Op.getOperand(0);
11175 SDValue ShOpHi = Op.getOperand(1);
11176 SDValue ShAmt = Op.getOperand(2);
11177 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11178 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11180 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11181 DAG.getConstant(VTBits - 1, MVT::i8));
11182 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11183 DAG.getConstant(VTBits - 1, MVT::i8))
11184 : DAG.getConstant(0, VT);
11186 SDValue Tmp2, Tmp3;
11187 if (Op.getOpcode() == ISD::SHL_PARTS) {
11188 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11189 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11191 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11192 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11195 // If the shift amount is larger or equal than the width of a part we can't
11196 // rely on the results of shld/shrd. Insert a test and select the appropriate
11197 // values for large shift amounts.
11198 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11199 DAG.getConstant(VTBits, MVT::i8));
11200 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11201 AndNode, DAG.getConstant(0, MVT::i8));
11204 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11205 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11206 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11208 if (Op.getOpcode() == ISD::SHL_PARTS) {
11209 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11210 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11212 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11213 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11216 SDValue Ops[2] = { Lo, Hi };
11217 return DAG.getMergeValues(Ops, dl);
11220 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11221 SelectionDAG &DAG) const {
11222 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11225 if (SrcVT.isVector()) {
11226 if (SrcVT.getVectorElementType() == MVT::i1) {
11227 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11228 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11229 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11230 Op.getOperand(0)));
11235 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11236 "Unknown SINT_TO_FP to lower!");
11238 // These are really Legal; return the operand so the caller accepts it as
11240 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11242 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11243 Subtarget->is64Bit()) {
11247 unsigned Size = SrcVT.getSizeInBits()/8;
11248 MachineFunction &MF = DAG.getMachineFunction();
11249 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11250 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11251 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11253 MachinePointerInfo::getFixedStack(SSFI),
11255 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11258 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11260 SelectionDAG &DAG) const {
11264 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11266 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11268 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11270 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11272 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11273 MachineMemOperand *MMO;
11275 int SSFI = FI->getIndex();
11277 DAG.getMachineFunction()
11278 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11279 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11281 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11282 StackSlot = StackSlot.getOperand(1);
11284 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11285 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11287 Tys, Ops, SrcVT, MMO);
11290 Chain = Result.getValue(1);
11291 SDValue InFlag = Result.getValue(2);
11293 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11294 // shouldn't be necessary except that RFP cannot be live across
11295 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11296 MachineFunction &MF = DAG.getMachineFunction();
11297 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11298 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11299 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11300 Tys = DAG.getVTList(MVT::Other);
11302 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11304 MachineMemOperand *MMO =
11305 DAG.getMachineFunction()
11306 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11307 MachineMemOperand::MOStore, SSFISize, SSFISize);
11309 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11310 Ops, Op.getValueType(), MMO);
11311 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11312 MachinePointerInfo::getFixedStack(SSFI),
11313 false, false, false, 0);
11319 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11320 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11321 SelectionDAG &DAG) const {
11322 // This algorithm is not obvious. Here it is what we're trying to output:
11325 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11326 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11328 haddpd %xmm0, %xmm0
11330 pshufd $0x4e, %xmm0, %xmm1
11336 LLVMContext *Context = DAG.getContext();
11338 // Build some magic constants.
11339 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11340 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11341 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11343 SmallVector<Constant*,2> CV1;
11345 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11346 APInt(64, 0x4330000000000000ULL))));
11348 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11349 APInt(64, 0x4530000000000000ULL))));
11350 Constant *C1 = ConstantVector::get(CV1);
11351 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11353 // Load the 64-bit value into an XMM register.
11354 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11356 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11357 MachinePointerInfo::getConstantPool(),
11358 false, false, false, 16);
11359 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11360 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11363 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11364 MachinePointerInfo::getConstantPool(),
11365 false, false, false, 16);
11366 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11367 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11370 if (Subtarget->hasSSE3()) {
11371 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11372 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11374 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11375 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11377 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11378 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11382 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11383 DAG.getIntPtrConstant(0));
11386 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11387 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11388 SelectionDAG &DAG) const {
11390 // FP constant to bias correct the final result.
11391 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11394 // Load the 32-bit value into an XMM register.
11395 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11398 // Zero out the upper parts of the register.
11399 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11401 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11402 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11403 DAG.getIntPtrConstant(0));
11405 // Or the load with the bias.
11406 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11407 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11408 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11409 MVT::v2f64, Load)),
11410 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11411 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11412 MVT::v2f64, Bias)));
11413 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11414 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11415 DAG.getIntPtrConstant(0));
11417 // Subtract the bias.
11418 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11420 // Handle final rounding.
11421 EVT DestVT = Op.getValueType();
11423 if (DestVT.bitsLT(MVT::f64))
11424 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11425 DAG.getIntPtrConstant(0));
11426 if (DestVT.bitsGT(MVT::f64))
11427 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11429 // Handle final rounding.
11433 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11434 const X86Subtarget &Subtarget) {
11435 // The algorithm is the following:
11436 // #ifdef __SSE4_1__
11437 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11438 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11439 // (uint4) 0x53000000, 0xaa);
11441 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11442 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11444 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11445 // return (float4) lo + fhi;
11448 SDValue V = Op->getOperand(0);
11449 EVT VecIntVT = V.getValueType();
11450 bool Is128 = VecIntVT == MVT::v4i32;
11451 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11452 // If we convert to something else than the supported type, e.g., to v4f64,
11454 if (VecFloatVT != Op->getValueType(0))
11457 unsigned NumElts = VecIntVT.getVectorNumElements();
11458 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11459 "Unsupported custom type");
11460 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11462 // In the #idef/#else code, we have in common:
11463 // - The vector of constants:
11469 // Create the splat vector for 0x4b000000.
11470 SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11471 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11472 CstLow, CstLow, CstLow, CstLow};
11473 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11474 makeArrayRef(&CstLowArray[0], NumElts));
11475 // Create the splat vector for 0x53000000.
11476 SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11477 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11478 CstHigh, CstHigh, CstHigh, CstHigh};
11479 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11480 makeArrayRef(&CstHighArray[0], NumElts));
11482 // Create the right shift.
11483 SDValue CstShift = DAG.getConstant(16, MVT::i32);
11484 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11485 CstShift, CstShift, CstShift, CstShift};
11486 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11487 makeArrayRef(&CstShiftArray[0], NumElts));
11488 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11491 if (Subtarget.hasSSE41()) {
11492 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11493 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11494 SDValue VecCstLowBitcast =
11495 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11496 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11497 // Low will be bitcasted right away, so do not bother bitcasting back to its
11499 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11500 VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11501 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11502 // (uint4) 0x53000000, 0xaa);
11503 SDValue VecCstHighBitcast =
11504 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11505 SDValue VecShiftBitcast =
11506 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11507 // High will be bitcasted right away, so do not bother bitcasting back to
11508 // its original type.
11509 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11510 VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11512 SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11513 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11514 CstMask, CstMask, CstMask);
11515 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11516 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11517 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11519 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11520 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11523 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11524 SDValue CstFAdd = DAG.getConstantFP(
11525 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11526 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11527 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11528 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11529 makeArrayRef(&CstFAddArray[0], NumElts));
11531 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11532 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11534 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11535 // return (float4) lo + fhi;
11536 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11537 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11540 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11541 SelectionDAG &DAG) const {
11542 SDValue N0 = Op.getOperand(0);
11543 MVT SVT = N0.getSimpleValueType();
11546 switch (SVT.SimpleTy) {
11548 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11553 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11554 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11555 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11559 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11561 llvm_unreachable(nullptr);
11564 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11565 SelectionDAG &DAG) const {
11566 SDValue N0 = Op.getOperand(0);
11569 if (Op.getValueType().isVector())
11570 return lowerUINT_TO_FP_vec(Op, DAG);
11572 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11573 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11574 // the optimization here.
11575 if (DAG.SignBitIsZero(N0))
11576 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11578 MVT SrcVT = N0.getSimpleValueType();
11579 MVT DstVT = Op.getSimpleValueType();
11580 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11581 return LowerUINT_TO_FP_i64(Op, DAG);
11582 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11583 return LowerUINT_TO_FP_i32(Op, DAG);
11584 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11587 // Make a 64-bit buffer, and use it to build an FILD.
11588 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11589 if (SrcVT == MVT::i32) {
11590 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11591 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11592 getPointerTy(), StackSlot, WordOff);
11593 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11594 StackSlot, MachinePointerInfo(),
11596 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11597 OffsetSlot, MachinePointerInfo(),
11599 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11603 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11604 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11605 StackSlot, MachinePointerInfo(),
11607 // For i64 source, we need to add the appropriate power of 2 if the input
11608 // was negative. This is the same as the optimization in
11609 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11610 // we must be careful to do the computation in x87 extended precision, not
11611 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11612 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11613 MachineMemOperand *MMO =
11614 DAG.getMachineFunction()
11615 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11616 MachineMemOperand::MOLoad, 8, 8);
11618 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11619 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11620 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11623 APInt FF(32, 0x5F800000ULL);
11625 // Check whether the sign bit is set.
11626 SDValue SignSet = DAG.getSetCC(dl,
11627 getSetCCResultType(*DAG.getContext(), MVT::i64),
11628 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11631 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11632 SDValue FudgePtr = DAG.getConstantPool(
11633 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11636 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11637 SDValue Zero = DAG.getIntPtrConstant(0);
11638 SDValue Four = DAG.getIntPtrConstant(4);
11639 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11641 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11643 // Load the value out, extending it from f32 to f80.
11644 // FIXME: Avoid the extend by constructing the right constant pool?
11645 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11646 FudgePtr, MachinePointerInfo::getConstantPool(),
11647 MVT::f32, false, false, false, 4);
11648 // Extend everything to 80 bits to force it to be done on x87.
11649 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11650 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11653 std::pair<SDValue,SDValue>
11654 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11655 bool IsSigned, bool IsReplace) const {
11658 EVT DstTy = Op.getValueType();
11660 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11661 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11665 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11666 DstTy.getSimpleVT() >= MVT::i16 &&
11667 "Unknown FP_TO_INT to lower!");
11669 // These are really Legal.
11670 if (DstTy == MVT::i32 &&
11671 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11672 return std::make_pair(SDValue(), SDValue());
11673 if (Subtarget->is64Bit() &&
11674 DstTy == MVT::i64 &&
11675 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11676 return std::make_pair(SDValue(), SDValue());
11678 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11679 // stack slot, or into the FTOL runtime function.
11680 MachineFunction &MF = DAG.getMachineFunction();
11681 unsigned MemSize = DstTy.getSizeInBits()/8;
11682 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11683 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11686 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11687 Opc = X86ISD::WIN_FTOL;
11689 switch (DstTy.getSimpleVT().SimpleTy) {
11690 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11691 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11692 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11693 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11696 SDValue Chain = DAG.getEntryNode();
11697 SDValue Value = Op.getOperand(0);
11698 EVT TheVT = Op.getOperand(0).getValueType();
11699 // FIXME This causes a redundant load/store if the SSE-class value is already
11700 // in memory, such as if it is on the callstack.
11701 if (isScalarFPTypeInSSEReg(TheVT)) {
11702 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11703 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11704 MachinePointerInfo::getFixedStack(SSFI),
11706 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11708 Chain, StackSlot, DAG.getValueType(TheVT)
11711 MachineMemOperand *MMO =
11712 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11713 MachineMemOperand::MOLoad, MemSize, MemSize);
11714 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11715 Chain = Value.getValue(1);
11716 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11717 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11720 MachineMemOperand *MMO =
11721 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11722 MachineMemOperand::MOStore, MemSize, MemSize);
11724 if (Opc != X86ISD::WIN_FTOL) {
11725 // Build the FP_TO_INT*_IN_MEM
11726 SDValue Ops[] = { Chain, Value, StackSlot };
11727 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11729 return std::make_pair(FIST, StackSlot);
11731 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11732 DAG.getVTList(MVT::Other, MVT::Glue),
11734 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11735 MVT::i32, ftol.getValue(1));
11736 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11737 MVT::i32, eax.getValue(2));
11738 SDValue Ops[] = { eax, edx };
11739 SDValue pair = IsReplace
11740 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11741 : DAG.getMergeValues(Ops, DL);
11742 return std::make_pair(pair, SDValue());
11746 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11747 const X86Subtarget *Subtarget) {
11748 MVT VT = Op->getSimpleValueType(0);
11749 SDValue In = Op->getOperand(0);
11750 MVT InVT = In.getSimpleValueType();
11753 // Optimize vectors in AVX mode:
11756 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11757 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11758 // Concat upper and lower parts.
11761 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11762 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11763 // Concat upper and lower parts.
11766 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11767 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11768 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11771 if (Subtarget->hasInt256())
11772 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11774 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11775 SDValue Undef = DAG.getUNDEF(InVT);
11776 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11777 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11778 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11780 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11781 VT.getVectorNumElements()/2);
11783 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11784 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11786 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11789 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11790 SelectionDAG &DAG) {
11791 MVT VT = Op->getSimpleValueType(0);
11792 SDValue In = Op->getOperand(0);
11793 MVT InVT = In.getSimpleValueType();
11795 unsigned int NumElts = VT.getVectorNumElements();
11796 if (NumElts != 8 && NumElts != 16)
11799 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11800 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11802 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11803 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11804 // Now we have only mask extension
11805 assert(InVT.getVectorElementType() == MVT::i1);
11806 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11807 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11808 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11809 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11810 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11811 MachinePointerInfo::getConstantPool(),
11812 false, false, false, Alignment);
11814 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11815 if (VT.is512BitVector())
11817 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11820 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11821 SelectionDAG &DAG) {
11822 if (Subtarget->hasFp256()) {
11823 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11831 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11832 SelectionDAG &DAG) {
11834 MVT VT = Op.getSimpleValueType();
11835 SDValue In = Op.getOperand(0);
11836 MVT SVT = In.getSimpleValueType();
11838 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11839 return LowerZERO_EXTEND_AVX512(Op, DAG);
11841 if (Subtarget->hasFp256()) {
11842 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11847 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11848 VT.getVectorNumElements() != SVT.getVectorNumElements());
11852 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11854 MVT VT = Op.getSimpleValueType();
11855 SDValue In = Op.getOperand(0);
11856 MVT InVT = In.getSimpleValueType();
11858 if (VT == MVT::i1) {
11859 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11860 "Invalid scalar TRUNCATE operation");
11861 if (InVT.getSizeInBits() >= 32)
11863 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11864 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11866 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11867 "Invalid TRUNCATE operation");
11869 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11870 if (VT.getVectorElementType().getSizeInBits() >=8)
11871 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11873 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11874 unsigned NumElts = InVT.getVectorNumElements();
11875 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11876 if (InVT.getSizeInBits() < 512) {
11877 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11878 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11882 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11883 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11884 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11885 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11886 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11887 MachinePointerInfo::getConstantPool(),
11888 false, false, false, Alignment);
11889 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11890 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11891 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11894 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11895 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11896 if (Subtarget->hasInt256()) {
11897 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11898 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11899 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11901 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11902 DAG.getIntPtrConstant(0));
11905 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11906 DAG.getIntPtrConstant(0));
11907 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11908 DAG.getIntPtrConstant(2));
11909 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11910 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11911 static const int ShufMask[] = {0, 2, 4, 6};
11912 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11915 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11916 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11917 if (Subtarget->hasInt256()) {
11918 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11920 SmallVector<SDValue,32> pshufbMask;
11921 for (unsigned i = 0; i < 2; ++i) {
11922 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11923 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11924 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11925 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11926 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11927 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11928 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11929 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11930 for (unsigned j = 0; j < 8; ++j)
11931 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11933 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11934 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11935 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11937 static const int ShufMask[] = {0, 2, -1, -1};
11938 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11940 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11941 DAG.getIntPtrConstant(0));
11942 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11945 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11946 DAG.getIntPtrConstant(0));
11948 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11949 DAG.getIntPtrConstant(4));
11951 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11952 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11954 // The PSHUFB mask:
11955 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11956 -1, -1, -1, -1, -1, -1, -1, -1};
11958 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11959 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11960 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11962 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11963 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11965 // The MOVLHPS Mask:
11966 static const int ShufMask2[] = {0, 1, 4, 5};
11967 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11968 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11971 // Handle truncation of V256 to V128 using shuffles.
11972 if (!VT.is128BitVector() || !InVT.is256BitVector())
11975 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11977 unsigned NumElems = VT.getVectorNumElements();
11978 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11980 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11981 // Prepare truncation shuffle mask
11982 for (unsigned i = 0; i != NumElems; ++i)
11983 MaskVec[i] = i * 2;
11984 SDValue V = DAG.getVectorShuffle(NVT, DL,
11985 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11986 DAG.getUNDEF(NVT), &MaskVec[0]);
11987 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11988 DAG.getIntPtrConstant(0));
11991 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11992 SelectionDAG &DAG) const {
11993 assert(!Op.getSimpleValueType().isVector());
11995 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11996 /*IsSigned=*/ true, /*IsReplace=*/ false);
11997 SDValue FIST = Vals.first, StackSlot = Vals.second;
11998 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11999 if (!FIST.getNode()) return Op;
12001 if (StackSlot.getNode())
12002 // Load the result.
12003 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12004 FIST, StackSlot, MachinePointerInfo(),
12005 false, false, false, 0);
12007 // The node is the result.
12011 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12012 SelectionDAG &DAG) const {
12013 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12014 /*IsSigned=*/ false, /*IsReplace=*/ false);
12015 SDValue FIST = Vals.first, StackSlot = Vals.second;
12016 assert(FIST.getNode() && "Unexpected failure");
12018 if (StackSlot.getNode())
12019 // Load the result.
12020 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12021 FIST, StackSlot, MachinePointerInfo(),
12022 false, false, false, 0);
12024 // The node is the result.
12028 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12030 MVT VT = Op.getSimpleValueType();
12031 SDValue In = Op.getOperand(0);
12032 MVT SVT = In.getSimpleValueType();
12034 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12036 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12037 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12038 In, DAG.getUNDEF(SVT)));
12041 /// The only differences between FABS and FNEG are the mask and the logic op.
12042 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12043 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12044 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12045 "Wrong opcode for lowering FABS or FNEG.");
12047 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12049 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12050 // into an FNABS. We'll lower the FABS after that if it is still in use.
12052 for (SDNode *User : Op->uses())
12053 if (User->getOpcode() == ISD::FNEG)
12056 SDValue Op0 = Op.getOperand(0);
12057 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12060 MVT VT = Op.getSimpleValueType();
12061 // Assume scalar op for initialization; update for vector if needed.
12062 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12063 // generate a 16-byte vector constant and logic op even for the scalar case.
12064 // Using a 16-byte mask allows folding the load of the mask with
12065 // the logic op, so it can save (~4 bytes) on code size.
12067 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12068 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12069 // decide if we should generate a 16-byte constant mask when we only need 4 or
12070 // 8 bytes for the scalar case.
12071 if (VT.isVector()) {
12072 EltVT = VT.getVectorElementType();
12073 NumElts = VT.getVectorNumElements();
12076 unsigned EltBits = EltVT.getSizeInBits();
12077 LLVMContext *Context = DAG.getContext();
12078 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12080 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12081 Constant *C = ConstantInt::get(*Context, MaskElt);
12082 C = ConstantVector::getSplat(NumElts, C);
12083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12084 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12085 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12086 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12087 MachinePointerInfo::getConstantPool(),
12088 false, false, false, Alignment);
12090 if (VT.isVector()) {
12091 // For a vector, cast operands to a vector type, perform the logic op,
12092 // and cast the result back to the original value type.
12093 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12094 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12095 SDValue Operand = IsFNABS ?
12096 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12097 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12098 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12099 return DAG.getNode(ISD::BITCAST, dl, VT,
12100 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12103 // If not vector, then scalar.
12104 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12105 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12106 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12109 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12111 LLVMContext *Context = DAG.getContext();
12112 SDValue Op0 = Op.getOperand(0);
12113 SDValue Op1 = Op.getOperand(1);
12115 MVT VT = Op.getSimpleValueType();
12116 MVT SrcVT = Op1.getSimpleValueType();
12118 // If second operand is smaller, extend it first.
12119 if (SrcVT.bitsLT(VT)) {
12120 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12123 // And if it is bigger, shrink it first.
12124 if (SrcVT.bitsGT(VT)) {
12125 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12129 // At this point the operands and the result should have the same
12130 // type, and that won't be f80 since that is not custom lowered.
12132 const fltSemantics &Sem =
12133 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12134 const unsigned SizeInBits = VT.getSizeInBits();
12136 SmallVector<Constant *, 4> CV(
12137 VT == MVT::f64 ? 2 : 4,
12138 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12140 // First, clear all bits but the sign bit from the second operand (sign).
12141 CV[0] = ConstantFP::get(*Context,
12142 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12143 Constant *C = ConstantVector::get(CV);
12144 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12145 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12146 MachinePointerInfo::getConstantPool(),
12147 false, false, false, 16);
12148 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12150 // Next, clear the sign bit from the first operand (magnitude).
12151 // If it's a constant, we can clear it here.
12152 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12153 APFloat APF = Op0CN->getValueAPF();
12154 // If the magnitude is a positive zero, the sign bit alone is enough.
12155 if (APF.isPosZero())
12158 CV[0] = ConstantFP::get(*Context, APF);
12160 CV[0] = ConstantFP::get(
12162 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12164 C = ConstantVector::get(CV);
12165 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12166 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12167 MachinePointerInfo::getConstantPool(),
12168 false, false, false, 16);
12169 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12170 if (!isa<ConstantFPSDNode>(Op0))
12171 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12173 // OR the magnitude value with the sign bit.
12174 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12177 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12178 SDValue N0 = Op.getOperand(0);
12180 MVT VT = Op.getSimpleValueType();
12182 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12183 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12184 DAG.getConstant(1, VT));
12185 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12188 // Check whether an OR'd tree is PTEST-able.
12189 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12190 SelectionDAG &DAG) {
12191 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12193 if (!Subtarget->hasSSE41())
12196 if (!Op->hasOneUse())
12199 SDNode *N = Op.getNode();
12202 SmallVector<SDValue, 8> Opnds;
12203 DenseMap<SDValue, unsigned> VecInMap;
12204 SmallVector<SDValue, 8> VecIns;
12205 EVT VT = MVT::Other;
12207 // Recognize a special case where a vector is casted into wide integer to
12209 Opnds.push_back(N->getOperand(0));
12210 Opnds.push_back(N->getOperand(1));
12212 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12213 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12214 // BFS traverse all OR'd operands.
12215 if (I->getOpcode() == ISD::OR) {
12216 Opnds.push_back(I->getOperand(0));
12217 Opnds.push_back(I->getOperand(1));
12218 // Re-evaluate the number of nodes to be traversed.
12219 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12223 // Quit if a non-EXTRACT_VECTOR_ELT
12224 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12227 // Quit if without a constant index.
12228 SDValue Idx = I->getOperand(1);
12229 if (!isa<ConstantSDNode>(Idx))
12232 SDValue ExtractedFromVec = I->getOperand(0);
12233 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12234 if (M == VecInMap.end()) {
12235 VT = ExtractedFromVec.getValueType();
12236 // Quit if not 128/256-bit vector.
12237 if (!VT.is128BitVector() && !VT.is256BitVector())
12239 // Quit if not the same type.
12240 if (VecInMap.begin() != VecInMap.end() &&
12241 VT != VecInMap.begin()->first.getValueType())
12243 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12244 VecIns.push_back(ExtractedFromVec);
12246 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12249 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12250 "Not extracted from 128-/256-bit vector.");
12252 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12254 for (DenseMap<SDValue, unsigned>::const_iterator
12255 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12256 // Quit if not all elements are used.
12257 if (I->second != FullMask)
12261 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12263 // Cast all vectors into TestVT for PTEST.
12264 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12265 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12267 // If more than one full vectors are evaluated, OR them first before PTEST.
12268 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12269 // Each iteration will OR 2 nodes and append the result until there is only
12270 // 1 node left, i.e. the final OR'd value of all vectors.
12271 SDValue LHS = VecIns[Slot];
12272 SDValue RHS = VecIns[Slot + 1];
12273 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12276 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12277 VecIns.back(), VecIns.back());
12280 /// \brief return true if \c Op has a use that doesn't just read flags.
12281 static bool hasNonFlagsUse(SDValue Op) {
12282 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12284 SDNode *User = *UI;
12285 unsigned UOpNo = UI.getOperandNo();
12286 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12287 // Look pass truncate.
12288 UOpNo = User->use_begin().getOperandNo();
12289 User = *User->use_begin();
12292 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12293 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12299 /// Emit nodes that will be selected as "test Op0,Op0", or something
12301 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12302 SelectionDAG &DAG) const {
12303 if (Op.getValueType() == MVT::i1) {
12304 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12305 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12306 DAG.getConstant(0, MVT::i8));
12308 // CF and OF aren't always set the way we want. Determine which
12309 // of these we need.
12310 bool NeedCF = false;
12311 bool NeedOF = false;
12314 case X86::COND_A: case X86::COND_AE:
12315 case X86::COND_B: case X86::COND_BE:
12318 case X86::COND_G: case X86::COND_GE:
12319 case X86::COND_L: case X86::COND_LE:
12320 case X86::COND_O: case X86::COND_NO: {
12321 // Check if we really need to set the
12322 // Overflow flag. If NoSignedWrap is present
12323 // that is not actually needed.
12324 switch (Op->getOpcode()) {
12329 const BinaryWithFlagsSDNode *BinNode =
12330 cast<BinaryWithFlagsSDNode>(Op.getNode());
12331 if (BinNode->hasNoSignedWrap())
12341 // See if we can use the EFLAGS value from the operand instead of
12342 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12343 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12344 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12345 // Emit a CMP with 0, which is the TEST pattern.
12346 //if (Op.getValueType() == MVT::i1)
12347 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12348 // DAG.getConstant(0, MVT::i1));
12349 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12350 DAG.getConstant(0, Op.getValueType()));
12352 unsigned Opcode = 0;
12353 unsigned NumOperands = 0;
12355 // Truncate operations may prevent the merge of the SETCC instruction
12356 // and the arithmetic instruction before it. Attempt to truncate the operands
12357 // of the arithmetic instruction and use a reduced bit-width instruction.
12358 bool NeedTruncation = false;
12359 SDValue ArithOp = Op;
12360 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12361 SDValue Arith = Op->getOperand(0);
12362 // Both the trunc and the arithmetic op need to have one user each.
12363 if (Arith->hasOneUse())
12364 switch (Arith.getOpcode()) {
12371 NeedTruncation = true;
12377 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12378 // which may be the result of a CAST. We use the variable 'Op', which is the
12379 // non-casted variable when we check for possible users.
12380 switch (ArithOp.getOpcode()) {
12382 // Due to an isel shortcoming, be conservative if this add is likely to be
12383 // selected as part of a load-modify-store instruction. When the root node
12384 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12385 // uses of other nodes in the match, such as the ADD in this case. This
12386 // leads to the ADD being left around and reselected, with the result being
12387 // two adds in the output. Alas, even if none our users are stores, that
12388 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12389 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12390 // climbing the DAG back to the root, and it doesn't seem to be worth the
12392 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12393 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12394 if (UI->getOpcode() != ISD::CopyToReg &&
12395 UI->getOpcode() != ISD::SETCC &&
12396 UI->getOpcode() != ISD::STORE)
12399 if (ConstantSDNode *C =
12400 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12401 // An add of one will be selected as an INC.
12402 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12403 Opcode = X86ISD::INC;
12408 // An add of negative one (subtract of one) will be selected as a DEC.
12409 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12410 Opcode = X86ISD::DEC;
12416 // Otherwise use a regular EFLAGS-setting add.
12417 Opcode = X86ISD::ADD;
12422 // If we have a constant logical shift that's only used in a comparison
12423 // against zero turn it into an equivalent AND. This allows turning it into
12424 // a TEST instruction later.
12425 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12426 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12427 EVT VT = Op.getValueType();
12428 unsigned BitWidth = VT.getSizeInBits();
12429 unsigned ShAmt = Op->getConstantOperandVal(1);
12430 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12432 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12433 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12434 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12435 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12437 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12438 DAG.getConstant(Mask, VT));
12439 DAG.ReplaceAllUsesWith(Op, New);
12445 // If the primary and result isn't used, don't bother using X86ISD::AND,
12446 // because a TEST instruction will be better.
12447 if (!hasNonFlagsUse(Op))
12453 // Due to the ISEL shortcoming noted above, be conservative if this op is
12454 // likely to be selected as part of a load-modify-store instruction.
12455 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12456 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12457 if (UI->getOpcode() == ISD::STORE)
12460 // Otherwise use a regular EFLAGS-setting instruction.
12461 switch (ArithOp.getOpcode()) {
12462 default: llvm_unreachable("unexpected operator!");
12463 case ISD::SUB: Opcode = X86ISD::SUB; break;
12464 case ISD::XOR: Opcode = X86ISD::XOR; break;
12465 case ISD::AND: Opcode = X86ISD::AND; break;
12467 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12468 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12469 if (EFLAGS.getNode())
12472 Opcode = X86ISD::OR;
12486 return SDValue(Op.getNode(), 1);
12492 // If we found that truncation is beneficial, perform the truncation and
12494 if (NeedTruncation) {
12495 EVT VT = Op.getValueType();
12496 SDValue WideVal = Op->getOperand(0);
12497 EVT WideVT = WideVal.getValueType();
12498 unsigned ConvertedOp = 0;
12499 // Use a target machine opcode to prevent further DAGCombine
12500 // optimizations that may separate the arithmetic operations
12501 // from the setcc node.
12502 switch (WideVal.getOpcode()) {
12504 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12505 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12506 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12507 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12508 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12513 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12514 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12515 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12516 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12522 // Emit a CMP with 0, which is the TEST pattern.
12523 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12524 DAG.getConstant(0, Op.getValueType()));
12526 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12527 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12529 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12530 DAG.ReplaceAllUsesWith(Op, New);
12531 return SDValue(New.getNode(), 1);
12534 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12536 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12537 SDLoc dl, SelectionDAG &DAG) const {
12538 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12539 if (C->getAPIntValue() == 0)
12540 return EmitTest(Op0, X86CC, dl, DAG);
12542 if (Op0.getValueType() == MVT::i1)
12543 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12546 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12547 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12548 // Do the comparison at i32 if it's smaller, besides the Atom case.
12549 // This avoids subregister aliasing issues. Keep the smaller reference
12550 // if we're optimizing for size, however, as that'll allow better folding
12551 // of memory operations.
12552 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12553 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12554 Attribute::MinSize) &&
12555 !Subtarget->isAtom()) {
12556 unsigned ExtendOp =
12557 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12558 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12559 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12561 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12562 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12563 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12565 return SDValue(Sub.getNode(), 1);
12567 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12570 /// Convert a comparison if required by the subtarget.
12571 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12572 SelectionDAG &DAG) const {
12573 // If the subtarget does not support the FUCOMI instruction, floating-point
12574 // comparisons have to be converted.
12575 if (Subtarget->hasCMov() ||
12576 Cmp.getOpcode() != X86ISD::CMP ||
12577 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12578 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12581 // The instruction selector will select an FUCOM instruction instead of
12582 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12583 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12584 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12586 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12587 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12588 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12589 DAG.getConstant(8, MVT::i8));
12590 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12591 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12594 /// The minimum architected relative accuracy is 2^-12. We need one
12595 /// Newton-Raphson step to have a good float result (24 bits of precision).
12596 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12597 DAGCombinerInfo &DCI,
12598 unsigned &RefinementSteps,
12599 bool &UseOneConstNR) const {
12600 // FIXME: We should use instruction latency models to calculate the cost of
12601 // each potential sequence, but this is very hard to do reliably because
12602 // at least Intel's Core* chips have variable timing based on the number of
12603 // significant digits in the divisor and/or sqrt operand.
12604 if (!Subtarget->useSqrtEst())
12607 EVT VT = Op.getValueType();
12609 // SSE1 has rsqrtss and rsqrtps.
12610 // TODO: Add support for AVX512 (v16f32).
12611 // It is likely not profitable to do this for f64 because a double-precision
12612 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12613 // instructions: convert to single, rsqrtss, convert back to double, refine
12614 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12615 // along with FMA, this could be a throughput win.
12616 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12617 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12618 RefinementSteps = 1;
12619 UseOneConstNR = false;
12620 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12625 /// The minimum architected relative accuracy is 2^-12. We need one
12626 /// Newton-Raphson step to have a good float result (24 bits of precision).
12627 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12628 DAGCombinerInfo &DCI,
12629 unsigned &RefinementSteps) const {
12630 // FIXME: We should use instruction latency models to calculate the cost of
12631 // each potential sequence, but this is very hard to do reliably because
12632 // at least Intel's Core* chips have variable timing based on the number of
12633 // significant digits in the divisor.
12634 if (!Subtarget->useReciprocalEst())
12637 EVT VT = Op.getValueType();
12639 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12640 // TODO: Add support for AVX512 (v16f32).
12641 // It is likely not profitable to do this for f64 because a double-precision
12642 // reciprocal estimate with refinement on x86 prior to FMA requires
12643 // 15 instructions: convert to single, rcpss, convert back to double, refine
12644 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12645 // along with FMA, this could be a throughput win.
12646 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12647 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12648 RefinementSteps = ReciprocalEstimateRefinementSteps;
12649 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12654 static bool isAllOnes(SDValue V) {
12655 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12656 return C && C->isAllOnesValue();
12659 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12660 /// if it's possible.
12661 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12662 SDLoc dl, SelectionDAG &DAG) const {
12663 SDValue Op0 = And.getOperand(0);
12664 SDValue Op1 = And.getOperand(1);
12665 if (Op0.getOpcode() == ISD::TRUNCATE)
12666 Op0 = Op0.getOperand(0);
12667 if (Op1.getOpcode() == ISD::TRUNCATE)
12668 Op1 = Op1.getOperand(0);
12671 if (Op1.getOpcode() == ISD::SHL)
12672 std::swap(Op0, Op1);
12673 if (Op0.getOpcode() == ISD::SHL) {
12674 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12675 if (And00C->getZExtValue() == 1) {
12676 // If we looked past a truncate, check that it's only truncating away
12678 unsigned BitWidth = Op0.getValueSizeInBits();
12679 unsigned AndBitWidth = And.getValueSizeInBits();
12680 if (BitWidth > AndBitWidth) {
12682 DAG.computeKnownBits(Op0, Zeros, Ones);
12683 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12687 RHS = Op0.getOperand(1);
12689 } else if (Op1.getOpcode() == ISD::Constant) {
12690 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12691 uint64_t AndRHSVal = AndRHS->getZExtValue();
12692 SDValue AndLHS = Op0;
12694 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12695 LHS = AndLHS.getOperand(0);
12696 RHS = AndLHS.getOperand(1);
12699 // Use BT if the immediate can't be encoded in a TEST instruction.
12700 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12702 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12706 if (LHS.getNode()) {
12707 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12708 // instruction. Since the shift amount is in-range-or-undefined, we know
12709 // that doing a bittest on the i32 value is ok. We extend to i32 because
12710 // the encoding for the i16 version is larger than the i32 version.
12711 // Also promote i16 to i32 for performance / code size reason.
12712 if (LHS.getValueType() == MVT::i8 ||
12713 LHS.getValueType() == MVT::i16)
12714 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12716 // If the operand types disagree, extend the shift amount to match. Since
12717 // BT ignores high bits (like shifts) we can use anyextend.
12718 if (LHS.getValueType() != RHS.getValueType())
12719 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12721 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12722 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12723 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12724 DAG.getConstant(Cond, MVT::i8), BT);
12730 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12732 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12737 // SSE Condition code mapping:
12746 switch (SetCCOpcode) {
12747 default: llvm_unreachable("Unexpected SETCC condition");
12749 case ISD::SETEQ: SSECC = 0; break;
12751 case ISD::SETGT: Swap = true; // Fallthrough
12753 case ISD::SETOLT: SSECC = 1; break;
12755 case ISD::SETGE: Swap = true; // Fallthrough
12757 case ISD::SETOLE: SSECC = 2; break;
12758 case ISD::SETUO: SSECC = 3; break;
12760 case ISD::SETNE: SSECC = 4; break;
12761 case ISD::SETULE: Swap = true; // Fallthrough
12762 case ISD::SETUGE: SSECC = 5; break;
12763 case ISD::SETULT: Swap = true; // Fallthrough
12764 case ISD::SETUGT: SSECC = 6; break;
12765 case ISD::SETO: SSECC = 7; break;
12767 case ISD::SETONE: SSECC = 8; break;
12770 std::swap(Op0, Op1);
12775 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12776 // ones, and then concatenate the result back.
12777 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12778 MVT VT = Op.getSimpleValueType();
12780 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12781 "Unsupported value type for operation");
12783 unsigned NumElems = VT.getVectorNumElements();
12785 SDValue CC = Op.getOperand(2);
12787 // Extract the LHS vectors
12788 SDValue LHS = Op.getOperand(0);
12789 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12790 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12792 // Extract the RHS vectors
12793 SDValue RHS = Op.getOperand(1);
12794 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12795 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12797 // Issue the operation on the smaller types and concatenate the result back
12798 MVT EltVT = VT.getVectorElementType();
12799 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12800 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12801 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12802 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12805 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12806 const X86Subtarget *Subtarget) {
12807 SDValue Op0 = Op.getOperand(0);
12808 SDValue Op1 = Op.getOperand(1);
12809 SDValue CC = Op.getOperand(2);
12810 MVT VT = Op.getSimpleValueType();
12813 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12814 Op.getValueType().getScalarType() == MVT::i1 &&
12815 "Cannot set masked compare for this operation");
12817 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12819 bool Unsigned = false;
12822 switch (SetCCOpcode) {
12823 default: llvm_unreachable("Unexpected SETCC condition");
12824 case ISD::SETNE: SSECC = 4; break;
12825 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12826 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12827 case ISD::SETLT: Swap = true; //fall-through
12828 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12829 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12830 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12831 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12832 case ISD::SETULE: Unsigned = true; //fall-through
12833 case ISD::SETLE: SSECC = 2; break;
12837 std::swap(Op0, Op1);
12839 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12840 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12841 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12842 DAG.getConstant(SSECC, MVT::i8));
12845 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12846 /// operand \p Op1. If non-trivial (for example because it's not constant)
12847 /// return an empty value.
12848 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12850 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12854 MVT VT = Op1.getSimpleValueType();
12855 MVT EVT = VT.getVectorElementType();
12856 unsigned n = VT.getVectorNumElements();
12857 SmallVector<SDValue, 8> ULTOp1;
12859 for (unsigned i = 0; i < n; ++i) {
12860 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12861 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12864 // Avoid underflow.
12865 APInt Val = Elt->getAPIntValue();
12869 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12872 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12875 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12876 SelectionDAG &DAG) {
12877 SDValue Op0 = Op.getOperand(0);
12878 SDValue Op1 = Op.getOperand(1);
12879 SDValue CC = Op.getOperand(2);
12880 MVT VT = Op.getSimpleValueType();
12881 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12882 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12887 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12888 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12891 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12892 unsigned Opc = X86ISD::CMPP;
12893 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12894 assert(VT.getVectorNumElements() <= 16);
12895 Opc = X86ISD::CMPM;
12897 // In the two special cases we can't handle, emit two comparisons.
12900 unsigned CombineOpc;
12901 if (SetCCOpcode == ISD::SETUEQ) {
12902 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12904 assert(SetCCOpcode == ISD::SETONE);
12905 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12908 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12909 DAG.getConstant(CC0, MVT::i8));
12910 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12911 DAG.getConstant(CC1, MVT::i8));
12912 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12914 // Handle all other FP comparisons here.
12915 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12916 DAG.getConstant(SSECC, MVT::i8));
12919 // Break 256-bit integer vector compare into smaller ones.
12920 if (VT.is256BitVector() && !Subtarget->hasInt256())
12921 return Lower256IntVSETCC(Op, DAG);
12923 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12924 EVT OpVT = Op1.getValueType();
12925 if (Subtarget->hasAVX512()) {
12926 if (Op1.getValueType().is512BitVector() ||
12927 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12928 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12929 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12931 // In AVX-512 architecture setcc returns mask with i1 elements,
12932 // But there is no compare instruction for i8 and i16 elements in KNL.
12933 // We are not talking about 512-bit operands in this case, these
12934 // types are illegal.
12936 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12937 OpVT.getVectorElementType().getSizeInBits() >= 8))
12938 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12939 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12942 // We are handling one of the integer comparisons here. Since SSE only has
12943 // GT and EQ comparisons for integer, swapping operands and multiple
12944 // operations may be required for some comparisons.
12946 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12947 bool Subus = false;
12949 switch (SetCCOpcode) {
12950 default: llvm_unreachable("Unexpected SETCC condition");
12951 case ISD::SETNE: Invert = true;
12952 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12953 case ISD::SETLT: Swap = true;
12954 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12955 case ISD::SETGE: Swap = true;
12956 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12957 Invert = true; break;
12958 case ISD::SETULT: Swap = true;
12959 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12960 FlipSigns = true; break;
12961 case ISD::SETUGE: Swap = true;
12962 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12963 FlipSigns = true; Invert = true; break;
12966 // Special case: Use min/max operations for SETULE/SETUGE
12967 MVT VET = VT.getVectorElementType();
12969 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12970 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12973 switch (SetCCOpcode) {
12975 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12976 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12979 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12982 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12983 if (!MinMax && hasSubus) {
12984 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12986 // t = psubus Op0, Op1
12987 // pcmpeq t, <0..0>
12988 switch (SetCCOpcode) {
12990 case ISD::SETULT: {
12991 // If the comparison is against a constant we can turn this into a
12992 // setule. With psubus, setule does not require a swap. This is
12993 // beneficial because the constant in the register is no longer
12994 // destructed as the destination so it can be hoisted out of a loop.
12995 // Only do this pre-AVX since vpcmp* is no longer destructive.
12996 if (Subtarget->hasAVX())
12998 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12999 if (ULEOp1.getNode()) {
13001 Subus = true; Invert = false; Swap = false;
13005 // Psubus is better than flip-sign because it requires no inversion.
13006 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13007 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13011 Opc = X86ISD::SUBUS;
13017 std::swap(Op0, Op1);
13019 // Check that the operation in question is available (most are plain SSE2,
13020 // but PCMPGTQ and PCMPEQQ have different requirements).
13021 if (VT == MVT::v2i64) {
13022 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13023 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13025 // First cast everything to the right type.
13026 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13027 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13029 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13030 // bits of the inputs before performing those operations. The lower
13031 // compare is always unsigned.
13034 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13036 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13037 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13038 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13039 Sign, Zero, Sign, Zero);
13041 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13042 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13044 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13045 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13046 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13048 // Create masks for only the low parts/high parts of the 64 bit integers.
13049 static const int MaskHi[] = { 1, 1, 3, 3 };
13050 static const int MaskLo[] = { 0, 0, 2, 2 };
13051 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13052 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13053 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13055 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13056 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13059 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13061 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13064 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13065 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13066 // pcmpeqd + pshufd + pand.
13067 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13069 // First cast everything to the right type.
13070 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13071 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13074 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13076 // Make sure the lower and upper halves are both all-ones.
13077 static const int Mask[] = { 1, 0, 3, 2 };
13078 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13079 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13082 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13084 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13088 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13089 // bits of the inputs before performing those operations.
13091 EVT EltVT = VT.getVectorElementType();
13092 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13093 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13094 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13097 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13099 // If the logical-not of the result is required, perform that now.
13101 Result = DAG.getNOT(dl, Result, VT);
13104 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13107 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13108 getZeroVector(VT, Subtarget, DAG, dl));
13113 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13115 MVT VT = Op.getSimpleValueType();
13117 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13119 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13120 && "SetCC type must be 8-bit or 1-bit integer");
13121 SDValue Op0 = Op.getOperand(0);
13122 SDValue Op1 = Op.getOperand(1);
13124 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13126 // Optimize to BT if possible.
13127 // Lower (X & (1 << N)) == 0 to BT(X, N).
13128 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13129 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13130 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13131 Op1.getOpcode() == ISD::Constant &&
13132 cast<ConstantSDNode>(Op1)->isNullValue() &&
13133 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13134 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13135 if (NewSetCC.getNode()) {
13137 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13142 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13144 if (Op1.getOpcode() == ISD::Constant &&
13145 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13146 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13147 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13149 // If the input is a setcc, then reuse the input setcc or use a new one with
13150 // the inverted condition.
13151 if (Op0.getOpcode() == X86ISD::SETCC) {
13152 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13153 bool Invert = (CC == ISD::SETNE) ^
13154 cast<ConstantSDNode>(Op1)->isNullValue();
13158 CCode = X86::GetOppositeBranchCondition(CCode);
13159 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13160 DAG.getConstant(CCode, MVT::i8),
13161 Op0.getOperand(1));
13163 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13167 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13168 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13169 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13171 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13172 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13175 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13176 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13177 if (X86CC == X86::COND_INVALID)
13180 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13181 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13182 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13183 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13185 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13189 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13190 static bool isX86LogicalCmp(SDValue Op) {
13191 unsigned Opc = Op.getNode()->getOpcode();
13192 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13193 Opc == X86ISD::SAHF)
13195 if (Op.getResNo() == 1 &&
13196 (Opc == X86ISD::ADD ||
13197 Opc == X86ISD::SUB ||
13198 Opc == X86ISD::ADC ||
13199 Opc == X86ISD::SBB ||
13200 Opc == X86ISD::SMUL ||
13201 Opc == X86ISD::UMUL ||
13202 Opc == X86ISD::INC ||
13203 Opc == X86ISD::DEC ||
13204 Opc == X86ISD::OR ||
13205 Opc == X86ISD::XOR ||
13206 Opc == X86ISD::AND))
13209 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13215 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13216 if (V.getOpcode() != ISD::TRUNCATE)
13219 SDValue VOp0 = V.getOperand(0);
13220 unsigned InBits = VOp0.getValueSizeInBits();
13221 unsigned Bits = V.getValueSizeInBits();
13222 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13225 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13226 bool addTest = true;
13227 SDValue Cond = Op.getOperand(0);
13228 SDValue Op1 = Op.getOperand(1);
13229 SDValue Op2 = Op.getOperand(2);
13231 EVT VT = Op1.getValueType();
13234 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13235 // are available or VBLENDV if AVX is available.
13236 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13237 if (Cond.getOpcode() == ISD::SETCC &&
13238 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13239 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13240 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13241 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13242 int SSECC = translateX86FSETCC(
13243 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13246 if (Subtarget->hasAVX512()) {
13247 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13248 DAG.getConstant(SSECC, MVT::i8));
13249 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13252 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13253 DAG.getConstant(SSECC, MVT::i8));
13255 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13256 // of 3 logic instructions for size savings and potentially speed.
13257 // Unfortunately, there is no scalar form of VBLENDV.
13259 // If either operand is a constant, don't try this. We can expect to
13260 // optimize away at least one of the logic instructions later in that
13261 // case, so that sequence would be faster than a variable blend.
13263 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13264 // uses XMM0 as the selection register. That may need just as many
13265 // instructions as the AND/ANDN/OR sequence due to register moves, so
13268 if (Subtarget->hasAVX() &&
13269 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13271 // Convert to vectors, do a VSELECT, and convert back to scalar.
13272 // All of the conversions should be optimized away.
13274 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13275 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13276 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13277 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13279 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13280 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13282 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13284 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13285 VSel, DAG.getIntPtrConstant(0));
13287 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13288 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13289 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13293 if (Cond.getOpcode() == ISD::SETCC) {
13294 SDValue NewCond = LowerSETCC(Cond, DAG);
13295 if (NewCond.getNode())
13299 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13300 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13301 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13302 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13303 if (Cond.getOpcode() == X86ISD::SETCC &&
13304 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13305 isZero(Cond.getOperand(1).getOperand(1))) {
13306 SDValue Cmp = Cond.getOperand(1);
13308 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13310 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13311 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13312 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13314 SDValue CmpOp0 = Cmp.getOperand(0);
13315 // Apply further optimizations for special cases
13316 // (select (x != 0), -1, 0) -> neg & sbb
13317 // (select (x == 0), 0, -1) -> neg & sbb
13318 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13319 if (YC->isNullValue() &&
13320 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13321 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13322 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13323 DAG.getConstant(0, CmpOp0.getValueType()),
13325 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13326 DAG.getConstant(X86::COND_B, MVT::i8),
13327 SDValue(Neg.getNode(), 1));
13331 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13332 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13333 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13335 SDValue Res = // Res = 0 or -1.
13336 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13337 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13339 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13340 Res = DAG.getNOT(DL, Res, Res.getValueType());
13342 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13343 if (!N2C || !N2C->isNullValue())
13344 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13349 // Look past (and (setcc_carry (cmp ...)), 1).
13350 if (Cond.getOpcode() == ISD::AND &&
13351 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13352 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13353 if (C && C->getAPIntValue() == 1)
13354 Cond = Cond.getOperand(0);
13357 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13358 // setting operand in place of the X86ISD::SETCC.
13359 unsigned CondOpcode = Cond.getOpcode();
13360 if (CondOpcode == X86ISD::SETCC ||
13361 CondOpcode == X86ISD::SETCC_CARRY) {
13362 CC = Cond.getOperand(0);
13364 SDValue Cmp = Cond.getOperand(1);
13365 unsigned Opc = Cmp.getOpcode();
13366 MVT VT = Op.getSimpleValueType();
13368 bool IllegalFPCMov = false;
13369 if (VT.isFloatingPoint() && !VT.isVector() &&
13370 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13371 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13373 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13374 Opc == X86ISD::BT) { // FIXME
13378 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13379 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13380 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13381 Cond.getOperand(0).getValueType() != MVT::i8)) {
13382 SDValue LHS = Cond.getOperand(0);
13383 SDValue RHS = Cond.getOperand(1);
13384 unsigned X86Opcode;
13387 switch (CondOpcode) {
13388 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13389 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13390 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13391 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13392 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13393 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13394 default: llvm_unreachable("unexpected overflowing operator");
13396 if (CondOpcode == ISD::UMULO)
13397 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13400 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13402 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13404 if (CondOpcode == ISD::UMULO)
13405 Cond = X86Op.getValue(2);
13407 Cond = X86Op.getValue(1);
13409 CC = DAG.getConstant(X86Cond, MVT::i8);
13414 // Look pass the truncate if the high bits are known zero.
13415 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13416 Cond = Cond.getOperand(0);
13418 // We know the result of AND is compared against zero. Try to match
13420 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13421 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13422 if (NewSetCC.getNode()) {
13423 CC = NewSetCC.getOperand(0);
13424 Cond = NewSetCC.getOperand(1);
13431 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13432 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13435 // a < b ? -1 : 0 -> RES = ~setcc_carry
13436 // a < b ? 0 : -1 -> RES = setcc_carry
13437 // a >= b ? -1 : 0 -> RES = setcc_carry
13438 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13439 if (Cond.getOpcode() == X86ISD::SUB) {
13440 Cond = ConvertCmpIfNecessary(Cond, DAG);
13441 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13443 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13444 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13445 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13446 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13447 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13448 return DAG.getNOT(DL, Res, Res.getValueType());
13453 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13454 // widen the cmov and push the truncate through. This avoids introducing a new
13455 // branch during isel and doesn't add any extensions.
13456 if (Op.getValueType() == MVT::i8 &&
13457 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13458 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13459 if (T1.getValueType() == T2.getValueType() &&
13460 // Blacklist CopyFromReg to avoid partial register stalls.
13461 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13462 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13463 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13464 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13468 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13469 // condition is true.
13470 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13471 SDValue Ops[] = { Op2, Op1, CC, Cond };
13472 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13475 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13476 SelectionDAG &DAG) {
13477 MVT VT = Op->getSimpleValueType(0);
13478 SDValue In = Op->getOperand(0);
13479 MVT InVT = In.getSimpleValueType();
13480 MVT VTElt = VT.getVectorElementType();
13481 MVT InVTElt = InVT.getVectorElementType();
13485 if ((InVTElt == MVT::i1) &&
13486 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13487 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13489 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13490 VTElt.getSizeInBits() <= 16)) ||
13492 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13493 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13495 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13496 VTElt.getSizeInBits() >= 32))))
13497 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13499 unsigned int NumElts = VT.getVectorNumElements();
13501 if (NumElts != 8 && NumElts != 16)
13504 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13505 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13506 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13507 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13510 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13511 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13513 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13514 Constant *C = ConstantInt::get(*DAG.getContext(),
13515 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13517 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13518 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13519 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13520 MachinePointerInfo::getConstantPool(),
13521 false, false, false, Alignment);
13522 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13523 if (VT.is512BitVector())
13525 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13528 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13529 SelectionDAG &DAG) {
13530 MVT VT = Op->getSimpleValueType(0);
13531 SDValue In = Op->getOperand(0);
13532 MVT InVT = In.getSimpleValueType();
13535 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13536 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13538 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13539 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13540 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13543 if (Subtarget->hasInt256())
13544 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13546 // Optimize vectors in AVX mode
13547 // Sign extend v8i16 to v8i32 and
13550 // Divide input vector into two parts
13551 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13552 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13553 // concat the vectors to original VT
13555 unsigned NumElems = InVT.getVectorNumElements();
13556 SDValue Undef = DAG.getUNDEF(InVT);
13558 SmallVector<int,8> ShufMask1(NumElems, -1);
13559 for (unsigned i = 0; i != NumElems/2; ++i)
13562 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13564 SmallVector<int,8> ShufMask2(NumElems, -1);
13565 for (unsigned i = 0; i != NumElems/2; ++i)
13566 ShufMask2[i] = i + NumElems/2;
13568 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13570 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13571 VT.getVectorNumElements()/2);
13573 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13574 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13576 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13579 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13580 // may emit an illegal shuffle but the expansion is still better than scalar
13581 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13582 // we'll emit a shuffle and a arithmetic shift.
13583 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13584 // TODO: It is possible to support ZExt by zeroing the undef values during
13585 // the shuffle phase or after the shuffle.
13586 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13587 SelectionDAG &DAG) {
13588 MVT RegVT = Op.getSimpleValueType();
13589 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13590 assert(RegVT.isInteger() &&
13591 "We only custom lower integer vector sext loads.");
13593 // Nothing useful we can do without SSE2 shuffles.
13594 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13596 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13598 EVT MemVT = Ld->getMemoryVT();
13599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13600 unsigned RegSz = RegVT.getSizeInBits();
13602 ISD::LoadExtType Ext = Ld->getExtensionType();
13604 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13605 && "Only anyext and sext are currently implemented.");
13606 assert(MemVT != RegVT && "Cannot extend to the same type");
13607 assert(MemVT.isVector() && "Must load a vector from memory");
13609 unsigned NumElems = RegVT.getVectorNumElements();
13610 unsigned MemSz = MemVT.getSizeInBits();
13611 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13613 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13614 // The only way in which we have a legal 256-bit vector result but not the
13615 // integer 256-bit operations needed to directly lower a sextload is if we
13616 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13617 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13618 // correctly legalized. We do this late to allow the canonical form of
13619 // sextload to persist throughout the rest of the DAG combiner -- it wants
13620 // to fold together any extensions it can, and so will fuse a sign_extend
13621 // of an sextload into a sextload targeting a wider value.
13623 if (MemSz == 128) {
13624 // Just switch this to a normal load.
13625 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13626 "it must be a legal 128-bit vector "
13628 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13629 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13630 Ld->isInvariant(), Ld->getAlignment());
13632 assert(MemSz < 128 &&
13633 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13634 // Do an sext load to a 128-bit vector type. We want to use the same
13635 // number of elements, but elements half as wide. This will end up being
13636 // recursively lowered by this routine, but will succeed as we definitely
13637 // have all the necessary features if we're using AVX1.
13639 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13640 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13642 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13643 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13644 Ld->isNonTemporal(), Ld->isInvariant(),
13645 Ld->getAlignment());
13648 // Replace chain users with the new chain.
13649 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13650 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13652 // Finally, do a normal sign-extend to the desired register.
13653 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13656 // All sizes must be a power of two.
13657 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13658 "Non-power-of-two elements are not custom lowered!");
13660 // Attempt to load the original value using scalar loads.
13661 // Find the largest scalar type that divides the total loaded size.
13662 MVT SclrLoadTy = MVT::i8;
13663 for (MVT Tp : MVT::integer_valuetypes()) {
13664 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13669 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13670 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13672 SclrLoadTy = MVT::f64;
13674 // Calculate the number of scalar loads that we need to perform
13675 // in order to load our vector from memory.
13676 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13678 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13679 "Can only lower sext loads with a single scalar load!");
13681 unsigned loadRegZize = RegSz;
13682 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13685 // Represent our vector as a sequence of elements which are the
13686 // largest scalar that we can load.
13687 EVT LoadUnitVecVT = EVT::getVectorVT(
13688 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13690 // Represent the data using the same element type that is stored in
13691 // memory. In practice, we ''widen'' MemVT.
13693 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13694 loadRegZize / MemVT.getScalarType().getSizeInBits());
13696 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13697 "Invalid vector type");
13699 // We can't shuffle using an illegal type.
13700 assert(TLI.isTypeLegal(WideVecVT) &&
13701 "We only lower types that form legal widened vector types");
13703 SmallVector<SDValue, 8> Chains;
13704 SDValue Ptr = Ld->getBasePtr();
13705 SDValue Increment =
13706 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13707 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13709 for (unsigned i = 0; i < NumLoads; ++i) {
13710 // Perform a single load.
13711 SDValue ScalarLoad =
13712 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13713 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13714 Ld->getAlignment());
13715 Chains.push_back(ScalarLoad.getValue(1));
13716 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13717 // another round of DAGCombining.
13719 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13721 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13722 ScalarLoad, DAG.getIntPtrConstant(i));
13724 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13727 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13729 // Bitcast the loaded value to a vector of the original element type, in
13730 // the size of the target vector type.
13731 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13732 unsigned SizeRatio = RegSz / MemSz;
13734 if (Ext == ISD::SEXTLOAD) {
13735 // If we have SSE4.1, we can directly emit a VSEXT node.
13736 if (Subtarget->hasSSE41()) {
13737 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13738 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13742 // Otherwise we'll shuffle the small elements in the high bits of the
13743 // larger type and perform an arithmetic shift. If the shift is not legal
13744 // it's better to scalarize.
13745 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13746 "We can't implement a sext load without an arithmetic right shift!");
13748 // Redistribute the loaded elements into the different locations.
13749 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13750 for (unsigned i = 0; i != NumElems; ++i)
13751 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13753 SDValue Shuff = DAG.getVectorShuffle(
13754 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13756 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13758 // Build the arithmetic shift.
13759 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13760 MemVT.getVectorElementType().getSizeInBits();
13762 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13764 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13768 // Redistribute the loaded elements into the different locations.
13769 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13770 for (unsigned i = 0; i != NumElems; ++i)
13771 ShuffleVec[i * SizeRatio] = i;
13773 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13774 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13776 // Bitcast to the requested type.
13777 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13778 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13782 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13783 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13784 // from the AND / OR.
13785 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13786 Opc = Op.getOpcode();
13787 if (Opc != ISD::OR && Opc != ISD::AND)
13789 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13790 Op.getOperand(0).hasOneUse() &&
13791 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13792 Op.getOperand(1).hasOneUse());
13795 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13796 // 1 and that the SETCC node has a single use.
13797 static bool isXor1OfSetCC(SDValue Op) {
13798 if (Op.getOpcode() != ISD::XOR)
13800 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13801 if (N1C && N1C->getAPIntValue() == 1) {
13802 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13803 Op.getOperand(0).hasOneUse();
13808 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13809 bool addTest = true;
13810 SDValue Chain = Op.getOperand(0);
13811 SDValue Cond = Op.getOperand(1);
13812 SDValue Dest = Op.getOperand(2);
13815 bool Inverted = false;
13817 if (Cond.getOpcode() == ISD::SETCC) {
13818 // Check for setcc([su]{add,sub,mul}o == 0).
13819 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13820 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13821 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13822 Cond.getOperand(0).getResNo() == 1 &&
13823 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13824 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13825 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13826 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13827 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13828 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13830 Cond = Cond.getOperand(0);
13832 SDValue NewCond = LowerSETCC(Cond, DAG);
13833 if (NewCond.getNode())
13838 // FIXME: LowerXALUO doesn't handle these!!
13839 else if (Cond.getOpcode() == X86ISD::ADD ||
13840 Cond.getOpcode() == X86ISD::SUB ||
13841 Cond.getOpcode() == X86ISD::SMUL ||
13842 Cond.getOpcode() == X86ISD::UMUL)
13843 Cond = LowerXALUO(Cond, DAG);
13846 // Look pass (and (setcc_carry (cmp ...)), 1).
13847 if (Cond.getOpcode() == ISD::AND &&
13848 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13849 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13850 if (C && C->getAPIntValue() == 1)
13851 Cond = Cond.getOperand(0);
13854 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13855 // setting operand in place of the X86ISD::SETCC.
13856 unsigned CondOpcode = Cond.getOpcode();
13857 if (CondOpcode == X86ISD::SETCC ||
13858 CondOpcode == X86ISD::SETCC_CARRY) {
13859 CC = Cond.getOperand(0);
13861 SDValue Cmp = Cond.getOperand(1);
13862 unsigned Opc = Cmp.getOpcode();
13863 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13864 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13868 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13872 // These can only come from an arithmetic instruction with overflow,
13873 // e.g. SADDO, UADDO.
13874 Cond = Cond.getNode()->getOperand(1);
13880 CondOpcode = Cond.getOpcode();
13881 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13882 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13883 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13884 Cond.getOperand(0).getValueType() != MVT::i8)) {
13885 SDValue LHS = Cond.getOperand(0);
13886 SDValue RHS = Cond.getOperand(1);
13887 unsigned X86Opcode;
13890 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13891 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13893 switch (CondOpcode) {
13894 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13896 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13898 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13901 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13902 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13906 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13909 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13910 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13911 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13912 default: llvm_unreachable("unexpected overflowing operator");
13915 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13916 if (CondOpcode == ISD::UMULO)
13917 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13920 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13922 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13924 if (CondOpcode == ISD::UMULO)
13925 Cond = X86Op.getValue(2);
13927 Cond = X86Op.getValue(1);
13929 CC = DAG.getConstant(X86Cond, MVT::i8);
13933 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13934 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13935 if (CondOpc == ISD::OR) {
13936 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13937 // two branches instead of an explicit OR instruction with a
13939 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13940 isX86LogicalCmp(Cmp)) {
13941 CC = Cond.getOperand(0).getOperand(0);
13942 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13943 Chain, Dest, CC, Cmp);
13944 CC = Cond.getOperand(1).getOperand(0);
13948 } else { // ISD::AND
13949 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13950 // two branches instead of an explicit AND instruction with a
13951 // separate test. However, we only do this if this block doesn't
13952 // have a fall-through edge, because this requires an explicit
13953 // jmp when the condition is false.
13954 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13955 isX86LogicalCmp(Cmp) &&
13956 Op.getNode()->hasOneUse()) {
13957 X86::CondCode CCode =
13958 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13959 CCode = X86::GetOppositeBranchCondition(CCode);
13960 CC = DAG.getConstant(CCode, MVT::i8);
13961 SDNode *User = *Op.getNode()->use_begin();
13962 // Look for an unconditional branch following this conditional branch.
13963 // We need this because we need to reverse the successors in order
13964 // to implement FCMP_OEQ.
13965 if (User->getOpcode() == ISD::BR) {
13966 SDValue FalseBB = User->getOperand(1);
13968 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13969 assert(NewBR == User);
13973 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13974 Chain, Dest, CC, Cmp);
13975 X86::CondCode CCode =
13976 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13977 CCode = X86::GetOppositeBranchCondition(CCode);
13978 CC = DAG.getConstant(CCode, MVT::i8);
13984 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13985 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13986 // It should be transformed during dag combiner except when the condition
13987 // is set by a arithmetics with overflow node.
13988 X86::CondCode CCode =
13989 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13990 CCode = X86::GetOppositeBranchCondition(CCode);
13991 CC = DAG.getConstant(CCode, MVT::i8);
13992 Cond = Cond.getOperand(0).getOperand(1);
13994 } else if (Cond.getOpcode() == ISD::SETCC &&
13995 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13996 // For FCMP_OEQ, we can emit
13997 // two branches instead of an explicit AND instruction with a
13998 // separate test. However, we only do this if this block doesn't
13999 // have a fall-through edge, because this requires an explicit
14000 // jmp when the condition is false.
14001 if (Op.getNode()->hasOneUse()) {
14002 SDNode *User = *Op.getNode()->use_begin();
14003 // Look for an unconditional branch following this conditional branch.
14004 // We need this because we need to reverse the successors in order
14005 // to implement FCMP_OEQ.
14006 if (User->getOpcode() == ISD::BR) {
14007 SDValue FalseBB = User->getOperand(1);
14009 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14010 assert(NewBR == User);
14014 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14015 Cond.getOperand(0), Cond.getOperand(1));
14016 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14017 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14018 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14019 Chain, Dest, CC, Cmp);
14020 CC = DAG.getConstant(X86::COND_P, MVT::i8);
14025 } else if (Cond.getOpcode() == ISD::SETCC &&
14026 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14027 // For FCMP_UNE, we can emit
14028 // two branches instead of an explicit AND instruction with a
14029 // separate test. However, we only do this if this block doesn't
14030 // have a fall-through edge, because this requires an explicit
14031 // jmp when the condition is false.
14032 if (Op.getNode()->hasOneUse()) {
14033 SDNode *User = *Op.getNode()->use_begin();
14034 // Look for an unconditional branch following this conditional branch.
14035 // We need this because we need to reverse the successors in order
14036 // to implement FCMP_UNE.
14037 if (User->getOpcode() == ISD::BR) {
14038 SDValue FalseBB = User->getOperand(1);
14040 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14041 assert(NewBR == User);
14044 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14045 Cond.getOperand(0), Cond.getOperand(1));
14046 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14047 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14048 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14049 Chain, Dest, CC, Cmp);
14050 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14060 // Look pass the truncate if the high bits are known zero.
14061 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14062 Cond = Cond.getOperand(0);
14064 // We know the result of AND is compared against zero. Try to match
14066 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14067 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14068 if (NewSetCC.getNode()) {
14069 CC = NewSetCC.getOperand(0);
14070 Cond = NewSetCC.getOperand(1);
14077 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14078 CC = DAG.getConstant(X86Cond, MVT::i8);
14079 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14081 Cond = ConvertCmpIfNecessary(Cond, DAG);
14082 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14083 Chain, Dest, CC, Cond);
14086 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14087 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14088 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14089 // that the guard pages used by the OS virtual memory manager are allocated in
14090 // correct sequence.
14092 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14093 SelectionDAG &DAG) const {
14094 MachineFunction &MF = DAG.getMachineFunction();
14095 bool SplitStack = MF.shouldSplitStack();
14096 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14101 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14102 SDNode* Node = Op.getNode();
14104 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14105 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14106 " not tell us which reg is the stack pointer!");
14107 EVT VT = Node->getValueType(0);
14108 SDValue Tmp1 = SDValue(Node, 0);
14109 SDValue Tmp2 = SDValue(Node, 1);
14110 SDValue Tmp3 = Node->getOperand(2);
14111 SDValue Chain = Tmp1.getOperand(0);
14113 // Chain the dynamic stack allocation so that it doesn't modify the stack
14114 // pointer when other instructions are using the stack.
14115 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14118 SDValue Size = Tmp2.getOperand(1);
14119 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14120 Chain = SP.getValue(1);
14121 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14122 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14123 unsigned StackAlign = TFI.getStackAlignment();
14124 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14125 if (Align > StackAlign)
14126 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14127 DAG.getConstant(-(uint64_t)Align, VT));
14128 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14130 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14131 DAG.getIntPtrConstant(0, true), SDValue(),
14134 SDValue Ops[2] = { Tmp1, Tmp2 };
14135 return DAG.getMergeValues(Ops, dl);
14139 SDValue Chain = Op.getOperand(0);
14140 SDValue Size = Op.getOperand(1);
14141 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14142 EVT VT = Op.getNode()->getValueType(0);
14144 bool Is64Bit = Subtarget->is64Bit();
14145 EVT SPTy = getPointerTy();
14148 MachineRegisterInfo &MRI = MF.getRegInfo();
14151 // The 64 bit implementation of segmented stacks needs to clobber both r10
14152 // r11. This makes it impossible to use it along with nested parameters.
14153 const Function *F = MF.getFunction();
14155 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14157 if (I->hasNestAttr())
14158 report_fatal_error("Cannot use segmented stacks with functions that "
14159 "have nested arguments.");
14162 const TargetRegisterClass *AddrRegClass =
14163 getRegClassFor(getPointerTy());
14164 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14165 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14166 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14167 DAG.getRegister(Vreg, SPTy));
14168 SDValue Ops1[2] = { Value, Chain };
14169 return DAG.getMergeValues(Ops1, dl);
14172 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14174 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14175 Flag = Chain.getValue(1);
14176 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14178 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14180 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14181 unsigned SPReg = RegInfo->getStackRegister();
14182 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14183 Chain = SP.getValue(1);
14186 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14187 DAG.getConstant(-(uint64_t)Align, VT));
14188 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14191 SDValue Ops1[2] = { SP, Chain };
14192 return DAG.getMergeValues(Ops1, dl);
14196 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14197 MachineFunction &MF = DAG.getMachineFunction();
14198 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14200 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14203 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14204 // vastart just stores the address of the VarArgsFrameIndex slot into the
14205 // memory location argument.
14206 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14208 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14209 MachinePointerInfo(SV), false, false, 0);
14213 // gp_offset (0 - 6 * 8)
14214 // fp_offset (48 - 48 + 8 * 16)
14215 // overflow_arg_area (point to parameters coming in memory).
14217 SmallVector<SDValue, 8> MemOps;
14218 SDValue FIN = Op.getOperand(1);
14220 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14221 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14223 FIN, MachinePointerInfo(SV), false, false, 0);
14224 MemOps.push_back(Store);
14227 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14228 FIN, DAG.getIntPtrConstant(4));
14229 Store = DAG.getStore(Op.getOperand(0), DL,
14230 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14232 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14233 MemOps.push_back(Store);
14235 // Store ptr to overflow_arg_area
14236 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14237 FIN, DAG.getIntPtrConstant(4));
14238 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14240 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14241 MachinePointerInfo(SV, 8),
14243 MemOps.push_back(Store);
14245 // Store ptr to reg_save_area.
14246 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14247 FIN, DAG.getIntPtrConstant(8));
14248 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14250 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14251 MachinePointerInfo(SV, 16), false, false, 0);
14252 MemOps.push_back(Store);
14253 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14256 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14257 assert(Subtarget->is64Bit() &&
14258 "LowerVAARG only handles 64-bit va_arg!");
14259 assert((Subtarget->isTargetLinux() ||
14260 Subtarget->isTargetDarwin()) &&
14261 "Unhandled target in LowerVAARG");
14262 assert(Op.getNode()->getNumOperands() == 4);
14263 SDValue Chain = Op.getOperand(0);
14264 SDValue SrcPtr = Op.getOperand(1);
14265 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14266 unsigned Align = Op.getConstantOperandVal(3);
14269 EVT ArgVT = Op.getNode()->getValueType(0);
14270 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14271 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14274 // Decide which area this value should be read from.
14275 // TODO: Implement the AMD64 ABI in its entirety. This simple
14276 // selection mechanism works only for the basic types.
14277 if (ArgVT == MVT::f80) {
14278 llvm_unreachable("va_arg for f80 not yet implemented");
14279 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14280 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14281 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14282 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14284 llvm_unreachable("Unhandled argument type in LowerVAARG");
14287 if (ArgMode == 2) {
14288 // Sanity Check: Make sure using fp_offset makes sense.
14289 assert(!DAG.getTarget().Options.UseSoftFloat &&
14290 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14291 Attribute::NoImplicitFloat)) &&
14292 Subtarget->hasSSE1());
14295 // Insert VAARG_64 node into the DAG
14296 // VAARG_64 returns two values: Variable Argument Address, Chain
14297 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14298 DAG.getConstant(ArgMode, MVT::i8),
14299 DAG.getConstant(Align, MVT::i32)};
14300 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14301 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14302 VTs, InstOps, MVT::i64,
14303 MachinePointerInfo(SV),
14305 /*Volatile=*/false,
14307 /*WriteMem=*/true);
14308 Chain = VAARG.getValue(1);
14310 // Load the next argument and return it
14311 return DAG.getLoad(ArgVT, dl,
14314 MachinePointerInfo(),
14315 false, false, false, 0);
14318 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14319 SelectionDAG &DAG) {
14320 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14321 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14322 SDValue Chain = Op.getOperand(0);
14323 SDValue DstPtr = Op.getOperand(1);
14324 SDValue SrcPtr = Op.getOperand(2);
14325 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14326 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14329 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14330 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14332 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14335 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14336 // amount is a constant. Takes immediate version of shift as input.
14337 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14338 SDValue SrcOp, uint64_t ShiftAmt,
14339 SelectionDAG &DAG) {
14340 MVT ElementType = VT.getVectorElementType();
14342 // Fold this packed shift into its first operand if ShiftAmt is 0.
14346 // Check for ShiftAmt >= element width
14347 if (ShiftAmt >= ElementType.getSizeInBits()) {
14348 if (Opc == X86ISD::VSRAI)
14349 ShiftAmt = ElementType.getSizeInBits() - 1;
14351 return DAG.getConstant(0, VT);
14354 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14355 && "Unknown target vector shift-by-constant node");
14357 // Fold this packed vector shift into a build vector if SrcOp is a
14358 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14359 if (VT == SrcOp.getSimpleValueType() &&
14360 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14361 SmallVector<SDValue, 8> Elts;
14362 unsigned NumElts = SrcOp->getNumOperands();
14363 ConstantSDNode *ND;
14366 default: llvm_unreachable(nullptr);
14367 case X86ISD::VSHLI:
14368 for (unsigned i=0; i!=NumElts; ++i) {
14369 SDValue CurrentOp = SrcOp->getOperand(i);
14370 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14371 Elts.push_back(CurrentOp);
14374 ND = cast<ConstantSDNode>(CurrentOp);
14375 const APInt &C = ND->getAPIntValue();
14376 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14379 case X86ISD::VSRLI:
14380 for (unsigned i=0; i!=NumElts; ++i) {
14381 SDValue CurrentOp = SrcOp->getOperand(i);
14382 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14383 Elts.push_back(CurrentOp);
14386 ND = cast<ConstantSDNode>(CurrentOp);
14387 const APInt &C = ND->getAPIntValue();
14388 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14391 case X86ISD::VSRAI:
14392 for (unsigned i=0; i!=NumElts; ++i) {
14393 SDValue CurrentOp = SrcOp->getOperand(i);
14394 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14395 Elts.push_back(CurrentOp);
14398 ND = cast<ConstantSDNode>(CurrentOp);
14399 const APInt &C = ND->getAPIntValue();
14400 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14405 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14408 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14411 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14412 // may or may not be a constant. Takes immediate version of shift as input.
14413 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14414 SDValue SrcOp, SDValue ShAmt,
14415 SelectionDAG &DAG) {
14416 MVT SVT = ShAmt.getSimpleValueType();
14417 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14419 // Catch shift-by-constant.
14420 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14421 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14422 CShAmt->getZExtValue(), DAG);
14424 // Change opcode to non-immediate version
14426 default: llvm_unreachable("Unknown target vector shift node");
14427 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14428 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14429 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14432 const X86Subtarget &Subtarget =
14433 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14434 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14435 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14436 // Let the shuffle legalizer expand this shift amount node.
14437 SDValue Op0 = ShAmt.getOperand(0);
14438 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14439 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14441 // Need to build a vector containing shift amount.
14442 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14443 SmallVector<SDValue, 4> ShOps;
14444 ShOps.push_back(ShAmt);
14445 if (SVT == MVT::i32) {
14446 ShOps.push_back(DAG.getConstant(0, SVT));
14447 ShOps.push_back(DAG.getUNDEF(SVT));
14449 ShOps.push_back(DAG.getUNDEF(SVT));
14451 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14452 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14455 // The return type has to be a 128-bit type with the same element
14456 // type as the input type.
14457 MVT EltVT = VT.getVectorElementType();
14458 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14460 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14461 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14464 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14465 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14466 /// necessary casting for \p Mask when lowering masking intrinsics.
14467 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14468 SDValue PreservedSrc,
14469 const X86Subtarget *Subtarget,
14470 SelectionDAG &DAG) {
14471 EVT VT = Op.getValueType();
14472 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14473 MVT::i1, VT.getVectorNumElements());
14474 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14475 Mask.getValueType().getSizeInBits());
14478 assert(MaskVT.isSimple() && "invalid mask type");
14480 if (isAllOnes(Mask))
14483 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14484 // are extracted by EXTRACT_SUBVECTOR.
14485 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14486 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14487 DAG.getIntPtrConstant(0));
14489 switch (Op.getOpcode()) {
14491 case X86ISD::PCMPEQM:
14492 case X86ISD::PCMPGTM:
14494 case X86ISD::CMPMU:
14495 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14497 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14498 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14499 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14502 /// \brief Creates an SDNode for a predicated scalar operation.
14503 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14504 /// The mask is comming as MVT::i8 and it should be truncated
14505 /// to MVT::i1 while lowering masking intrinsics.
14506 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14507 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14508 /// a scalar instruction.
14509 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14510 SDValue PreservedSrc,
14511 const X86Subtarget *Subtarget,
14512 SelectionDAG &DAG) {
14513 if (isAllOnes(Mask))
14516 EVT VT = Op.getValueType();
14518 // The mask should be of type MVT::i1
14519 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14521 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14522 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14523 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14526 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14527 SelectionDAG &DAG) {
14529 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14530 EVT VT = Op.getValueType();
14531 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14533 switch(IntrData->Type) {
14534 case INTR_TYPE_1OP:
14535 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14536 case INTR_TYPE_2OP:
14537 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14539 case INTR_TYPE_3OP:
14540 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14541 Op.getOperand(2), Op.getOperand(3));
14542 case INTR_TYPE_1OP_MASK_RM: {
14543 SDValue Src = Op.getOperand(1);
14544 SDValue Src0 = Op.getOperand(2);
14545 SDValue Mask = Op.getOperand(3);
14546 SDValue RoundingMode = Op.getOperand(4);
14547 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14549 Mask, Src0, Subtarget, DAG);
14551 case INTR_TYPE_SCALAR_MASK_RM: {
14552 SDValue Src1 = Op.getOperand(1);
14553 SDValue Src2 = Op.getOperand(2);
14554 SDValue Src0 = Op.getOperand(3);
14555 SDValue Mask = Op.getOperand(4);
14556 // There are 2 kinds of intrinsics in this group:
14557 // (1) With supress-all-exceptions (sae) - 6 operands
14558 // (2) With rounding mode and sae - 7 operands.
14559 if (Op.getNumOperands() == 6) {
14560 SDValue Sae = Op.getOperand(5);
14561 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14563 Mask, Src0, Subtarget, DAG);
14565 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14566 SDValue RoundingMode = Op.getOperand(5);
14567 SDValue Sae = Op.getOperand(6);
14568 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14569 RoundingMode, Sae),
14570 Mask, Src0, Subtarget, DAG);
14572 case INTR_TYPE_2OP_MASK: {
14573 SDValue Src1 = Op.getOperand(1);
14574 SDValue Src2 = Op.getOperand(2);
14575 SDValue PassThru = Op.getOperand(3);
14576 SDValue Mask = Op.getOperand(4);
14577 // We specify 2 possible opcodes for intrinsics with rounding modes.
14578 // First, we check if the intrinsic may have non-default rounding mode,
14579 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14580 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14581 if (IntrWithRoundingModeOpcode != 0) {
14582 SDValue Rnd = Op.getOperand(5);
14583 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14584 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14585 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14586 dl, Op.getValueType(),
14588 Mask, PassThru, Subtarget, DAG);
14591 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14593 Mask, PassThru, Subtarget, DAG);
14595 case FMA_OP_MASK: {
14596 SDValue Src1 = Op.getOperand(1);
14597 SDValue Src2 = Op.getOperand(2);
14598 SDValue Src3 = Op.getOperand(3);
14599 SDValue Mask = Op.getOperand(4);
14600 // We specify 2 possible opcodes for intrinsics with rounding modes.
14601 // First, we check if the intrinsic may have non-default rounding mode,
14602 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14603 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14604 if (IntrWithRoundingModeOpcode != 0) {
14605 SDValue Rnd = Op.getOperand(5);
14606 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14607 X86::STATIC_ROUNDING::CUR_DIRECTION)
14608 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14609 dl, Op.getValueType(),
14610 Src1, Src2, Src3, Rnd),
14611 Mask, Src1, Subtarget, DAG);
14613 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14614 dl, Op.getValueType(),
14616 Mask, Src1, Subtarget, DAG);
14619 case CMP_MASK_CC: {
14620 // Comparison intrinsics with masks.
14621 // Example of transformation:
14622 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14623 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14625 // (v8i1 (insert_subvector undef,
14626 // (v2i1 (and (PCMPEQM %a, %b),
14627 // (extract_subvector
14628 // (v8i1 (bitcast %mask)), 0))), 0))))
14629 EVT VT = Op.getOperand(1).getValueType();
14630 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14631 VT.getVectorNumElements());
14632 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14633 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14634 Mask.getValueType().getSizeInBits());
14636 if (IntrData->Type == CMP_MASK_CC) {
14637 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14638 Op.getOperand(2), Op.getOperand(3));
14640 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14641 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14644 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14645 DAG.getTargetConstant(0, MaskVT),
14647 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14648 DAG.getUNDEF(BitcastVT), CmpMask,
14649 DAG.getIntPtrConstant(0));
14650 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14652 case COMI: { // Comparison intrinsics
14653 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14654 SDValue LHS = Op.getOperand(1);
14655 SDValue RHS = Op.getOperand(2);
14656 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14657 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14658 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14659 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14660 DAG.getConstant(X86CC, MVT::i8), Cond);
14661 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14664 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14665 Op.getOperand(1), Op.getOperand(2), DAG);
14667 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14668 Op.getSimpleValueType(),
14670 Op.getOperand(2), DAG),
14671 Op.getOperand(4), Op.getOperand(3), Subtarget,
14673 case COMPRESS_EXPAND_IN_REG: {
14674 SDValue Mask = Op.getOperand(3);
14675 SDValue DataToCompress = Op.getOperand(1);
14676 SDValue PassThru = Op.getOperand(2);
14677 if (isAllOnes(Mask)) // return data as is
14678 return Op.getOperand(1);
14679 EVT VT = Op.getValueType();
14680 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14681 VT.getVectorNumElements());
14682 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14683 Mask.getValueType().getSizeInBits());
14685 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14686 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14687 DAG.getIntPtrConstant(0));
14689 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14693 SDValue Mask = Op.getOperand(3);
14694 EVT VT = Op.getValueType();
14695 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14696 VT.getVectorNumElements());
14697 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14698 Mask.getValueType().getSizeInBits());
14700 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14701 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14702 DAG.getIntPtrConstant(0));
14703 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14712 default: return SDValue(); // Don't custom lower most intrinsics.
14714 case Intrinsic::x86_avx2_permd:
14715 case Intrinsic::x86_avx2_permps:
14716 // Operands intentionally swapped. Mask is last operand to intrinsic,
14717 // but second operand for node/instruction.
14718 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14719 Op.getOperand(2), Op.getOperand(1));
14721 case Intrinsic::x86_avx512_mask_valign_q_512:
14722 case Intrinsic::x86_avx512_mask_valign_d_512:
14723 // Vector source operands are swapped.
14724 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14725 Op.getValueType(), Op.getOperand(2),
14728 Op.getOperand(5), Op.getOperand(4),
14731 // ptest and testp intrinsics. The intrinsic these come from are designed to
14732 // return an integer value, not just an instruction so lower it to the ptest
14733 // or testp pattern and a setcc for the result.
14734 case Intrinsic::x86_sse41_ptestz:
14735 case Intrinsic::x86_sse41_ptestc:
14736 case Intrinsic::x86_sse41_ptestnzc:
14737 case Intrinsic::x86_avx_ptestz_256:
14738 case Intrinsic::x86_avx_ptestc_256:
14739 case Intrinsic::x86_avx_ptestnzc_256:
14740 case Intrinsic::x86_avx_vtestz_ps:
14741 case Intrinsic::x86_avx_vtestc_ps:
14742 case Intrinsic::x86_avx_vtestnzc_ps:
14743 case Intrinsic::x86_avx_vtestz_pd:
14744 case Intrinsic::x86_avx_vtestc_pd:
14745 case Intrinsic::x86_avx_vtestnzc_pd:
14746 case Intrinsic::x86_avx_vtestz_ps_256:
14747 case Intrinsic::x86_avx_vtestc_ps_256:
14748 case Intrinsic::x86_avx_vtestnzc_ps_256:
14749 case Intrinsic::x86_avx_vtestz_pd_256:
14750 case Intrinsic::x86_avx_vtestc_pd_256:
14751 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14752 bool IsTestPacked = false;
14755 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14756 case Intrinsic::x86_avx_vtestz_ps:
14757 case Intrinsic::x86_avx_vtestz_pd:
14758 case Intrinsic::x86_avx_vtestz_ps_256:
14759 case Intrinsic::x86_avx_vtestz_pd_256:
14760 IsTestPacked = true; // Fallthrough
14761 case Intrinsic::x86_sse41_ptestz:
14762 case Intrinsic::x86_avx_ptestz_256:
14764 X86CC = X86::COND_E;
14766 case Intrinsic::x86_avx_vtestc_ps:
14767 case Intrinsic::x86_avx_vtestc_pd:
14768 case Intrinsic::x86_avx_vtestc_ps_256:
14769 case Intrinsic::x86_avx_vtestc_pd_256:
14770 IsTestPacked = true; // Fallthrough
14771 case Intrinsic::x86_sse41_ptestc:
14772 case Intrinsic::x86_avx_ptestc_256:
14774 X86CC = X86::COND_B;
14776 case Intrinsic::x86_avx_vtestnzc_ps:
14777 case Intrinsic::x86_avx_vtestnzc_pd:
14778 case Intrinsic::x86_avx_vtestnzc_ps_256:
14779 case Intrinsic::x86_avx_vtestnzc_pd_256:
14780 IsTestPacked = true; // Fallthrough
14781 case Intrinsic::x86_sse41_ptestnzc:
14782 case Intrinsic::x86_avx_ptestnzc_256:
14784 X86CC = X86::COND_A;
14788 SDValue LHS = Op.getOperand(1);
14789 SDValue RHS = Op.getOperand(2);
14790 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14791 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14792 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14793 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14794 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14796 case Intrinsic::x86_avx512_kortestz_w:
14797 case Intrinsic::x86_avx512_kortestc_w: {
14798 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14799 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14800 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14801 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14802 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14803 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14804 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14807 case Intrinsic::x86_sse42_pcmpistria128:
14808 case Intrinsic::x86_sse42_pcmpestria128:
14809 case Intrinsic::x86_sse42_pcmpistric128:
14810 case Intrinsic::x86_sse42_pcmpestric128:
14811 case Intrinsic::x86_sse42_pcmpistrio128:
14812 case Intrinsic::x86_sse42_pcmpestrio128:
14813 case Intrinsic::x86_sse42_pcmpistris128:
14814 case Intrinsic::x86_sse42_pcmpestris128:
14815 case Intrinsic::x86_sse42_pcmpistriz128:
14816 case Intrinsic::x86_sse42_pcmpestriz128: {
14820 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14821 case Intrinsic::x86_sse42_pcmpistria128:
14822 Opcode = X86ISD::PCMPISTRI;
14823 X86CC = X86::COND_A;
14825 case Intrinsic::x86_sse42_pcmpestria128:
14826 Opcode = X86ISD::PCMPESTRI;
14827 X86CC = X86::COND_A;
14829 case Intrinsic::x86_sse42_pcmpistric128:
14830 Opcode = X86ISD::PCMPISTRI;
14831 X86CC = X86::COND_B;
14833 case Intrinsic::x86_sse42_pcmpestric128:
14834 Opcode = X86ISD::PCMPESTRI;
14835 X86CC = X86::COND_B;
14837 case Intrinsic::x86_sse42_pcmpistrio128:
14838 Opcode = X86ISD::PCMPISTRI;
14839 X86CC = X86::COND_O;
14841 case Intrinsic::x86_sse42_pcmpestrio128:
14842 Opcode = X86ISD::PCMPESTRI;
14843 X86CC = X86::COND_O;
14845 case Intrinsic::x86_sse42_pcmpistris128:
14846 Opcode = X86ISD::PCMPISTRI;
14847 X86CC = X86::COND_S;
14849 case Intrinsic::x86_sse42_pcmpestris128:
14850 Opcode = X86ISD::PCMPESTRI;
14851 X86CC = X86::COND_S;
14853 case Intrinsic::x86_sse42_pcmpistriz128:
14854 Opcode = X86ISD::PCMPISTRI;
14855 X86CC = X86::COND_E;
14857 case Intrinsic::x86_sse42_pcmpestriz128:
14858 Opcode = X86ISD::PCMPESTRI;
14859 X86CC = X86::COND_E;
14862 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14863 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14864 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14865 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14866 DAG.getConstant(X86CC, MVT::i8),
14867 SDValue(PCMP.getNode(), 1));
14868 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14871 case Intrinsic::x86_sse42_pcmpistri128:
14872 case Intrinsic::x86_sse42_pcmpestri128: {
14874 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14875 Opcode = X86ISD::PCMPISTRI;
14877 Opcode = X86ISD::PCMPESTRI;
14879 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14880 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14881 return DAG.getNode(Opcode, dl, VTs, NewOps);
14886 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14887 SDValue Src, SDValue Mask, SDValue Base,
14888 SDValue Index, SDValue ScaleOp, SDValue Chain,
14889 const X86Subtarget * Subtarget) {
14891 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14892 assert(C && "Invalid scale type");
14893 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14894 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14895 Index.getSimpleValueType().getVectorNumElements());
14897 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14899 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14901 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14902 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14903 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14904 SDValue Segment = DAG.getRegister(0, MVT::i32);
14905 if (Src.getOpcode() == ISD::UNDEF)
14906 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14907 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14908 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14909 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14910 return DAG.getMergeValues(RetOps, dl);
14913 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14914 SDValue Src, SDValue Mask, SDValue Base,
14915 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14917 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14918 assert(C && "Invalid scale type");
14919 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14920 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14921 SDValue Segment = DAG.getRegister(0, MVT::i32);
14922 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14923 Index.getSimpleValueType().getVectorNumElements());
14925 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14927 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14929 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14930 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14931 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14932 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14933 return SDValue(Res, 1);
14936 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14937 SDValue Mask, SDValue Base, SDValue Index,
14938 SDValue ScaleOp, SDValue Chain) {
14940 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14941 assert(C && "Invalid scale type");
14942 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14943 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14944 SDValue Segment = DAG.getRegister(0, MVT::i32);
14946 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14948 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14950 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14952 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14953 //SDVTList VTs = DAG.getVTList(MVT::Other);
14954 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14955 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14956 return SDValue(Res, 0);
14959 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14960 // read performance monitor counters (x86_rdpmc).
14961 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14962 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14963 SmallVectorImpl<SDValue> &Results) {
14964 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14965 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14968 // The ECX register is used to select the index of the performance counter
14970 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14972 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14974 // Reads the content of a 64-bit performance counter and returns it in the
14975 // registers EDX:EAX.
14976 if (Subtarget->is64Bit()) {
14977 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14978 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14981 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14982 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14985 Chain = HI.getValue(1);
14987 if (Subtarget->is64Bit()) {
14988 // The EAX register is loaded with the low-order 32 bits. The EDX register
14989 // is loaded with the supported high-order bits of the counter.
14990 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14991 DAG.getConstant(32, MVT::i8));
14992 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14993 Results.push_back(Chain);
14997 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14998 SDValue Ops[] = { LO, HI };
14999 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15000 Results.push_back(Pair);
15001 Results.push_back(Chain);
15004 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15005 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15006 // also used to custom lower READCYCLECOUNTER nodes.
15007 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15008 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15009 SmallVectorImpl<SDValue> &Results) {
15010 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15011 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15014 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15015 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15016 // and the EAX register is loaded with the low-order 32 bits.
15017 if (Subtarget->is64Bit()) {
15018 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15019 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15022 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15023 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15026 SDValue Chain = HI.getValue(1);
15028 if (Opcode == X86ISD::RDTSCP_DAG) {
15029 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15031 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15032 // the ECX register. Add 'ecx' explicitly to the chain.
15033 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15035 // Explicitly store the content of ECX at the location passed in input
15036 // to the 'rdtscp' intrinsic.
15037 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15038 MachinePointerInfo(), false, false, 0);
15041 if (Subtarget->is64Bit()) {
15042 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15043 // the EAX register is loaded with the low-order 32 bits.
15044 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15045 DAG.getConstant(32, MVT::i8));
15046 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15047 Results.push_back(Chain);
15051 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15052 SDValue Ops[] = { LO, HI };
15053 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15054 Results.push_back(Pair);
15055 Results.push_back(Chain);
15058 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15059 SelectionDAG &DAG) {
15060 SmallVector<SDValue, 2> Results;
15062 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15064 return DAG.getMergeValues(Results, DL);
15068 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15069 SelectionDAG &DAG) {
15070 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15072 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15077 switch(IntrData->Type) {
15079 llvm_unreachable("Unknown Intrinsic Type");
15083 // Emit the node with the right value type.
15084 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15085 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15087 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15088 // Otherwise return the value from Rand, which is always 0, casted to i32.
15089 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15090 DAG.getConstant(1, Op->getValueType(1)),
15091 DAG.getConstant(X86::COND_B, MVT::i32),
15092 SDValue(Result.getNode(), 1) };
15093 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15094 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15097 // Return { result, isValid, chain }.
15098 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15099 SDValue(Result.getNode(), 2));
15102 //gather(v1, mask, index, base, scale);
15103 SDValue Chain = Op.getOperand(0);
15104 SDValue Src = Op.getOperand(2);
15105 SDValue Base = Op.getOperand(3);
15106 SDValue Index = Op.getOperand(4);
15107 SDValue Mask = Op.getOperand(5);
15108 SDValue Scale = Op.getOperand(6);
15109 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15113 //scatter(base, mask, index, v1, scale);
15114 SDValue Chain = Op.getOperand(0);
15115 SDValue Base = Op.getOperand(2);
15116 SDValue Mask = Op.getOperand(3);
15117 SDValue Index = Op.getOperand(4);
15118 SDValue Src = Op.getOperand(5);
15119 SDValue Scale = Op.getOperand(6);
15120 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15123 SDValue Hint = Op.getOperand(6);
15125 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15126 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15127 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15128 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15129 SDValue Chain = Op.getOperand(0);
15130 SDValue Mask = Op.getOperand(2);
15131 SDValue Index = Op.getOperand(3);
15132 SDValue Base = Op.getOperand(4);
15133 SDValue Scale = Op.getOperand(5);
15134 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15136 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15138 SmallVector<SDValue, 2> Results;
15139 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15140 return DAG.getMergeValues(Results, dl);
15142 // Read Performance Monitoring Counters.
15144 SmallVector<SDValue, 2> Results;
15145 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15146 return DAG.getMergeValues(Results, dl);
15148 // XTEST intrinsics.
15150 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15151 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15152 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15153 DAG.getConstant(X86::COND_NE, MVT::i8),
15155 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15156 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15157 Ret, SDValue(InTrans.getNode(), 1));
15161 SmallVector<SDValue, 2> Results;
15162 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15163 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15164 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15165 DAG.getConstant(-1, MVT::i8));
15166 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15167 Op.getOperand(4), GenCF.getValue(1));
15168 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15169 Op.getOperand(5), MachinePointerInfo(),
15171 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15172 DAG.getConstant(X86::COND_B, MVT::i8),
15174 Results.push_back(SetCC);
15175 Results.push_back(Store);
15176 return DAG.getMergeValues(Results, dl);
15178 case COMPRESS_TO_MEM: {
15180 SDValue Mask = Op.getOperand(4);
15181 SDValue DataToCompress = Op.getOperand(3);
15182 SDValue Addr = Op.getOperand(2);
15183 SDValue Chain = Op.getOperand(0);
15185 if (isAllOnes(Mask)) // return just a store
15186 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15187 MachinePointerInfo(), false, false, 0);
15189 EVT VT = DataToCompress.getValueType();
15190 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15191 VT.getVectorNumElements());
15192 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15193 Mask.getValueType().getSizeInBits());
15194 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15195 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15196 DAG.getIntPtrConstant(0));
15198 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15199 DataToCompress, DAG.getUNDEF(VT));
15200 return DAG.getStore(Chain, dl, Compressed, Addr,
15201 MachinePointerInfo(), false, false, 0);
15203 case EXPAND_FROM_MEM: {
15205 SDValue Mask = Op.getOperand(4);
15206 SDValue PathThru = Op.getOperand(3);
15207 SDValue Addr = Op.getOperand(2);
15208 SDValue Chain = Op.getOperand(0);
15209 EVT VT = Op.getValueType();
15211 if (isAllOnes(Mask)) // return just a load
15212 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15214 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15215 VT.getVectorNumElements());
15216 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15217 Mask.getValueType().getSizeInBits());
15218 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15219 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15220 DAG.getIntPtrConstant(0));
15222 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15223 false, false, false, 0);
15225 SDValue Results[] = {
15226 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15228 return DAG.getMergeValues(Results, dl);
15233 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15234 SelectionDAG &DAG) const {
15235 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15236 MFI->setReturnAddressIsTaken(true);
15238 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15241 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15243 EVT PtrVT = getPointerTy();
15246 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15247 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15248 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15249 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15250 DAG.getNode(ISD::ADD, dl, PtrVT,
15251 FrameAddr, Offset),
15252 MachinePointerInfo(), false, false, false, 0);
15255 // Just load the return address.
15256 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15257 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15258 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15261 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15262 MachineFunction &MF = DAG.getMachineFunction();
15263 MachineFrameInfo *MFI = MF.getFrameInfo();
15264 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15265 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15266 EVT VT = Op.getValueType();
15268 MFI->setFrameAddressIsTaken(true);
15270 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15271 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15272 // is not possible to crawl up the stack without looking at the unwind codes
15274 int FrameAddrIndex = FuncInfo->getFAIndex();
15275 if (!FrameAddrIndex) {
15276 // Set up a frame object for the return address.
15277 unsigned SlotSize = RegInfo->getSlotSize();
15278 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15279 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15280 FuncInfo->setFAIndex(FrameAddrIndex);
15282 return DAG.getFrameIndex(FrameAddrIndex, VT);
15285 unsigned FrameReg =
15286 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15287 SDLoc dl(Op); // FIXME probably not meaningful
15288 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15289 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15290 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15291 "Invalid Frame Register!");
15292 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15294 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15295 MachinePointerInfo(),
15296 false, false, false, 0);
15300 // FIXME? Maybe this could be a TableGen attribute on some registers and
15301 // this table could be generated automatically from RegInfo.
15302 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15304 unsigned Reg = StringSwitch<unsigned>(RegName)
15305 .Case("esp", X86::ESP)
15306 .Case("rsp", X86::RSP)
15310 report_fatal_error("Invalid register name global variable");
15313 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15314 SelectionDAG &DAG) const {
15315 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15316 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15319 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15320 SDValue Chain = Op.getOperand(0);
15321 SDValue Offset = Op.getOperand(1);
15322 SDValue Handler = Op.getOperand(2);
15325 EVT PtrVT = getPointerTy();
15326 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15327 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15328 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15329 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15330 "Invalid Frame Register!");
15331 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15332 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15334 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15335 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15336 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15337 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15339 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15341 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15342 DAG.getRegister(StoreAddrReg, PtrVT));
15345 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15346 SelectionDAG &DAG) const {
15348 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15349 DAG.getVTList(MVT::i32, MVT::Other),
15350 Op.getOperand(0), Op.getOperand(1));
15353 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15354 SelectionDAG &DAG) const {
15356 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15357 Op.getOperand(0), Op.getOperand(1));
15360 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15361 return Op.getOperand(0);
15364 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15365 SelectionDAG &DAG) const {
15366 SDValue Root = Op.getOperand(0);
15367 SDValue Trmp = Op.getOperand(1); // trampoline
15368 SDValue FPtr = Op.getOperand(2); // nested function
15369 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15372 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15373 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15375 if (Subtarget->is64Bit()) {
15376 SDValue OutChains[6];
15378 // Large code-model.
15379 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15380 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15382 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15383 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15385 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15387 // Load the pointer to the nested function into R11.
15388 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15389 SDValue Addr = Trmp;
15390 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15391 Addr, MachinePointerInfo(TrmpAddr),
15394 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15395 DAG.getConstant(2, MVT::i64));
15396 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15397 MachinePointerInfo(TrmpAddr, 2),
15400 // Load the 'nest' parameter value into R10.
15401 // R10 is specified in X86CallingConv.td
15402 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15403 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15404 DAG.getConstant(10, MVT::i64));
15405 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15406 Addr, MachinePointerInfo(TrmpAddr, 10),
15409 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15410 DAG.getConstant(12, MVT::i64));
15411 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15412 MachinePointerInfo(TrmpAddr, 12),
15415 // Jump to the nested function.
15416 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15417 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15418 DAG.getConstant(20, MVT::i64));
15419 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15420 Addr, MachinePointerInfo(TrmpAddr, 20),
15423 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15424 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15425 DAG.getConstant(22, MVT::i64));
15426 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15427 MachinePointerInfo(TrmpAddr, 22),
15430 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15432 const Function *Func =
15433 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15434 CallingConv::ID CC = Func->getCallingConv();
15439 llvm_unreachable("Unsupported calling convention");
15440 case CallingConv::C:
15441 case CallingConv::X86_StdCall: {
15442 // Pass 'nest' parameter in ECX.
15443 // Must be kept in sync with X86CallingConv.td
15444 NestReg = X86::ECX;
15446 // Check that ECX wasn't needed by an 'inreg' parameter.
15447 FunctionType *FTy = Func->getFunctionType();
15448 const AttributeSet &Attrs = Func->getAttributes();
15450 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15451 unsigned InRegCount = 0;
15454 for (FunctionType::param_iterator I = FTy->param_begin(),
15455 E = FTy->param_end(); I != E; ++I, ++Idx)
15456 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15457 // FIXME: should only count parameters that are lowered to integers.
15458 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15460 if (InRegCount > 2) {
15461 report_fatal_error("Nest register in use - reduce number of inreg"
15467 case CallingConv::X86_FastCall:
15468 case CallingConv::X86_ThisCall:
15469 case CallingConv::Fast:
15470 // Pass 'nest' parameter in EAX.
15471 // Must be kept in sync with X86CallingConv.td
15472 NestReg = X86::EAX;
15476 SDValue OutChains[4];
15477 SDValue Addr, Disp;
15479 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15480 DAG.getConstant(10, MVT::i32));
15481 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15483 // This is storing the opcode for MOV32ri.
15484 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15485 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15486 OutChains[0] = DAG.getStore(Root, dl,
15487 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15488 Trmp, MachinePointerInfo(TrmpAddr),
15491 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15492 DAG.getConstant(1, MVT::i32));
15493 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15494 MachinePointerInfo(TrmpAddr, 1),
15497 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15498 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15499 DAG.getConstant(5, MVT::i32));
15500 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15501 MachinePointerInfo(TrmpAddr, 5),
15504 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15505 DAG.getConstant(6, MVT::i32));
15506 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15507 MachinePointerInfo(TrmpAddr, 6),
15510 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15514 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15515 SelectionDAG &DAG) const {
15517 The rounding mode is in bits 11:10 of FPSR, and has the following
15519 00 Round to nearest
15524 FLT_ROUNDS, on the other hand, expects the following:
15531 To perform the conversion, we do:
15532 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15535 MachineFunction &MF = DAG.getMachineFunction();
15536 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15537 unsigned StackAlignment = TFI.getStackAlignment();
15538 MVT VT = Op.getSimpleValueType();
15541 // Save FP Control Word to stack slot
15542 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15543 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15545 MachineMemOperand *MMO =
15546 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15547 MachineMemOperand::MOStore, 2, 2);
15549 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15550 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15551 DAG.getVTList(MVT::Other),
15552 Ops, MVT::i16, MMO);
15554 // Load FP Control Word from stack slot
15555 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15556 MachinePointerInfo(), false, false, false, 0);
15558 // Transform as necessary
15560 DAG.getNode(ISD::SRL, DL, MVT::i16,
15561 DAG.getNode(ISD::AND, DL, MVT::i16,
15562 CWD, DAG.getConstant(0x800, MVT::i16)),
15563 DAG.getConstant(11, MVT::i8));
15565 DAG.getNode(ISD::SRL, DL, MVT::i16,
15566 DAG.getNode(ISD::AND, DL, MVT::i16,
15567 CWD, DAG.getConstant(0x400, MVT::i16)),
15568 DAG.getConstant(9, MVT::i8));
15571 DAG.getNode(ISD::AND, DL, MVT::i16,
15572 DAG.getNode(ISD::ADD, DL, MVT::i16,
15573 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15574 DAG.getConstant(1, MVT::i16)),
15575 DAG.getConstant(3, MVT::i16));
15577 return DAG.getNode((VT.getSizeInBits() < 16 ?
15578 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15581 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15582 MVT VT = Op.getSimpleValueType();
15584 unsigned NumBits = VT.getSizeInBits();
15587 Op = Op.getOperand(0);
15588 if (VT == MVT::i8) {
15589 // Zero extend to i32 since there is not an i8 bsr.
15591 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15594 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15595 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15596 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15598 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15601 DAG.getConstant(NumBits+NumBits-1, OpVT),
15602 DAG.getConstant(X86::COND_E, MVT::i8),
15605 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15607 // Finally xor with NumBits-1.
15608 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15611 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15615 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15616 MVT VT = Op.getSimpleValueType();
15618 unsigned NumBits = VT.getSizeInBits();
15621 Op = Op.getOperand(0);
15622 if (VT == MVT::i8) {
15623 // Zero extend to i32 since there is not an i8 bsr.
15625 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15628 // Issue a bsr (scan bits in reverse).
15629 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15630 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15632 // And xor with NumBits-1.
15633 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15636 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15640 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15641 MVT VT = Op.getSimpleValueType();
15642 unsigned NumBits = VT.getSizeInBits();
15644 Op = Op.getOperand(0);
15646 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15647 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15648 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15650 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15653 DAG.getConstant(NumBits, VT),
15654 DAG.getConstant(X86::COND_E, MVT::i8),
15657 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15660 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15661 // ones, and then concatenate the result back.
15662 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15663 MVT VT = Op.getSimpleValueType();
15665 assert(VT.is256BitVector() && VT.isInteger() &&
15666 "Unsupported value type for operation");
15668 unsigned NumElems = VT.getVectorNumElements();
15671 // Extract the LHS vectors
15672 SDValue LHS = Op.getOperand(0);
15673 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15674 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15676 // Extract the RHS vectors
15677 SDValue RHS = Op.getOperand(1);
15678 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15679 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15681 MVT EltVT = VT.getVectorElementType();
15682 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15684 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15685 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15686 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15689 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15690 assert(Op.getSimpleValueType().is256BitVector() &&
15691 Op.getSimpleValueType().isInteger() &&
15692 "Only handle AVX 256-bit vector integer operation");
15693 return Lower256IntArith(Op, DAG);
15696 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15697 assert(Op.getSimpleValueType().is256BitVector() &&
15698 Op.getSimpleValueType().isInteger() &&
15699 "Only handle AVX 256-bit vector integer operation");
15700 return Lower256IntArith(Op, DAG);
15703 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15704 SelectionDAG &DAG) {
15706 MVT VT = Op.getSimpleValueType();
15708 // Decompose 256-bit ops into smaller 128-bit ops.
15709 if (VT.is256BitVector() && !Subtarget->hasInt256())
15710 return Lower256IntArith(Op, DAG);
15712 SDValue A = Op.getOperand(0);
15713 SDValue B = Op.getOperand(1);
15715 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15716 if (VT == MVT::v4i32) {
15717 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15718 "Should not custom lower when pmuldq is available!");
15720 // Extract the odd parts.
15721 static const int UnpackMask[] = { 1, -1, 3, -1 };
15722 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15723 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15725 // Multiply the even parts.
15726 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15727 // Now multiply odd parts.
15728 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15730 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15731 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15733 // Merge the two vectors back together with a shuffle. This expands into 2
15735 static const int ShufMask[] = { 0, 4, 2, 6 };
15736 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15739 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15740 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15742 // Ahi = psrlqi(a, 32);
15743 // Bhi = psrlqi(b, 32);
15745 // AloBlo = pmuludq(a, b);
15746 // AloBhi = pmuludq(a, Bhi);
15747 // AhiBlo = pmuludq(Ahi, b);
15749 // AloBhi = psllqi(AloBhi, 32);
15750 // AhiBlo = psllqi(AhiBlo, 32);
15751 // return AloBlo + AloBhi + AhiBlo;
15753 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15754 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15756 // Bit cast to 32-bit vectors for MULUDQ
15757 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15758 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15759 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15760 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15761 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15762 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15764 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15765 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15766 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15768 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15769 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15771 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15772 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15775 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15776 assert(Subtarget->isTargetWin64() && "Unexpected target");
15777 EVT VT = Op.getValueType();
15778 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15779 "Unexpected return type for lowering");
15783 switch (Op->getOpcode()) {
15784 default: llvm_unreachable("Unexpected request for libcall!");
15785 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15786 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15787 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15788 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15789 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15790 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15794 SDValue InChain = DAG.getEntryNode();
15796 TargetLowering::ArgListTy Args;
15797 TargetLowering::ArgListEntry Entry;
15798 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15799 EVT ArgVT = Op->getOperand(i).getValueType();
15800 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15801 "Unexpected argument type for lowering");
15802 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15803 Entry.Node = StackPtr;
15804 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15806 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15807 Entry.Ty = PointerType::get(ArgTy,0);
15808 Entry.isSExt = false;
15809 Entry.isZExt = false;
15810 Args.push_back(Entry);
15813 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15816 TargetLowering::CallLoweringInfo CLI(DAG);
15817 CLI.setDebugLoc(dl).setChain(InChain)
15818 .setCallee(getLibcallCallingConv(LC),
15819 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15820 Callee, std::move(Args), 0)
15821 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15823 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15824 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15827 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15828 SelectionDAG &DAG) {
15829 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15830 EVT VT = Op0.getValueType();
15833 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15834 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15836 // PMULxD operations multiply each even value (starting at 0) of LHS with
15837 // the related value of RHS and produce a widen result.
15838 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15839 // => <2 x i64> <ae|cg>
15841 // In other word, to have all the results, we need to perform two PMULxD:
15842 // 1. one with the even values.
15843 // 2. one with the odd values.
15844 // To achieve #2, with need to place the odd values at an even position.
15846 // Place the odd value at an even position (basically, shift all values 1
15847 // step to the left):
15848 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15849 // <a|b|c|d> => <b|undef|d|undef>
15850 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15851 // <e|f|g|h> => <f|undef|h|undef>
15852 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15854 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15856 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15857 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15859 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15860 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15861 // => <2 x i64> <ae|cg>
15862 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15863 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15864 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15865 // => <2 x i64> <bf|dh>
15866 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15867 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15869 // Shuffle it back into the right order.
15870 SDValue Highs, Lows;
15871 if (VT == MVT::v8i32) {
15872 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15873 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15874 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15875 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15877 const int HighMask[] = {1, 5, 3, 7};
15878 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15879 const int LowMask[] = {0, 4, 2, 6};
15880 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15883 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15884 // unsigned multiply.
15885 if (IsSigned && !Subtarget->hasSSE41()) {
15887 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15888 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15889 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15890 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15891 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15893 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15894 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15897 // The first result of MUL_LOHI is actually the low value, followed by the
15899 SDValue Ops[] = {Lows, Highs};
15900 return DAG.getMergeValues(Ops, dl);
15903 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15904 const X86Subtarget *Subtarget) {
15905 MVT VT = Op.getSimpleValueType();
15907 SDValue R = Op.getOperand(0);
15908 SDValue Amt = Op.getOperand(1);
15910 // Optimize shl/srl/sra with constant shift amount.
15911 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15912 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15913 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15915 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15916 (Subtarget->hasInt256() &&
15917 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15918 (Subtarget->hasAVX512() &&
15919 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15920 if (Op.getOpcode() == ISD::SHL)
15921 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15923 if (Op.getOpcode() == ISD::SRL)
15924 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15926 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15927 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15931 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15932 unsigned NumElts = VT.getVectorNumElements();
15933 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15935 if (Op.getOpcode() == ISD::SHL) {
15936 // Make a large shift.
15937 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15939 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15940 // Zero out the rightmost bits.
15941 SmallVector<SDValue, 32> V(
15942 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15943 return DAG.getNode(ISD::AND, dl, VT, SHL,
15944 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15946 if (Op.getOpcode() == ISD::SRL) {
15947 // Make a large shift.
15948 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15950 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15951 // Zero out the leftmost bits.
15952 SmallVector<SDValue, 32> V(
15953 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15954 return DAG.getNode(ISD::AND, dl, VT, SRL,
15955 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15957 if (Op.getOpcode() == ISD::SRA) {
15958 if (ShiftAmt == 7) {
15959 // R s>> 7 === R s< 0
15960 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15961 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15964 // R s>> a === ((R u>> a) ^ m) - m
15965 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15966 SmallVector<SDValue, 32> V(NumElts,
15967 DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15968 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15969 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15970 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15973 llvm_unreachable("Unknown shift opcode.");
15978 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15979 if (!Subtarget->is64Bit() &&
15980 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15981 Amt.getOpcode() == ISD::BITCAST &&
15982 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15983 Amt = Amt.getOperand(0);
15984 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15985 VT.getVectorNumElements();
15986 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15987 uint64_t ShiftAmt = 0;
15988 for (unsigned i = 0; i != Ratio; ++i) {
15989 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15993 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15995 // Check remaining shift amounts.
15996 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15997 uint64_t ShAmt = 0;
15998 for (unsigned j = 0; j != Ratio; ++j) {
15999 ConstantSDNode *C =
16000 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16004 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16006 if (ShAmt != ShiftAmt)
16009 switch (Op.getOpcode()) {
16011 llvm_unreachable("Unknown shift opcode!");
16013 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16016 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16019 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16027 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16028 const X86Subtarget* Subtarget) {
16029 MVT VT = Op.getSimpleValueType();
16031 SDValue R = Op.getOperand(0);
16032 SDValue Amt = Op.getOperand(1);
16034 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16035 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16036 (Subtarget->hasInt256() &&
16037 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16038 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16039 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16041 EVT EltVT = VT.getVectorElementType();
16043 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16044 // Check if this build_vector node is doing a splat.
16045 // If so, then set BaseShAmt equal to the splat value.
16046 BaseShAmt = BV->getSplatValue();
16047 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16048 BaseShAmt = SDValue();
16050 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16051 Amt = Amt.getOperand(0);
16053 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16054 if (SVN && SVN->isSplat()) {
16055 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16056 SDValue InVec = Amt.getOperand(0);
16057 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16058 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16059 "Unexpected shuffle index found!");
16060 BaseShAmt = InVec.getOperand(SplatIdx);
16061 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16062 if (ConstantSDNode *C =
16063 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16064 if (C->getZExtValue() == SplatIdx)
16065 BaseShAmt = InVec.getOperand(1);
16070 // Avoid introducing an extract element from a shuffle.
16071 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16072 DAG.getIntPtrConstant(SplatIdx));
16076 if (BaseShAmt.getNode()) {
16077 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16078 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16079 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16080 else if (EltVT.bitsLT(MVT::i32))
16081 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16083 switch (Op.getOpcode()) {
16085 llvm_unreachable("Unknown shift opcode!");
16087 switch (VT.SimpleTy) {
16088 default: return SDValue();
16097 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16100 switch (VT.SimpleTy) {
16101 default: return SDValue();
16108 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16111 switch (VT.SimpleTy) {
16112 default: return SDValue();
16121 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16127 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16128 if (!Subtarget->is64Bit() &&
16129 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16130 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16131 Amt.getOpcode() == ISD::BITCAST &&
16132 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16133 Amt = Amt.getOperand(0);
16134 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16135 VT.getVectorNumElements();
16136 std::vector<SDValue> Vals(Ratio);
16137 for (unsigned i = 0; i != Ratio; ++i)
16138 Vals[i] = Amt.getOperand(i);
16139 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16140 for (unsigned j = 0; j != Ratio; ++j)
16141 if (Vals[j] != Amt.getOperand(i + j))
16144 switch (Op.getOpcode()) {
16146 llvm_unreachable("Unknown shift opcode!");
16148 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16150 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16152 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16159 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16160 SelectionDAG &DAG) {
16161 MVT VT = Op.getSimpleValueType();
16163 SDValue R = Op.getOperand(0);
16164 SDValue Amt = Op.getOperand(1);
16166 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16167 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16169 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16172 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16175 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16178 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16179 if (Subtarget->hasInt256()) {
16180 if (Op.getOpcode() == ISD::SRL &&
16181 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16182 VT == MVT::v4i64 || VT == MVT::v8i32))
16184 if (Op.getOpcode() == ISD::SHL &&
16185 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16186 VT == MVT::v4i64 || VT == MVT::v8i32))
16188 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16192 // If possible, lower this packed shift into a vector multiply instead of
16193 // expanding it into a sequence of scalar shifts.
16194 // Do this only if the vector shift count is a constant build_vector.
16195 if (Op.getOpcode() == ISD::SHL &&
16196 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16197 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16198 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16199 SmallVector<SDValue, 8> Elts;
16200 EVT SVT = VT.getScalarType();
16201 unsigned SVTBits = SVT.getSizeInBits();
16202 const APInt &One = APInt(SVTBits, 1);
16203 unsigned NumElems = VT.getVectorNumElements();
16205 for (unsigned i=0; i !=NumElems; ++i) {
16206 SDValue Op = Amt->getOperand(i);
16207 if (Op->getOpcode() == ISD::UNDEF) {
16208 Elts.push_back(Op);
16212 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16213 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16214 uint64_t ShAmt = C.getZExtValue();
16215 if (ShAmt >= SVTBits) {
16216 Elts.push_back(DAG.getUNDEF(SVT));
16219 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16221 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16222 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16225 // Lower SHL with variable shift amount.
16226 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16227 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16229 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16230 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16231 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16232 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16235 // If possible, lower this shift as a sequence of two shifts by
16236 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16238 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16240 // Could be rewritten as:
16241 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16243 // The advantage is that the two shifts from the example would be
16244 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16245 // the vector shift into four scalar shifts plus four pairs of vector
16247 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16248 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16249 unsigned TargetOpcode = X86ISD::MOVSS;
16250 bool CanBeSimplified;
16251 // The splat value for the first packed shift (the 'X' from the example).
16252 SDValue Amt1 = Amt->getOperand(0);
16253 // The splat value for the second packed shift (the 'Y' from the example).
16254 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16255 Amt->getOperand(2);
16257 // See if it is possible to replace this node with a sequence of
16258 // two shifts followed by a MOVSS/MOVSD
16259 if (VT == MVT::v4i32) {
16260 // Check if it is legal to use a MOVSS.
16261 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16262 Amt2 == Amt->getOperand(3);
16263 if (!CanBeSimplified) {
16264 // Otherwise, check if we can still simplify this node using a MOVSD.
16265 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16266 Amt->getOperand(2) == Amt->getOperand(3);
16267 TargetOpcode = X86ISD::MOVSD;
16268 Amt2 = Amt->getOperand(2);
16271 // Do similar checks for the case where the machine value type
16273 CanBeSimplified = Amt1 == Amt->getOperand(1);
16274 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16275 CanBeSimplified = Amt2 == Amt->getOperand(i);
16277 if (!CanBeSimplified) {
16278 TargetOpcode = X86ISD::MOVSD;
16279 CanBeSimplified = true;
16280 Amt2 = Amt->getOperand(4);
16281 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16282 CanBeSimplified = Amt1 == Amt->getOperand(i);
16283 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16284 CanBeSimplified = Amt2 == Amt->getOperand(j);
16288 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16289 isa<ConstantSDNode>(Amt2)) {
16290 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16291 EVT CastVT = MVT::v4i32;
16293 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16294 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16296 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16297 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16298 if (TargetOpcode == X86ISD::MOVSD)
16299 CastVT = MVT::v2i64;
16300 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16301 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16302 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16304 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16308 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16309 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16312 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16313 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16315 // Turn 'a' into a mask suitable for VSELECT
16316 SDValue VSelM = DAG.getConstant(0x80, VT);
16317 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16318 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16320 SDValue CM1 = DAG.getConstant(0x0f, VT);
16321 SDValue CM2 = DAG.getConstant(0x3f, VT);
16323 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16324 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16325 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16326 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16327 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16330 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16331 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16332 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16334 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16335 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16336 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16337 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16338 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16341 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16342 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16343 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16345 // return VSELECT(r, r+r, a);
16346 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16347 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16351 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16352 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16353 // solution better.
16354 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16355 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16357 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16358 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16359 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16360 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16361 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16364 // Decompose 256-bit shifts into smaller 128-bit shifts.
16365 if (VT.is256BitVector()) {
16366 unsigned NumElems = VT.getVectorNumElements();
16367 MVT EltVT = VT.getVectorElementType();
16368 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16370 // Extract the two vectors
16371 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16372 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16374 // Recreate the shift amount vectors
16375 SDValue Amt1, Amt2;
16376 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16377 // Constant shift amount
16378 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16379 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16380 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16382 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16383 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16385 // Variable shift amount
16386 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16387 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16390 // Issue new vector shifts for the smaller types
16391 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16392 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16394 // Concatenate the result back
16395 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16401 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16402 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16403 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16404 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16405 // has only one use.
16406 SDNode *N = Op.getNode();
16407 SDValue LHS = N->getOperand(0);
16408 SDValue RHS = N->getOperand(1);
16409 unsigned BaseOp = 0;
16412 switch (Op.getOpcode()) {
16413 default: llvm_unreachable("Unknown ovf instruction!");
16415 // A subtract of one will be selected as a INC. Note that INC doesn't
16416 // set CF, so we can't do this for UADDO.
16417 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16419 BaseOp = X86ISD::INC;
16420 Cond = X86::COND_O;
16423 BaseOp = X86ISD::ADD;
16424 Cond = X86::COND_O;
16427 BaseOp = X86ISD::ADD;
16428 Cond = X86::COND_B;
16431 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16432 // set CF, so we can't do this for USUBO.
16433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16435 BaseOp = X86ISD::DEC;
16436 Cond = X86::COND_O;
16439 BaseOp = X86ISD::SUB;
16440 Cond = X86::COND_O;
16443 BaseOp = X86ISD::SUB;
16444 Cond = X86::COND_B;
16447 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16448 Cond = X86::COND_O;
16450 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16451 if (N->getValueType(0) == MVT::i8) {
16452 BaseOp = X86ISD::UMUL8;
16453 Cond = X86::COND_O;
16456 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16458 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16461 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16462 DAG.getConstant(X86::COND_O, MVT::i32),
16463 SDValue(Sum.getNode(), 2));
16465 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16469 // Also sets EFLAGS.
16470 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16471 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16474 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16475 DAG.getConstant(Cond, MVT::i32),
16476 SDValue(Sum.getNode(), 1));
16478 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16481 /// Returns true if the operand type is exactly twice the native width, and
16482 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16483 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16484 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16485 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16486 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16489 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16490 else if (OpWidth == 128)
16491 return Subtarget->hasCmpxchg16b();
16496 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16497 return needsCmpXchgNb(SI->getValueOperand()->getType());
16500 // Note: this turns large loads into lock cmpxchg8b/16b.
16501 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16502 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16503 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16504 return needsCmpXchgNb(PTy->getElementType());
16507 TargetLoweringBase::AtomicRMWExpansionKind
16508 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16509 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16510 const Type *MemType = AI->getType();
16512 // If the operand is too big, we must see if cmpxchg8/16b is available
16513 // and default to library calls otherwise.
16514 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16515 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16516 : AtomicRMWExpansionKind::None;
16519 AtomicRMWInst::BinOp Op = AI->getOperation();
16522 llvm_unreachable("Unknown atomic operation");
16523 case AtomicRMWInst::Xchg:
16524 case AtomicRMWInst::Add:
16525 case AtomicRMWInst::Sub:
16526 // It's better to use xadd, xsub or xchg for these in all cases.
16527 return AtomicRMWExpansionKind::None;
16528 case AtomicRMWInst::Or:
16529 case AtomicRMWInst::And:
16530 case AtomicRMWInst::Xor:
16531 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16532 // prefix to a normal instruction for these operations.
16533 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16534 : AtomicRMWExpansionKind::None;
16535 case AtomicRMWInst::Nand:
16536 case AtomicRMWInst::Max:
16537 case AtomicRMWInst::Min:
16538 case AtomicRMWInst::UMax:
16539 case AtomicRMWInst::UMin:
16540 // These always require a non-trivial set of data operations on x86. We must
16541 // use a cmpxchg loop.
16542 return AtomicRMWExpansionKind::CmpXChg;
16546 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16547 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16548 // no-sse2). There isn't any reason to disable it if the target processor
16550 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16554 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16555 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16556 const Type *MemType = AI->getType();
16557 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16558 // there is no benefit in turning such RMWs into loads, and it is actually
16559 // harmful as it introduces a mfence.
16560 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16563 auto Builder = IRBuilder<>(AI);
16564 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16565 auto SynchScope = AI->getSynchScope();
16566 // We must restrict the ordering to avoid generating loads with Release or
16567 // ReleaseAcquire orderings.
16568 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16569 auto Ptr = AI->getPointerOperand();
16571 // Before the load we need a fence. Here is an example lifted from
16572 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16575 // x.store(1, relaxed);
16576 // r1 = y.fetch_add(0, release);
16578 // y.fetch_add(42, acquire);
16579 // r2 = x.load(relaxed);
16580 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16581 // lowered to just a load without a fence. A mfence flushes the store buffer,
16582 // making the optimization clearly correct.
16583 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16584 // otherwise, we might be able to be more agressive on relaxed idempotent
16585 // rmw. In practice, they do not look useful, so we don't try to be
16586 // especially clever.
16587 if (SynchScope == SingleThread) {
16588 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16589 // the IR level, so we must wrap it in an intrinsic.
16591 } else if (hasMFENCE(*Subtarget)) {
16592 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16593 Intrinsic::x86_sse2_mfence);
16594 Builder.CreateCall(MFence);
16596 // FIXME: it might make sense to use a locked operation here but on a
16597 // different cache-line to prevent cache-line bouncing. In practice it
16598 // is probably a small win, and x86 processors without mfence are rare
16599 // enough that we do not bother.
16603 // Finally we can emit the atomic load.
16604 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16605 AI->getType()->getPrimitiveSizeInBits());
16606 Loaded->setAtomic(Order, SynchScope);
16607 AI->replaceAllUsesWith(Loaded);
16608 AI->eraseFromParent();
16612 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16613 SelectionDAG &DAG) {
16615 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16616 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16617 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16618 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16620 // The only fence that needs an instruction is a sequentially-consistent
16621 // cross-thread fence.
16622 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16623 if (hasMFENCE(*Subtarget))
16624 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16626 SDValue Chain = Op.getOperand(0);
16627 SDValue Zero = DAG.getConstant(0, MVT::i32);
16629 DAG.getRegister(X86::ESP, MVT::i32), // Base
16630 DAG.getTargetConstant(1, MVT::i8), // Scale
16631 DAG.getRegister(0, MVT::i32), // Index
16632 DAG.getTargetConstant(0, MVT::i32), // Disp
16633 DAG.getRegister(0, MVT::i32), // Segment.
16637 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16638 return SDValue(Res, 0);
16641 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16642 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16645 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16646 SelectionDAG &DAG) {
16647 MVT T = Op.getSimpleValueType();
16651 switch(T.SimpleTy) {
16652 default: llvm_unreachable("Invalid value type!");
16653 case MVT::i8: Reg = X86::AL; size = 1; break;
16654 case MVT::i16: Reg = X86::AX; size = 2; break;
16655 case MVT::i32: Reg = X86::EAX; size = 4; break;
16657 assert(Subtarget->is64Bit() && "Node not type legal!");
16658 Reg = X86::RAX; size = 8;
16661 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16662 Op.getOperand(2), SDValue());
16663 SDValue Ops[] = { cpIn.getValue(0),
16666 DAG.getTargetConstant(size, MVT::i8),
16667 cpIn.getValue(1) };
16668 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16669 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16670 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16674 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16675 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16676 MVT::i32, cpOut.getValue(2));
16677 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16678 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16680 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16681 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16682 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16686 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16687 SelectionDAG &DAG) {
16688 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16689 MVT DstVT = Op.getSimpleValueType();
16691 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16692 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16693 if (DstVT != MVT::f64)
16694 // This conversion needs to be expanded.
16697 SDValue InVec = Op->getOperand(0);
16699 unsigned NumElts = SrcVT.getVectorNumElements();
16700 EVT SVT = SrcVT.getVectorElementType();
16702 // Widen the vector in input in the case of MVT::v2i32.
16703 // Example: from MVT::v2i32 to MVT::v4i32.
16704 SmallVector<SDValue, 16> Elts;
16705 for (unsigned i = 0, e = NumElts; i != e; ++i)
16706 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16707 DAG.getIntPtrConstant(i)));
16709 // Explicitly mark the extra elements as Undef.
16710 Elts.append(NumElts, DAG.getUNDEF(SVT));
16712 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16713 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16714 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16715 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16716 DAG.getIntPtrConstant(0));
16719 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16720 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16721 assert((DstVT == MVT::i64 ||
16722 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16723 "Unexpected custom BITCAST");
16724 // i64 <=> MMX conversions are Legal.
16725 if (SrcVT==MVT::i64 && DstVT.isVector())
16727 if (DstVT==MVT::i64 && SrcVT.isVector())
16729 // MMX <=> MMX conversions are Legal.
16730 if (SrcVT.isVector() && DstVT.isVector())
16732 // All other conversions need to be expanded.
16736 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16737 SelectionDAG &DAG) {
16738 SDNode *Node = Op.getNode();
16741 Op = Op.getOperand(0);
16742 EVT VT = Op.getValueType();
16743 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16744 "CTPOP lowering only implemented for 128/256-bit wide vector types");
16746 unsigned NumElts = VT.getVectorNumElements();
16747 EVT EltVT = VT.getVectorElementType();
16748 unsigned Len = EltVT.getSizeInBits();
16750 // This is the vectorized version of the "best" algorithm from
16751 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16752 // with a minor tweak to use a series of adds + shifts instead of vector
16753 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16755 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16756 // v8i32 => Always profitable
16758 // FIXME: There a couple of possible improvements:
16760 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16761 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16763 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16764 "CTPOP not implemented for this vector element type.");
16766 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16767 // extra legalization.
16768 bool NeedsBitcast = EltVT == MVT::i32;
16769 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16771 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16772 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16773 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16775 // v = v - ((v >> 1) & 0x55555555...)
16776 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16777 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16778 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16780 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16782 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16783 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16785 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16787 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16788 if (VT != And.getValueType())
16789 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16790 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16792 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16793 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16794 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16795 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16796 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16798 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16799 if (NeedsBitcast) {
16800 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16801 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16802 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16805 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16806 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16807 if (VT != AndRHS.getValueType()) {
16808 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16809 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16811 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16813 // v = (v + (v >> 4)) & 0x0F0F0F0F...
16814 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16815 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16816 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16817 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16819 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16820 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16821 if (NeedsBitcast) {
16822 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16823 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16825 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16826 if (VT != And.getValueType())
16827 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16829 // The algorithm mentioned above uses:
16830 // v = (v * 0x01010101...) >> (Len - 8)
16832 // Change it to use vector adds + vector shifts which yield faster results on
16833 // Haswell than using vector integer multiplication.
16835 // For i32 elements:
16836 // v = v + (v >> 8)
16837 // v = v + (v >> 16)
16839 // For i64 elements:
16840 // v = v + (v >> 8)
16841 // v = v + (v >> 16)
16842 // v = v + (v >> 32)
16845 SmallVector<SDValue, 8> Csts;
16846 for (unsigned i = 8; i <= Len/2; i *= 2) {
16847 Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16848 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16849 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16850 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16854 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16855 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16856 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16857 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16858 if (NeedsBitcast) {
16859 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16860 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16862 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16863 if (VT != And.getValueType())
16864 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16869 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16870 SDNode *Node = Op.getNode();
16872 EVT T = Node->getValueType(0);
16873 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16874 DAG.getConstant(0, T), Node->getOperand(2));
16875 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16876 cast<AtomicSDNode>(Node)->getMemoryVT(),
16877 Node->getOperand(0),
16878 Node->getOperand(1), negOp,
16879 cast<AtomicSDNode>(Node)->getMemOperand(),
16880 cast<AtomicSDNode>(Node)->getOrdering(),
16881 cast<AtomicSDNode>(Node)->getSynchScope());
16884 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16885 SDNode *Node = Op.getNode();
16887 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16889 // Convert seq_cst store -> xchg
16890 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16891 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16892 // (The only way to get a 16-byte store is cmpxchg16b)
16893 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16894 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16895 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16896 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16897 cast<AtomicSDNode>(Node)->getMemoryVT(),
16898 Node->getOperand(0),
16899 Node->getOperand(1), Node->getOperand(2),
16900 cast<AtomicSDNode>(Node)->getMemOperand(),
16901 cast<AtomicSDNode>(Node)->getOrdering(),
16902 cast<AtomicSDNode>(Node)->getSynchScope());
16903 return Swap.getValue(1);
16905 // Other atomic stores have a simple pattern.
16909 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16910 EVT VT = Op.getNode()->getSimpleValueType(0);
16912 // Let legalize expand this if it isn't a legal type yet.
16913 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16916 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16919 bool ExtraOp = false;
16920 switch (Op.getOpcode()) {
16921 default: llvm_unreachable("Invalid code");
16922 case ISD::ADDC: Opc = X86ISD::ADD; break;
16923 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16924 case ISD::SUBC: Opc = X86ISD::SUB; break;
16925 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16929 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16931 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16932 Op.getOperand(1), Op.getOperand(2));
16935 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16936 SelectionDAG &DAG) {
16937 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16939 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16940 // which returns the values as { float, float } (in XMM0) or
16941 // { double, double } (which is returned in XMM0, XMM1).
16943 SDValue Arg = Op.getOperand(0);
16944 EVT ArgVT = Arg.getValueType();
16945 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16947 TargetLowering::ArgListTy Args;
16948 TargetLowering::ArgListEntry Entry;
16952 Entry.isSExt = false;
16953 Entry.isZExt = false;
16954 Args.push_back(Entry);
16956 bool isF64 = ArgVT == MVT::f64;
16957 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16958 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16959 // the results are returned via SRet in memory.
16960 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16961 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16962 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16964 Type *RetTy = isF64
16965 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16966 : (Type*)VectorType::get(ArgTy, 4);
16968 TargetLowering::CallLoweringInfo CLI(DAG);
16969 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16970 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16972 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16975 // Returned in xmm0 and xmm1.
16976 return CallResult.first;
16978 // Returned in bits 0:31 and 32:64 xmm0.
16979 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16980 CallResult.first, DAG.getIntPtrConstant(0));
16981 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16982 CallResult.first, DAG.getIntPtrConstant(1));
16983 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16984 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16987 /// LowerOperation - Provide custom lowering hooks for some operations.
16989 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16990 switch (Op.getOpcode()) {
16991 default: llvm_unreachable("Should not custom lower this!");
16992 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16993 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16994 return LowerCMP_SWAP(Op, Subtarget, DAG);
16995 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
16996 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16997 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16998 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16999 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17000 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17001 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17002 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17003 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17004 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17005 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17006 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17007 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17008 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17009 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17010 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17011 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17012 case ISD::SHL_PARTS:
17013 case ISD::SRA_PARTS:
17014 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17015 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17016 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17017 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17018 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17019 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17020 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17021 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17022 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17023 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17024 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17026 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17027 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17028 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17029 case ISD::SETCC: return LowerSETCC(Op, DAG);
17030 case ISD::SELECT: return LowerSELECT(Op, DAG);
17031 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17032 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17033 case ISD::VASTART: return LowerVASTART(Op, DAG);
17034 case ISD::VAARG: return LowerVAARG(Op, DAG);
17035 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17036 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17037 case ISD::INTRINSIC_VOID:
17038 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17039 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17040 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17041 case ISD::FRAME_TO_ARGS_OFFSET:
17042 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17043 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17044 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17045 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17046 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17047 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17048 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17049 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17050 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17051 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17052 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17053 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17054 case ISD::UMUL_LOHI:
17055 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17058 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17064 case ISD::UMULO: return LowerXALUO(Op, DAG);
17065 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17066 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17070 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17071 case ISD::ADD: return LowerADD(Op, DAG);
17072 case ISD::SUB: return LowerSUB(Op, DAG);
17073 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17077 /// ReplaceNodeResults - Replace a node with an illegal result type
17078 /// with a new node built out of custom code.
17079 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17080 SmallVectorImpl<SDValue>&Results,
17081 SelectionDAG &DAG) const {
17083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17084 switch (N->getOpcode()) {
17086 llvm_unreachable("Do not know how to custom type legalize this operation!");
17087 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17088 case X86ISD::FMINC:
17090 case X86ISD::FMAXC:
17091 case X86ISD::FMAX: {
17092 EVT VT = N->getValueType(0);
17093 if (VT != MVT::v2f32)
17094 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17095 SDValue UNDEF = DAG.getUNDEF(VT);
17096 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17097 N->getOperand(0), UNDEF);
17098 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17099 N->getOperand(1), UNDEF);
17100 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17103 case ISD::SIGN_EXTEND_INREG:
17108 // We don't want to expand or promote these.
17115 case ISD::UDIVREM: {
17116 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17117 Results.push_back(V);
17120 case ISD::FP_TO_SINT:
17121 case ISD::FP_TO_UINT: {
17122 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17124 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17127 std::pair<SDValue,SDValue> Vals =
17128 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17129 SDValue FIST = Vals.first, StackSlot = Vals.second;
17130 if (FIST.getNode()) {
17131 EVT VT = N->getValueType(0);
17132 // Return a load from the stack slot.
17133 if (StackSlot.getNode())
17134 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17135 MachinePointerInfo(),
17136 false, false, false, 0));
17138 Results.push_back(FIST);
17142 case ISD::UINT_TO_FP: {
17143 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17144 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17145 N->getValueType(0) != MVT::v2f32)
17147 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17149 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17151 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17152 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17153 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17154 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17155 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17156 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17159 case ISD::FP_ROUND: {
17160 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17162 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17163 Results.push_back(V);
17166 case ISD::INTRINSIC_W_CHAIN: {
17167 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17169 default : llvm_unreachable("Do not know how to custom type "
17170 "legalize this intrinsic operation!");
17171 case Intrinsic::x86_rdtsc:
17172 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17174 case Intrinsic::x86_rdtscp:
17175 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17177 case Intrinsic::x86_rdpmc:
17178 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17181 case ISD::READCYCLECOUNTER: {
17182 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17185 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17186 EVT T = N->getValueType(0);
17187 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17188 bool Regs64bit = T == MVT::i128;
17189 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17190 SDValue cpInL, cpInH;
17191 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17192 DAG.getConstant(0, HalfT));
17193 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17194 DAG.getConstant(1, HalfT));
17195 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17196 Regs64bit ? X86::RAX : X86::EAX,
17198 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17199 Regs64bit ? X86::RDX : X86::EDX,
17200 cpInH, cpInL.getValue(1));
17201 SDValue swapInL, swapInH;
17202 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17203 DAG.getConstant(0, HalfT));
17204 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17205 DAG.getConstant(1, HalfT));
17206 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17207 Regs64bit ? X86::RBX : X86::EBX,
17208 swapInL, cpInH.getValue(1));
17209 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17210 Regs64bit ? X86::RCX : X86::ECX,
17211 swapInH, swapInL.getValue(1));
17212 SDValue Ops[] = { swapInH.getValue(0),
17214 swapInH.getValue(1) };
17215 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17216 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17217 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17218 X86ISD::LCMPXCHG8_DAG;
17219 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17220 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17221 Regs64bit ? X86::RAX : X86::EAX,
17222 HalfT, Result.getValue(1));
17223 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17224 Regs64bit ? X86::RDX : X86::EDX,
17225 HalfT, cpOutL.getValue(2));
17226 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17228 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17229 MVT::i32, cpOutH.getValue(2));
17231 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17232 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17233 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17235 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17236 Results.push_back(Success);
17237 Results.push_back(EFLAGS.getValue(1));
17240 case ISD::ATOMIC_SWAP:
17241 case ISD::ATOMIC_LOAD_ADD:
17242 case ISD::ATOMIC_LOAD_SUB:
17243 case ISD::ATOMIC_LOAD_AND:
17244 case ISD::ATOMIC_LOAD_OR:
17245 case ISD::ATOMIC_LOAD_XOR:
17246 case ISD::ATOMIC_LOAD_NAND:
17247 case ISD::ATOMIC_LOAD_MIN:
17248 case ISD::ATOMIC_LOAD_MAX:
17249 case ISD::ATOMIC_LOAD_UMIN:
17250 case ISD::ATOMIC_LOAD_UMAX:
17251 case ISD::ATOMIC_LOAD: {
17252 // Delegate to generic TypeLegalization. Situations we can really handle
17253 // should have already been dealt with by AtomicExpandPass.cpp.
17256 case ISD::BITCAST: {
17257 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17258 EVT DstVT = N->getValueType(0);
17259 EVT SrcVT = N->getOperand(0)->getValueType(0);
17261 if (SrcVT != MVT::f64 ||
17262 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17265 unsigned NumElts = DstVT.getVectorNumElements();
17266 EVT SVT = DstVT.getVectorElementType();
17267 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17268 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17269 MVT::v2f64, N->getOperand(0));
17270 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17272 if (ExperimentalVectorWideningLegalization) {
17273 // If we are legalizing vectors by widening, we already have the desired
17274 // legal vector type, just return it.
17275 Results.push_back(ToVecInt);
17279 SmallVector<SDValue, 8> Elts;
17280 for (unsigned i = 0, e = NumElts; i != e; ++i)
17281 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17282 ToVecInt, DAG.getIntPtrConstant(i)));
17284 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17289 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17291 default: return nullptr;
17292 case X86ISD::BSF: return "X86ISD::BSF";
17293 case X86ISD::BSR: return "X86ISD::BSR";
17294 case X86ISD::SHLD: return "X86ISD::SHLD";
17295 case X86ISD::SHRD: return "X86ISD::SHRD";
17296 case X86ISD::FAND: return "X86ISD::FAND";
17297 case X86ISD::FANDN: return "X86ISD::FANDN";
17298 case X86ISD::FOR: return "X86ISD::FOR";
17299 case X86ISD::FXOR: return "X86ISD::FXOR";
17300 case X86ISD::FSRL: return "X86ISD::FSRL";
17301 case X86ISD::FILD: return "X86ISD::FILD";
17302 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17303 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17304 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17305 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17306 case X86ISD::FLD: return "X86ISD::FLD";
17307 case X86ISD::FST: return "X86ISD::FST";
17308 case X86ISD::CALL: return "X86ISD::CALL";
17309 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17310 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17311 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17312 case X86ISD::BT: return "X86ISD::BT";
17313 case X86ISD::CMP: return "X86ISD::CMP";
17314 case X86ISD::COMI: return "X86ISD::COMI";
17315 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17316 case X86ISD::CMPM: return "X86ISD::CMPM";
17317 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17318 case X86ISD::SETCC: return "X86ISD::SETCC";
17319 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17320 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17321 case X86ISD::CMOV: return "X86ISD::CMOV";
17322 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17323 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17324 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17325 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17326 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17327 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17328 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17329 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17330 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17331 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17332 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17333 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17334 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17335 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17336 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17337 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17338 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17339 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17340 case X86ISD::HADD: return "X86ISD::HADD";
17341 case X86ISD::HSUB: return "X86ISD::HSUB";
17342 case X86ISD::FHADD: return "X86ISD::FHADD";
17343 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17344 case X86ISD::UMAX: return "X86ISD::UMAX";
17345 case X86ISD::UMIN: return "X86ISD::UMIN";
17346 case X86ISD::SMAX: return "X86ISD::SMAX";
17347 case X86ISD::SMIN: return "X86ISD::SMIN";
17348 case X86ISD::FMAX: return "X86ISD::FMAX";
17349 case X86ISD::FMIN: return "X86ISD::FMIN";
17350 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17351 case X86ISD::FMINC: return "X86ISD::FMINC";
17352 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17353 case X86ISD::FRCP: return "X86ISD::FRCP";
17354 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17355 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17356 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17357 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17358 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17359 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17360 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17361 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17362 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17363 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17364 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17365 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17366 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17367 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17368 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17369 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17370 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17371 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17372 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17373 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17374 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17375 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17376 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17377 case X86ISD::VSHL: return "X86ISD::VSHL";
17378 case X86ISD::VSRL: return "X86ISD::VSRL";
17379 case X86ISD::VSRA: return "X86ISD::VSRA";
17380 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17381 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17382 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17383 case X86ISD::CMPP: return "X86ISD::CMPP";
17384 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17385 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17386 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17387 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17388 case X86ISD::ADD: return "X86ISD::ADD";
17389 case X86ISD::SUB: return "X86ISD::SUB";
17390 case X86ISD::ADC: return "X86ISD::ADC";
17391 case X86ISD::SBB: return "X86ISD::SBB";
17392 case X86ISD::SMUL: return "X86ISD::SMUL";
17393 case X86ISD::UMUL: return "X86ISD::UMUL";
17394 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17395 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17396 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17397 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17398 case X86ISD::INC: return "X86ISD::INC";
17399 case X86ISD::DEC: return "X86ISD::DEC";
17400 case X86ISD::OR: return "X86ISD::OR";
17401 case X86ISD::XOR: return "X86ISD::XOR";
17402 case X86ISD::AND: return "X86ISD::AND";
17403 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17404 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17405 case X86ISD::PTEST: return "X86ISD::PTEST";
17406 case X86ISD::TESTP: return "X86ISD::TESTP";
17407 case X86ISD::TESTM: return "X86ISD::TESTM";
17408 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17409 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17410 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17411 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17412 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17413 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17414 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17415 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17416 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17417 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17418 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17419 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17420 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17421 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17422 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17423 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17424 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17425 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17426 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17427 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17428 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17429 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17430 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17431 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17432 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17433 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17434 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17435 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17436 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17437 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17438 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17439 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17440 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17441 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17442 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17443 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17444 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17445 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17446 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17447 case X86ISD::SAHF: return "X86ISD::SAHF";
17448 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17449 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17450 case X86ISD::FMADD: return "X86ISD::FMADD";
17451 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17452 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17453 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17454 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17455 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17456 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17457 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17458 case X86ISD::XTEST: return "X86ISD::XTEST";
17459 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17460 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17461 case X86ISD::SELECT: return "X86ISD::SELECT";
17462 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17463 case X86ISD::RCP28: return "X86ISD::RCP28";
17464 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17465 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17466 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17467 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17468 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17472 // isLegalAddressingMode - Return true if the addressing mode represented
17473 // by AM is legal for this target, for a load/store of the specified type.
17474 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17476 // X86 supports extremely general addressing modes.
17477 CodeModel::Model M = getTargetMachine().getCodeModel();
17478 Reloc::Model R = getTargetMachine().getRelocationModel();
17480 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17481 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17486 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17488 // If a reference to this global requires an extra load, we can't fold it.
17489 if (isGlobalStubReference(GVFlags))
17492 // If BaseGV requires a register for the PIC base, we cannot also have a
17493 // BaseReg specified.
17494 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17497 // If lower 4G is not available, then we must use rip-relative addressing.
17498 if ((M != CodeModel::Small || R != Reloc::Static) &&
17499 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17503 switch (AM.Scale) {
17509 // These scales always work.
17514 // These scales are formed with basereg+scalereg. Only accept if there is
17519 default: // Other stuff never works.
17526 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17527 unsigned Bits = Ty->getScalarSizeInBits();
17529 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17530 // particularly cheaper than those without.
17534 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17535 // variable shifts just as cheap as scalar ones.
17536 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17539 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17540 // fully general vector.
17544 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17545 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17547 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17548 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17549 return NumBits1 > NumBits2;
17552 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17553 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17556 if (!isTypeLegal(EVT::getEVT(Ty1)))
17559 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17561 // Assuming the caller doesn't have a zeroext or signext return parameter,
17562 // truncation all the way down to i1 is valid.
17566 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17567 return isInt<32>(Imm);
17570 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17571 // Can also use sub to handle negated immediates.
17572 return isInt<32>(Imm);
17575 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17576 if (!VT1.isInteger() || !VT2.isInteger())
17578 unsigned NumBits1 = VT1.getSizeInBits();
17579 unsigned NumBits2 = VT2.getSizeInBits();
17580 return NumBits1 > NumBits2;
17583 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17584 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17585 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17588 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17589 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17590 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17593 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17594 EVT VT1 = Val.getValueType();
17595 if (isZExtFree(VT1, VT2))
17598 if (Val.getOpcode() != ISD::LOAD)
17601 if (!VT1.isSimple() || !VT1.isInteger() ||
17602 !VT2.isSimple() || !VT2.isInteger())
17605 switch (VT1.getSimpleVT().SimpleTy) {
17610 // X86 has 8, 16, and 32-bit zero-extending loads.
17617 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17620 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17621 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17624 VT = VT.getScalarType();
17626 if (!VT.isSimple())
17629 switch (VT.getSimpleVT().SimpleTy) {
17640 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17641 // i16 instructions are longer (0x66 prefix) and potentially slower.
17642 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17645 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17646 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17647 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17648 /// are assumed to be legal.
17650 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17652 if (!VT.isSimple())
17655 // Very little shuffling can be done for 64-bit vectors right now.
17656 if (VT.getSizeInBits() == 64)
17659 // We only care that the types being shuffled are legal. The lowering can
17660 // handle any possible shuffle mask that results.
17661 return isTypeLegal(VT.getSimpleVT());
17665 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17667 // Just delegate to the generic legality, clear masks aren't special.
17668 return isShuffleMaskLegal(Mask, VT);
17671 //===----------------------------------------------------------------------===//
17672 // X86 Scheduler Hooks
17673 //===----------------------------------------------------------------------===//
17675 /// Utility function to emit xbegin specifying the start of an RTM region.
17676 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17677 const TargetInstrInfo *TII) {
17678 DebugLoc DL = MI->getDebugLoc();
17680 const BasicBlock *BB = MBB->getBasicBlock();
17681 MachineFunction::iterator I = MBB;
17684 // For the v = xbegin(), we generate
17695 MachineBasicBlock *thisMBB = MBB;
17696 MachineFunction *MF = MBB->getParent();
17697 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17698 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17699 MF->insert(I, mainMBB);
17700 MF->insert(I, sinkMBB);
17702 // Transfer the remainder of BB and its successor edges to sinkMBB.
17703 sinkMBB->splice(sinkMBB->begin(), MBB,
17704 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17705 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17709 // # fallthrough to mainMBB
17710 // # abortion to sinkMBB
17711 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17712 thisMBB->addSuccessor(mainMBB);
17713 thisMBB->addSuccessor(sinkMBB);
17717 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17718 mainMBB->addSuccessor(sinkMBB);
17721 // EAX is live into the sinkMBB
17722 sinkMBB->addLiveIn(X86::EAX);
17723 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17724 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17727 MI->eraseFromParent();
17731 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17732 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17733 // in the .td file.
17734 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17735 const TargetInstrInfo *TII) {
17737 switch (MI->getOpcode()) {
17738 default: llvm_unreachable("illegal opcode!");
17739 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17740 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17741 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17742 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17743 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17744 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17745 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17746 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17749 DebugLoc dl = MI->getDebugLoc();
17750 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17752 unsigned NumArgs = MI->getNumOperands();
17753 for (unsigned i = 1; i < NumArgs; ++i) {
17754 MachineOperand &Op = MI->getOperand(i);
17755 if (!(Op.isReg() && Op.isImplicit()))
17756 MIB.addOperand(Op);
17758 if (MI->hasOneMemOperand())
17759 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17761 BuildMI(*BB, MI, dl,
17762 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17763 .addReg(X86::XMM0);
17765 MI->eraseFromParent();
17769 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17770 // defs in an instruction pattern
17771 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17772 const TargetInstrInfo *TII) {
17774 switch (MI->getOpcode()) {
17775 default: llvm_unreachable("illegal opcode!");
17776 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17777 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17778 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17779 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17780 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17781 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17782 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17783 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17786 DebugLoc dl = MI->getDebugLoc();
17787 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17789 unsigned NumArgs = MI->getNumOperands(); // remove the results
17790 for (unsigned i = 1; i < NumArgs; ++i) {
17791 MachineOperand &Op = MI->getOperand(i);
17792 if (!(Op.isReg() && Op.isImplicit()))
17793 MIB.addOperand(Op);
17795 if (MI->hasOneMemOperand())
17796 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17798 BuildMI(*BB, MI, dl,
17799 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17802 MI->eraseFromParent();
17806 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17807 const X86Subtarget *Subtarget) {
17808 DebugLoc dl = MI->getDebugLoc();
17809 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17810 // Address into RAX/EAX, other two args into ECX, EDX.
17811 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17812 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17813 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17814 for (int i = 0; i < X86::AddrNumOperands; ++i)
17815 MIB.addOperand(MI->getOperand(i));
17817 unsigned ValOps = X86::AddrNumOperands;
17818 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17819 .addReg(MI->getOperand(ValOps).getReg());
17820 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17821 .addReg(MI->getOperand(ValOps+1).getReg());
17823 // The instruction doesn't actually take any operands though.
17824 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17826 MI->eraseFromParent(); // The pseudo is gone now.
17830 MachineBasicBlock *
17831 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17832 MachineBasicBlock *MBB) const {
17833 // Emit va_arg instruction on X86-64.
17835 // Operands to this pseudo-instruction:
17836 // 0 ) Output : destination address (reg)
17837 // 1-5) Input : va_list address (addr, i64mem)
17838 // 6 ) ArgSize : Size (in bytes) of vararg type
17839 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17840 // 8 ) Align : Alignment of type
17841 // 9 ) EFLAGS (implicit-def)
17843 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17844 static_assert(X86::AddrNumOperands == 5,
17845 "VAARG_64 assumes 5 address operands");
17847 unsigned DestReg = MI->getOperand(0).getReg();
17848 MachineOperand &Base = MI->getOperand(1);
17849 MachineOperand &Scale = MI->getOperand(2);
17850 MachineOperand &Index = MI->getOperand(3);
17851 MachineOperand &Disp = MI->getOperand(4);
17852 MachineOperand &Segment = MI->getOperand(5);
17853 unsigned ArgSize = MI->getOperand(6).getImm();
17854 unsigned ArgMode = MI->getOperand(7).getImm();
17855 unsigned Align = MI->getOperand(8).getImm();
17857 // Memory Reference
17858 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17859 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17860 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17862 // Machine Information
17863 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17864 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17865 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17866 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17867 DebugLoc DL = MI->getDebugLoc();
17869 // struct va_list {
17872 // i64 overflow_area (address)
17873 // i64 reg_save_area (address)
17875 // sizeof(va_list) = 24
17876 // alignment(va_list) = 8
17878 unsigned TotalNumIntRegs = 6;
17879 unsigned TotalNumXMMRegs = 8;
17880 bool UseGPOffset = (ArgMode == 1);
17881 bool UseFPOffset = (ArgMode == 2);
17882 unsigned MaxOffset = TotalNumIntRegs * 8 +
17883 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17885 /* Align ArgSize to a multiple of 8 */
17886 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17887 bool NeedsAlign = (Align > 8);
17889 MachineBasicBlock *thisMBB = MBB;
17890 MachineBasicBlock *overflowMBB;
17891 MachineBasicBlock *offsetMBB;
17892 MachineBasicBlock *endMBB;
17894 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17895 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17896 unsigned OffsetReg = 0;
17898 if (!UseGPOffset && !UseFPOffset) {
17899 // If we only pull from the overflow region, we don't create a branch.
17900 // We don't need to alter control flow.
17901 OffsetDestReg = 0; // unused
17902 OverflowDestReg = DestReg;
17904 offsetMBB = nullptr;
17905 overflowMBB = thisMBB;
17908 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17909 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17910 // If not, pull from overflow_area. (branch to overflowMBB)
17915 // offsetMBB overflowMBB
17920 // Registers for the PHI in endMBB
17921 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17922 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17924 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17925 MachineFunction *MF = MBB->getParent();
17926 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17927 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17928 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17930 MachineFunction::iterator MBBIter = MBB;
17933 // Insert the new basic blocks
17934 MF->insert(MBBIter, offsetMBB);
17935 MF->insert(MBBIter, overflowMBB);
17936 MF->insert(MBBIter, endMBB);
17938 // Transfer the remainder of MBB and its successor edges to endMBB.
17939 endMBB->splice(endMBB->begin(), thisMBB,
17940 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17941 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17943 // Make offsetMBB and overflowMBB successors of thisMBB
17944 thisMBB->addSuccessor(offsetMBB);
17945 thisMBB->addSuccessor(overflowMBB);
17947 // endMBB is a successor of both offsetMBB and overflowMBB
17948 offsetMBB->addSuccessor(endMBB);
17949 overflowMBB->addSuccessor(endMBB);
17951 // Load the offset value into a register
17952 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17953 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17957 .addDisp(Disp, UseFPOffset ? 4 : 0)
17958 .addOperand(Segment)
17959 .setMemRefs(MMOBegin, MMOEnd);
17961 // Check if there is enough room left to pull this argument.
17962 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17964 .addImm(MaxOffset + 8 - ArgSizeA8);
17966 // Branch to "overflowMBB" if offset >= max
17967 // Fall through to "offsetMBB" otherwise
17968 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17969 .addMBB(overflowMBB);
17972 // In offsetMBB, emit code to use the reg_save_area.
17974 assert(OffsetReg != 0);
17976 // Read the reg_save_area address.
17977 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17978 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17983 .addOperand(Segment)
17984 .setMemRefs(MMOBegin, MMOEnd);
17986 // Zero-extend the offset
17987 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17988 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17991 .addImm(X86::sub_32bit);
17993 // Add the offset to the reg_save_area to get the final address.
17994 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17995 .addReg(OffsetReg64)
17996 .addReg(RegSaveReg);
17998 // Compute the offset for the next argument
17999 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18000 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18002 .addImm(UseFPOffset ? 16 : 8);
18004 // Store it back into the va_list.
18005 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18009 .addDisp(Disp, UseFPOffset ? 4 : 0)
18010 .addOperand(Segment)
18011 .addReg(NextOffsetReg)
18012 .setMemRefs(MMOBegin, MMOEnd);
18015 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18020 // Emit code to use overflow area
18023 // Load the overflow_area address into a register.
18024 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18025 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18030 .addOperand(Segment)
18031 .setMemRefs(MMOBegin, MMOEnd);
18033 // If we need to align it, do so. Otherwise, just copy the address
18034 // to OverflowDestReg.
18036 // Align the overflow address
18037 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18038 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18040 // aligned_addr = (addr + (align-1)) & ~(align-1)
18041 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18042 .addReg(OverflowAddrReg)
18045 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18047 .addImm(~(uint64_t)(Align-1));
18049 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18050 .addReg(OverflowAddrReg);
18053 // Compute the next overflow address after this argument.
18054 // (the overflow address should be kept 8-byte aligned)
18055 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18056 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18057 .addReg(OverflowDestReg)
18058 .addImm(ArgSizeA8);
18060 // Store the new overflow address.
18061 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18066 .addOperand(Segment)
18067 .addReg(NextAddrReg)
18068 .setMemRefs(MMOBegin, MMOEnd);
18070 // If we branched, emit the PHI to the front of endMBB.
18072 BuildMI(*endMBB, endMBB->begin(), DL,
18073 TII->get(X86::PHI), DestReg)
18074 .addReg(OffsetDestReg).addMBB(offsetMBB)
18075 .addReg(OverflowDestReg).addMBB(overflowMBB);
18078 // Erase the pseudo instruction
18079 MI->eraseFromParent();
18084 MachineBasicBlock *
18085 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18087 MachineBasicBlock *MBB) const {
18088 // Emit code to save XMM registers to the stack. The ABI says that the
18089 // number of registers to save is given in %al, so it's theoretically
18090 // possible to do an indirect jump trick to avoid saving all of them,
18091 // however this code takes a simpler approach and just executes all
18092 // of the stores if %al is non-zero. It's less code, and it's probably
18093 // easier on the hardware branch predictor, and stores aren't all that
18094 // expensive anyway.
18096 // Create the new basic blocks. One block contains all the XMM stores,
18097 // and one block is the final destination regardless of whether any
18098 // stores were performed.
18099 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18100 MachineFunction *F = MBB->getParent();
18101 MachineFunction::iterator MBBIter = MBB;
18103 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18104 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18105 F->insert(MBBIter, XMMSaveMBB);
18106 F->insert(MBBIter, EndMBB);
18108 // Transfer the remainder of MBB and its successor edges to EndMBB.
18109 EndMBB->splice(EndMBB->begin(), MBB,
18110 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18111 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18113 // The original block will now fall through to the XMM save block.
18114 MBB->addSuccessor(XMMSaveMBB);
18115 // The XMMSaveMBB will fall through to the end block.
18116 XMMSaveMBB->addSuccessor(EndMBB);
18118 // Now add the instructions.
18119 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18120 DebugLoc DL = MI->getDebugLoc();
18122 unsigned CountReg = MI->getOperand(0).getReg();
18123 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18124 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18126 if (!Subtarget->isTargetWin64()) {
18127 // If %al is 0, branch around the XMM save block.
18128 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18129 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18130 MBB->addSuccessor(EndMBB);
18133 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18134 // that was just emitted, but clearly shouldn't be "saved".
18135 assert((MI->getNumOperands() <= 3 ||
18136 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18137 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18138 && "Expected last argument to be EFLAGS");
18139 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18140 // In the XMM save block, save all the XMM argument registers.
18141 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18142 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18143 MachineMemOperand *MMO =
18144 F->getMachineMemOperand(
18145 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18146 MachineMemOperand::MOStore,
18147 /*Size=*/16, /*Align=*/16);
18148 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18149 .addFrameIndex(RegSaveFrameIndex)
18150 .addImm(/*Scale=*/1)
18151 .addReg(/*IndexReg=*/0)
18152 .addImm(/*Disp=*/Offset)
18153 .addReg(/*Segment=*/0)
18154 .addReg(MI->getOperand(i).getReg())
18155 .addMemOperand(MMO);
18158 MI->eraseFromParent(); // The pseudo instruction is gone now.
18163 // The EFLAGS operand of SelectItr might be missing a kill marker
18164 // because there were multiple uses of EFLAGS, and ISel didn't know
18165 // which to mark. Figure out whether SelectItr should have had a
18166 // kill marker, and set it if it should. Returns the correct kill
18168 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18169 MachineBasicBlock* BB,
18170 const TargetRegisterInfo* TRI) {
18171 // Scan forward through BB for a use/def of EFLAGS.
18172 MachineBasicBlock::iterator miI(std::next(SelectItr));
18173 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18174 const MachineInstr& mi = *miI;
18175 if (mi.readsRegister(X86::EFLAGS))
18177 if (mi.definesRegister(X86::EFLAGS))
18178 break; // Should have kill-flag - update below.
18181 // If we hit the end of the block, check whether EFLAGS is live into a
18183 if (miI == BB->end()) {
18184 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18185 sEnd = BB->succ_end();
18186 sItr != sEnd; ++sItr) {
18187 MachineBasicBlock* succ = *sItr;
18188 if (succ->isLiveIn(X86::EFLAGS))
18193 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18194 // out. SelectMI should have a kill flag on EFLAGS.
18195 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18199 MachineBasicBlock *
18200 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18201 MachineBasicBlock *BB) const {
18202 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18203 DebugLoc DL = MI->getDebugLoc();
18205 // To "insert" a SELECT_CC instruction, we actually have to insert the
18206 // diamond control-flow pattern. The incoming instruction knows the
18207 // destination vreg to set, the condition code register to branch on, the
18208 // true/false values to select between, and a branch opcode to use.
18209 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18210 MachineFunction::iterator It = BB;
18216 // cmpTY ccX, r1, r2
18218 // fallthrough --> copy0MBB
18219 MachineBasicBlock *thisMBB = BB;
18220 MachineFunction *F = BB->getParent();
18222 // We also lower double CMOVs:
18223 // (CMOV (CMOV F, T, cc1), T, cc2)
18224 // to two successives branches. For that, we look for another CMOV as the
18225 // following instruction.
18227 // Without this, we would add a PHI between the two jumps, which ends up
18228 // creating a few copies all around. For instance, for
18230 // (sitofp (zext (fcmp une)))
18232 // we would generate:
18234 // ucomiss %xmm1, %xmm0
18235 // movss <1.0f>, %xmm0
18236 // movaps %xmm0, %xmm1
18238 // xorps %xmm1, %xmm1
18241 // movaps %xmm1, %xmm0
18245 // because this custom-inserter would have generated:
18257 // A: X = ...; Y = ...
18259 // C: Z = PHI [X, A], [Y, B]
18261 // E: PHI [X, C], [Z, D]
18263 // If we lower both CMOVs in a single step, we can instead generate:
18275 // A: X = ...; Y = ...
18277 // E: PHI [X, A], [X, C], [Y, D]
18279 // Which, in our sitofp/fcmp example, gives us something like:
18281 // ucomiss %xmm1, %xmm0
18282 // movss <1.0f>, %xmm0
18285 // xorps %xmm0, %xmm0
18289 MachineInstr *NextCMOV = nullptr;
18290 MachineBasicBlock::iterator NextMIIt =
18291 std::next(MachineBasicBlock::iterator(MI));
18292 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18293 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18294 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18295 NextCMOV = &*NextMIIt;
18297 MachineBasicBlock *jcc1MBB = nullptr;
18299 // If we have a double CMOV, we lower it to two successive branches to
18300 // the same block. EFLAGS is used by both, so mark it as live in the second.
18302 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18303 F->insert(It, jcc1MBB);
18304 jcc1MBB->addLiveIn(X86::EFLAGS);
18307 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18308 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18309 F->insert(It, copy0MBB);
18310 F->insert(It, sinkMBB);
18312 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18313 // live into the sink and copy blocks.
18314 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18316 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18317 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18318 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18319 copy0MBB->addLiveIn(X86::EFLAGS);
18320 sinkMBB->addLiveIn(X86::EFLAGS);
18323 // Transfer the remainder of BB and its successor edges to sinkMBB.
18324 sinkMBB->splice(sinkMBB->begin(), BB,
18325 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18326 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18328 // Add the true and fallthrough blocks as its successors.
18330 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18331 BB->addSuccessor(jcc1MBB);
18333 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18334 // jump to the sinkMBB.
18335 jcc1MBB->addSuccessor(copy0MBB);
18336 jcc1MBB->addSuccessor(sinkMBB);
18338 BB->addSuccessor(copy0MBB);
18341 // The true block target of the first (or only) branch is always sinkMBB.
18342 BB->addSuccessor(sinkMBB);
18344 // Create the conditional branch instruction.
18346 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18347 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18350 unsigned Opc2 = X86::GetCondBranchFromCond(
18351 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18352 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18356 // %FalseValue = ...
18357 // # fallthrough to sinkMBB
18358 copy0MBB->addSuccessor(sinkMBB);
18361 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18363 MachineInstrBuilder MIB =
18364 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18365 MI->getOperand(0).getReg())
18366 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18367 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18369 // If we have a double CMOV, the second Jcc provides the same incoming
18370 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18372 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18373 // Copy the PHI result to the register defined by the second CMOV.
18374 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18375 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18376 .addReg(MI->getOperand(0).getReg());
18377 NextCMOV->eraseFromParent();
18380 MI->eraseFromParent(); // The pseudo instruction is gone now.
18384 MachineBasicBlock *
18385 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18386 MachineBasicBlock *BB) const {
18387 MachineFunction *MF = BB->getParent();
18388 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18389 DebugLoc DL = MI->getDebugLoc();
18390 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18392 assert(MF->shouldSplitStack());
18394 const bool Is64Bit = Subtarget->is64Bit();
18395 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18397 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18398 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18401 // ... [Till the alloca]
18402 // If stacklet is not large enough, jump to mallocMBB
18405 // Allocate by subtracting from RSP
18406 // Jump to continueMBB
18409 // Allocate by call to runtime
18413 // [rest of original BB]
18416 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18417 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18418 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18420 MachineRegisterInfo &MRI = MF->getRegInfo();
18421 const TargetRegisterClass *AddrRegClass =
18422 getRegClassFor(getPointerTy());
18424 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18425 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18426 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18427 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18428 sizeVReg = MI->getOperand(1).getReg(),
18429 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18431 MachineFunction::iterator MBBIter = BB;
18434 MF->insert(MBBIter, bumpMBB);
18435 MF->insert(MBBIter, mallocMBB);
18436 MF->insert(MBBIter, continueMBB);
18438 continueMBB->splice(continueMBB->begin(), BB,
18439 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18440 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18442 // Add code to the main basic block to check if the stack limit has been hit,
18443 // and if so, jump to mallocMBB otherwise to bumpMBB.
18444 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18445 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18446 .addReg(tmpSPVReg).addReg(sizeVReg);
18447 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18448 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18449 .addReg(SPLimitVReg);
18450 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18452 // bumpMBB simply decreases the stack pointer, since we know the current
18453 // stacklet has enough space.
18454 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18455 .addReg(SPLimitVReg);
18456 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18457 .addReg(SPLimitVReg);
18458 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18460 // Calls into a routine in libgcc to allocate more space from the heap.
18461 const uint32_t *RegMask =
18462 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18464 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18466 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18467 .addExternalSymbol("__morestack_allocate_stack_space")
18468 .addRegMask(RegMask)
18469 .addReg(X86::RDI, RegState::Implicit)
18470 .addReg(X86::RAX, RegState::ImplicitDefine);
18471 } else if (Is64Bit) {
18472 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18474 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18475 .addExternalSymbol("__morestack_allocate_stack_space")
18476 .addRegMask(RegMask)
18477 .addReg(X86::EDI, RegState::Implicit)
18478 .addReg(X86::EAX, RegState::ImplicitDefine);
18480 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18482 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18483 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18484 .addExternalSymbol("__morestack_allocate_stack_space")
18485 .addRegMask(RegMask)
18486 .addReg(X86::EAX, RegState::ImplicitDefine);
18490 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18493 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18494 .addReg(IsLP64 ? X86::RAX : X86::EAX);
18495 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18497 // Set up the CFG correctly.
18498 BB->addSuccessor(bumpMBB);
18499 BB->addSuccessor(mallocMBB);
18500 mallocMBB->addSuccessor(continueMBB);
18501 bumpMBB->addSuccessor(continueMBB);
18503 // Take care of the PHI nodes.
18504 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18505 MI->getOperand(0).getReg())
18506 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18507 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18509 // Delete the original pseudo instruction.
18510 MI->eraseFromParent();
18513 return continueMBB;
18516 MachineBasicBlock *
18517 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18518 MachineBasicBlock *BB) const {
18519 DebugLoc DL = MI->getDebugLoc();
18521 assert(!Subtarget->isTargetMachO());
18523 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18525 MI->eraseFromParent(); // The pseudo instruction is gone now.
18529 MachineBasicBlock *
18530 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18531 MachineBasicBlock *BB) const {
18532 // This is pretty easy. We're taking the value that we received from
18533 // our load from the relocation, sticking it in either RDI (x86-64)
18534 // or EAX and doing an indirect call. The return value will then
18535 // be in the normal return register.
18536 MachineFunction *F = BB->getParent();
18537 const X86InstrInfo *TII = Subtarget->getInstrInfo();
18538 DebugLoc DL = MI->getDebugLoc();
18540 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18541 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18543 // Get a register mask for the lowered call.
18544 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18545 // proper register mask.
18546 const uint32_t *RegMask =
18547 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18548 if (Subtarget->is64Bit()) {
18549 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18550 TII->get(X86::MOV64rm), X86::RDI)
18552 .addImm(0).addReg(0)
18553 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18554 MI->getOperand(3).getTargetFlags())
18556 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18557 addDirectMem(MIB, X86::RDI);
18558 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18559 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18560 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18561 TII->get(X86::MOV32rm), X86::EAX)
18563 .addImm(0).addReg(0)
18564 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18565 MI->getOperand(3).getTargetFlags())
18567 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18568 addDirectMem(MIB, X86::EAX);
18569 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18571 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18572 TII->get(X86::MOV32rm), X86::EAX)
18573 .addReg(TII->getGlobalBaseReg(F))
18574 .addImm(0).addReg(0)
18575 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18576 MI->getOperand(3).getTargetFlags())
18578 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18579 addDirectMem(MIB, X86::EAX);
18580 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18583 MI->eraseFromParent(); // The pseudo instruction is gone now.
18587 MachineBasicBlock *
18588 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18589 MachineBasicBlock *MBB) const {
18590 DebugLoc DL = MI->getDebugLoc();
18591 MachineFunction *MF = MBB->getParent();
18592 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18593 MachineRegisterInfo &MRI = MF->getRegInfo();
18595 const BasicBlock *BB = MBB->getBasicBlock();
18596 MachineFunction::iterator I = MBB;
18599 // Memory Reference
18600 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18601 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18604 unsigned MemOpndSlot = 0;
18606 unsigned CurOp = 0;
18608 DstReg = MI->getOperand(CurOp++).getReg();
18609 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18610 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18611 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18612 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18614 MemOpndSlot = CurOp;
18616 MVT PVT = getPointerTy();
18617 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18618 "Invalid Pointer Size!");
18620 // For v = setjmp(buf), we generate
18623 // buf[LabelOffset] = restoreMBB
18624 // SjLjSetup restoreMBB
18630 // v = phi(main, restore)
18633 // if base pointer being used, load it from frame
18636 MachineBasicBlock *thisMBB = MBB;
18637 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18638 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18639 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18640 MF->insert(I, mainMBB);
18641 MF->insert(I, sinkMBB);
18642 MF->push_back(restoreMBB);
18644 MachineInstrBuilder MIB;
18646 // Transfer the remainder of BB and its successor edges to sinkMBB.
18647 sinkMBB->splice(sinkMBB->begin(), MBB,
18648 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18649 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18652 unsigned PtrStoreOpc = 0;
18653 unsigned LabelReg = 0;
18654 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18655 Reloc::Model RM = MF->getTarget().getRelocationModel();
18656 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18657 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18659 // Prepare IP either in reg or imm.
18660 if (!UseImmLabel) {
18661 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18662 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18663 LabelReg = MRI.createVirtualRegister(PtrRC);
18664 if (Subtarget->is64Bit()) {
18665 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18669 .addMBB(restoreMBB)
18672 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18673 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18674 .addReg(XII->getGlobalBaseReg(MF))
18677 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18681 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18683 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18684 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18685 if (i == X86::AddrDisp)
18686 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18688 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18691 MIB.addReg(LabelReg);
18693 MIB.addMBB(restoreMBB);
18694 MIB.setMemRefs(MMOBegin, MMOEnd);
18696 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18697 .addMBB(restoreMBB);
18699 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18700 MIB.addRegMask(RegInfo->getNoPreservedMask());
18701 thisMBB->addSuccessor(mainMBB);
18702 thisMBB->addSuccessor(restoreMBB);
18706 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18707 mainMBB->addSuccessor(sinkMBB);
18710 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18711 TII->get(X86::PHI), DstReg)
18712 .addReg(mainDstReg).addMBB(mainMBB)
18713 .addReg(restoreDstReg).addMBB(restoreMBB);
18716 if (RegInfo->hasBasePointer(*MF)) {
18717 const bool Uses64BitFramePtr =
18718 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18719 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18720 X86FI->setRestoreBasePointer(MF);
18721 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18722 unsigned BasePtr = RegInfo->getBaseRegister();
18723 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18724 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18725 FramePtr, true, X86FI->getRestoreBasePointerOffset())
18726 .setMIFlag(MachineInstr::FrameSetup);
18728 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18729 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18730 restoreMBB->addSuccessor(sinkMBB);
18732 MI->eraseFromParent();
18736 MachineBasicBlock *
18737 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18738 MachineBasicBlock *MBB) const {
18739 DebugLoc DL = MI->getDebugLoc();
18740 MachineFunction *MF = MBB->getParent();
18741 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18742 MachineRegisterInfo &MRI = MF->getRegInfo();
18744 // Memory Reference
18745 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18746 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18748 MVT PVT = getPointerTy();
18749 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18750 "Invalid Pointer Size!");
18752 const TargetRegisterClass *RC =
18753 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18754 unsigned Tmp = MRI.createVirtualRegister(RC);
18755 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18756 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18757 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18758 unsigned SP = RegInfo->getStackRegister();
18760 MachineInstrBuilder MIB;
18762 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18763 const int64_t SPOffset = 2 * PVT.getStoreSize();
18765 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18766 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18769 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18770 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18771 MIB.addOperand(MI->getOperand(i));
18772 MIB.setMemRefs(MMOBegin, MMOEnd);
18774 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18775 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18776 if (i == X86::AddrDisp)
18777 MIB.addDisp(MI->getOperand(i), LabelOffset);
18779 MIB.addOperand(MI->getOperand(i));
18781 MIB.setMemRefs(MMOBegin, MMOEnd);
18783 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18784 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18785 if (i == X86::AddrDisp)
18786 MIB.addDisp(MI->getOperand(i), SPOffset);
18788 MIB.addOperand(MI->getOperand(i));
18790 MIB.setMemRefs(MMOBegin, MMOEnd);
18792 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18794 MI->eraseFromParent();
18798 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18799 // accumulator loops. Writing back to the accumulator allows the coalescer
18800 // to remove extra copies in the loop.
18801 MachineBasicBlock *
18802 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18803 MachineBasicBlock *MBB) const {
18804 MachineOperand &AddendOp = MI->getOperand(3);
18806 // Bail out early if the addend isn't a register - we can't switch these.
18807 if (!AddendOp.isReg())
18810 MachineFunction &MF = *MBB->getParent();
18811 MachineRegisterInfo &MRI = MF.getRegInfo();
18813 // Check whether the addend is defined by a PHI:
18814 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18815 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18816 if (!AddendDef.isPHI())
18819 // Look for the following pattern:
18821 // %addend = phi [%entry, 0], [%loop, %result]
18823 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18827 // %addend = phi [%entry, 0], [%loop, %result]
18829 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18831 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18832 assert(AddendDef.getOperand(i).isReg());
18833 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18834 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18835 if (&PHISrcInst == MI) {
18836 // Found a matching instruction.
18837 unsigned NewFMAOpc = 0;
18838 switch (MI->getOpcode()) {
18839 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18840 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18841 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18842 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18843 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18844 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18845 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18846 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18847 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18848 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18849 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18850 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18851 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18852 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18853 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18854 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18855 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18856 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18857 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18858 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18860 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18861 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18862 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18863 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18864 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18865 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18866 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18867 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18868 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18869 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18870 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18871 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18872 default: llvm_unreachable("Unrecognized FMA variant.");
18875 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18876 MachineInstrBuilder MIB =
18877 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18878 .addOperand(MI->getOperand(0))
18879 .addOperand(MI->getOperand(3))
18880 .addOperand(MI->getOperand(2))
18881 .addOperand(MI->getOperand(1));
18882 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18883 MI->eraseFromParent();
18890 MachineBasicBlock *
18891 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18892 MachineBasicBlock *BB) const {
18893 switch (MI->getOpcode()) {
18894 default: llvm_unreachable("Unexpected instr type to insert");
18895 case X86::TAILJMPd64:
18896 case X86::TAILJMPr64:
18897 case X86::TAILJMPm64:
18898 case X86::TAILJMPd64_REX:
18899 case X86::TAILJMPr64_REX:
18900 case X86::TAILJMPm64_REX:
18901 llvm_unreachable("TAILJMP64 would not be touched here.");
18902 case X86::TCRETURNdi64:
18903 case X86::TCRETURNri64:
18904 case X86::TCRETURNmi64:
18906 case X86::WIN_ALLOCA:
18907 return EmitLoweredWinAlloca(MI, BB);
18908 case X86::SEG_ALLOCA_32:
18909 case X86::SEG_ALLOCA_64:
18910 return EmitLoweredSegAlloca(MI, BB);
18911 case X86::TLSCall_32:
18912 case X86::TLSCall_64:
18913 return EmitLoweredTLSCall(MI, BB);
18914 case X86::CMOV_GR8:
18915 case X86::CMOV_FR32:
18916 case X86::CMOV_FR64:
18917 case X86::CMOV_V4F32:
18918 case X86::CMOV_V2F64:
18919 case X86::CMOV_V2I64:
18920 case X86::CMOV_V8F32:
18921 case X86::CMOV_V4F64:
18922 case X86::CMOV_V4I64:
18923 case X86::CMOV_V16F32:
18924 case X86::CMOV_V8F64:
18925 case X86::CMOV_V8I64:
18926 case X86::CMOV_GR16:
18927 case X86::CMOV_GR32:
18928 case X86::CMOV_RFP32:
18929 case X86::CMOV_RFP64:
18930 case X86::CMOV_RFP80:
18931 return EmitLoweredSelect(MI, BB);
18933 case X86::FP32_TO_INT16_IN_MEM:
18934 case X86::FP32_TO_INT32_IN_MEM:
18935 case X86::FP32_TO_INT64_IN_MEM:
18936 case X86::FP64_TO_INT16_IN_MEM:
18937 case X86::FP64_TO_INT32_IN_MEM:
18938 case X86::FP64_TO_INT64_IN_MEM:
18939 case X86::FP80_TO_INT16_IN_MEM:
18940 case X86::FP80_TO_INT32_IN_MEM:
18941 case X86::FP80_TO_INT64_IN_MEM: {
18942 MachineFunction *F = BB->getParent();
18943 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18944 DebugLoc DL = MI->getDebugLoc();
18946 // Change the floating point control register to use "round towards zero"
18947 // mode when truncating to an integer value.
18948 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18949 addFrameReference(BuildMI(*BB, MI, DL,
18950 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18952 // Load the old value of the high byte of the control word...
18954 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18955 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18958 // Set the high part to be round to zero...
18959 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18962 // Reload the modified control word now...
18963 addFrameReference(BuildMI(*BB, MI, DL,
18964 TII->get(X86::FLDCW16m)), CWFrameIdx);
18966 // Restore the memory image of control word to original value
18967 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18970 // Get the X86 opcode to use.
18972 switch (MI->getOpcode()) {
18973 default: llvm_unreachable("illegal opcode!");
18974 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18975 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18976 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18977 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18978 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18979 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18980 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18981 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18982 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18986 MachineOperand &Op = MI->getOperand(0);
18988 AM.BaseType = X86AddressMode::RegBase;
18989 AM.Base.Reg = Op.getReg();
18991 AM.BaseType = X86AddressMode::FrameIndexBase;
18992 AM.Base.FrameIndex = Op.getIndex();
18994 Op = MI->getOperand(1);
18996 AM.Scale = Op.getImm();
18997 Op = MI->getOperand(2);
18999 AM.IndexReg = Op.getImm();
19000 Op = MI->getOperand(3);
19001 if (Op.isGlobal()) {
19002 AM.GV = Op.getGlobal();
19004 AM.Disp = Op.getImm();
19006 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19007 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19009 // Reload the original control word now.
19010 addFrameReference(BuildMI(*BB, MI, DL,
19011 TII->get(X86::FLDCW16m)), CWFrameIdx);
19013 MI->eraseFromParent(); // The pseudo instruction is gone now.
19016 // String/text processing lowering.
19017 case X86::PCMPISTRM128REG:
19018 case X86::VPCMPISTRM128REG:
19019 case X86::PCMPISTRM128MEM:
19020 case X86::VPCMPISTRM128MEM:
19021 case X86::PCMPESTRM128REG:
19022 case X86::VPCMPESTRM128REG:
19023 case X86::PCMPESTRM128MEM:
19024 case X86::VPCMPESTRM128MEM:
19025 assert(Subtarget->hasSSE42() &&
19026 "Target must have SSE4.2 or AVX features enabled");
19027 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19029 // String/text processing lowering.
19030 case X86::PCMPISTRIREG:
19031 case X86::VPCMPISTRIREG:
19032 case X86::PCMPISTRIMEM:
19033 case X86::VPCMPISTRIMEM:
19034 case X86::PCMPESTRIREG:
19035 case X86::VPCMPESTRIREG:
19036 case X86::PCMPESTRIMEM:
19037 case X86::VPCMPESTRIMEM:
19038 assert(Subtarget->hasSSE42() &&
19039 "Target must have SSE4.2 or AVX features enabled");
19040 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19042 // Thread synchronization.
19044 return EmitMonitor(MI, BB, Subtarget);
19048 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19050 case X86::VASTART_SAVE_XMM_REGS:
19051 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19053 case X86::VAARG_64:
19054 return EmitVAARG64WithCustomInserter(MI, BB);
19056 case X86::EH_SjLj_SetJmp32:
19057 case X86::EH_SjLj_SetJmp64:
19058 return emitEHSjLjSetJmp(MI, BB);
19060 case X86::EH_SjLj_LongJmp32:
19061 case X86::EH_SjLj_LongJmp64:
19062 return emitEHSjLjLongJmp(MI, BB);
19064 case TargetOpcode::STATEPOINT:
19065 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19066 // this point in the process. We diverge later.
19067 return emitPatchPoint(MI, BB);
19069 case TargetOpcode::STACKMAP:
19070 case TargetOpcode::PATCHPOINT:
19071 return emitPatchPoint(MI, BB);
19073 case X86::VFMADDPDr213r:
19074 case X86::VFMADDPSr213r:
19075 case X86::VFMADDSDr213r:
19076 case X86::VFMADDSSr213r:
19077 case X86::VFMSUBPDr213r:
19078 case X86::VFMSUBPSr213r:
19079 case X86::VFMSUBSDr213r:
19080 case X86::VFMSUBSSr213r:
19081 case X86::VFNMADDPDr213r:
19082 case X86::VFNMADDPSr213r:
19083 case X86::VFNMADDSDr213r:
19084 case X86::VFNMADDSSr213r:
19085 case X86::VFNMSUBPDr213r:
19086 case X86::VFNMSUBPSr213r:
19087 case X86::VFNMSUBSDr213r:
19088 case X86::VFNMSUBSSr213r:
19089 case X86::VFMADDSUBPDr213r:
19090 case X86::VFMADDSUBPSr213r:
19091 case X86::VFMSUBADDPDr213r:
19092 case X86::VFMSUBADDPSr213r:
19093 case X86::VFMADDPDr213rY:
19094 case X86::VFMADDPSr213rY:
19095 case X86::VFMSUBPDr213rY:
19096 case X86::VFMSUBPSr213rY:
19097 case X86::VFNMADDPDr213rY:
19098 case X86::VFNMADDPSr213rY:
19099 case X86::VFNMSUBPDr213rY:
19100 case X86::VFNMSUBPSr213rY:
19101 case X86::VFMADDSUBPDr213rY:
19102 case X86::VFMADDSUBPSr213rY:
19103 case X86::VFMSUBADDPDr213rY:
19104 case X86::VFMSUBADDPSr213rY:
19105 return emitFMA3Instr(MI, BB);
19109 //===----------------------------------------------------------------------===//
19110 // X86 Optimization Hooks
19111 //===----------------------------------------------------------------------===//
19113 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19116 const SelectionDAG &DAG,
19117 unsigned Depth) const {
19118 unsigned BitWidth = KnownZero.getBitWidth();
19119 unsigned Opc = Op.getOpcode();
19120 assert((Opc >= ISD::BUILTIN_OP_END ||
19121 Opc == ISD::INTRINSIC_WO_CHAIN ||
19122 Opc == ISD::INTRINSIC_W_CHAIN ||
19123 Opc == ISD::INTRINSIC_VOID) &&
19124 "Should use MaskedValueIsZero if you don't know whether Op"
19125 " is a target node!");
19127 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19141 // These nodes' second result is a boolean.
19142 if (Op.getResNo() == 0)
19145 case X86ISD::SETCC:
19146 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19148 case ISD::INTRINSIC_WO_CHAIN: {
19149 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19150 unsigned NumLoBits = 0;
19153 case Intrinsic::x86_sse_movmsk_ps:
19154 case Intrinsic::x86_avx_movmsk_ps_256:
19155 case Intrinsic::x86_sse2_movmsk_pd:
19156 case Intrinsic::x86_avx_movmsk_pd_256:
19157 case Intrinsic::x86_mmx_pmovmskb:
19158 case Intrinsic::x86_sse2_pmovmskb_128:
19159 case Intrinsic::x86_avx2_pmovmskb: {
19160 // High bits of movmskp{s|d}, pmovmskb are known zero.
19162 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19163 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19164 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19165 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19166 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19167 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19168 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19169 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19171 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19180 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19182 const SelectionDAG &,
19183 unsigned Depth) const {
19184 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19185 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19186 return Op.getValueType().getScalarType().getSizeInBits();
19192 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19193 /// node is a GlobalAddress + offset.
19194 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19195 const GlobalValue* &GA,
19196 int64_t &Offset) const {
19197 if (N->getOpcode() == X86ISD::Wrapper) {
19198 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19199 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19200 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19204 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19207 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19208 /// same as extracting the high 128-bit part of 256-bit vector and then
19209 /// inserting the result into the low part of a new 256-bit vector
19210 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19211 EVT VT = SVOp->getValueType(0);
19212 unsigned NumElems = VT.getVectorNumElements();
19214 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19215 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19216 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19217 SVOp->getMaskElt(j) >= 0)
19223 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19224 /// same as extracting the low 128-bit part of 256-bit vector and then
19225 /// inserting the result into the high part of a new 256-bit vector
19226 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19227 EVT VT = SVOp->getValueType(0);
19228 unsigned NumElems = VT.getVectorNumElements();
19230 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19231 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19232 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19233 SVOp->getMaskElt(j) >= 0)
19239 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19240 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19241 TargetLowering::DAGCombinerInfo &DCI,
19242 const X86Subtarget* Subtarget) {
19244 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19245 SDValue V1 = SVOp->getOperand(0);
19246 SDValue V2 = SVOp->getOperand(1);
19247 EVT VT = SVOp->getValueType(0);
19248 unsigned NumElems = VT.getVectorNumElements();
19250 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19251 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19255 // V UNDEF BUILD_VECTOR UNDEF
19257 // CONCAT_VECTOR CONCAT_VECTOR
19260 // RESULT: V + zero extended
19262 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19263 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19264 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19267 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19270 // To match the shuffle mask, the first half of the mask should
19271 // be exactly the first vector, and all the rest a splat with the
19272 // first element of the second one.
19273 for (unsigned i = 0; i != NumElems/2; ++i)
19274 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19275 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19278 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19279 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19280 if (Ld->hasNUsesOfValue(1, 0)) {
19281 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19282 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19284 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19286 Ld->getPointerInfo(),
19287 Ld->getAlignment(),
19288 false/*isVolatile*/, true/*ReadMem*/,
19289 false/*WriteMem*/);
19291 // Make sure the newly-created LOAD is in the same position as Ld in
19292 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19293 // and update uses of Ld's output chain to use the TokenFactor.
19294 if (Ld->hasAnyUseOfValue(1)) {
19295 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19296 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19297 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19298 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19299 SDValue(ResNode.getNode(), 1));
19302 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19306 // Emit a zeroed vector and insert the desired subvector on its
19308 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19309 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19310 return DCI.CombineTo(N, InsV);
19313 //===--------------------------------------------------------------------===//
19314 // Combine some shuffles into subvector extracts and inserts:
19317 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19318 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19319 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19320 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19321 return DCI.CombineTo(N, InsV);
19324 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19325 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19326 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19327 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19328 return DCI.CombineTo(N, InsV);
19334 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19337 /// This is the leaf of the recursive combinine below. When we have found some
19338 /// chain of single-use x86 shuffle instructions and accumulated the combined
19339 /// shuffle mask represented by them, this will try to pattern match that mask
19340 /// into either a single instruction if there is a special purpose instruction
19341 /// for this operation, or into a PSHUFB instruction which is a fully general
19342 /// instruction but should only be used to replace chains over a certain depth.
19343 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19344 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19345 TargetLowering::DAGCombinerInfo &DCI,
19346 const X86Subtarget *Subtarget) {
19347 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19349 // Find the operand that enters the chain. Note that multiple uses are OK
19350 // here, we're not going to remove the operand we find.
19351 SDValue Input = Op.getOperand(0);
19352 while (Input.getOpcode() == ISD::BITCAST)
19353 Input = Input.getOperand(0);
19355 MVT VT = Input.getSimpleValueType();
19356 MVT RootVT = Root.getSimpleValueType();
19359 // Just remove no-op shuffle masks.
19360 if (Mask.size() == 1) {
19361 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19366 // Use the float domain if the operand type is a floating point type.
19367 bool FloatDomain = VT.isFloatingPoint();
19369 // For floating point shuffles, we don't have free copies in the shuffle
19370 // instructions or the ability to load as part of the instruction, so
19371 // canonicalize their shuffles to UNPCK or MOV variants.
19373 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19374 // vectors because it can have a load folded into it that UNPCK cannot. This
19375 // doesn't preclude something switching to the shorter encoding post-RA.
19377 // FIXME: Should teach these routines about AVX vector widths.
19378 if (FloatDomain && VT.getSizeInBits() == 128) {
19379 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19380 bool Lo = Mask.equals({0, 0});
19383 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19384 // is no slower than UNPCKLPD but has the option to fold the input operand
19385 // into even an unaligned memory load.
19386 if (Lo && Subtarget->hasSSE3()) {
19387 Shuffle = X86ISD::MOVDDUP;
19388 ShuffleVT = MVT::v2f64;
19390 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19391 // than the UNPCK variants.
19392 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19393 ShuffleVT = MVT::v4f32;
19395 if (Depth == 1 && Root->getOpcode() == Shuffle)
19396 return false; // Nothing to do!
19397 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19398 DCI.AddToWorklist(Op.getNode());
19399 if (Shuffle == X86ISD::MOVDDUP)
19400 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19402 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19403 DCI.AddToWorklist(Op.getNode());
19404 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19408 if (Subtarget->hasSSE3() &&
19409 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19410 bool Lo = Mask.equals({0, 0, 2, 2});
19411 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19412 MVT ShuffleVT = MVT::v4f32;
19413 if (Depth == 1 && Root->getOpcode() == Shuffle)
19414 return false; // Nothing to do!
19415 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19416 DCI.AddToWorklist(Op.getNode());
19417 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19418 DCI.AddToWorklist(Op.getNode());
19419 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19423 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19424 bool Lo = Mask.equals({0, 0, 1, 1});
19425 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19426 MVT ShuffleVT = MVT::v4f32;
19427 if (Depth == 1 && Root->getOpcode() == Shuffle)
19428 return false; // Nothing to do!
19429 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19430 DCI.AddToWorklist(Op.getNode());
19431 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19432 DCI.AddToWorklist(Op.getNode());
19433 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19439 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19440 // variants as none of these have single-instruction variants that are
19441 // superior to the UNPCK formulation.
19442 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19443 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19444 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19445 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19447 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19448 bool Lo = Mask[0] == 0;
19449 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19450 if (Depth == 1 && Root->getOpcode() == Shuffle)
19451 return false; // Nothing to do!
19453 switch (Mask.size()) {
19455 ShuffleVT = MVT::v8i16;
19458 ShuffleVT = MVT::v16i8;
19461 llvm_unreachable("Impossible mask size!");
19463 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19464 DCI.AddToWorklist(Op.getNode());
19465 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19466 DCI.AddToWorklist(Op.getNode());
19467 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19472 // Don't try to re-form single instruction chains under any circumstances now
19473 // that we've done encoding canonicalization for them.
19477 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19478 // can replace them with a single PSHUFB instruction profitably. Intel's
19479 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19480 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19481 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19482 SmallVector<SDValue, 16> PSHUFBMask;
19483 int NumBytes = VT.getSizeInBits() / 8;
19484 int Ratio = NumBytes / Mask.size();
19485 for (int i = 0; i < NumBytes; ++i) {
19486 if (Mask[i / Ratio] == SM_SentinelUndef) {
19487 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19490 int M = Mask[i / Ratio] != SM_SentinelZero
19491 ? Ratio * Mask[i / Ratio] + i % Ratio
19493 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19495 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19496 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19497 DCI.AddToWorklist(Op.getNode());
19498 SDValue PSHUFBMaskOp =
19499 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19500 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19501 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19502 DCI.AddToWorklist(Op.getNode());
19503 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19508 // Failed to find any combines.
19512 /// \brief Fully generic combining of x86 shuffle instructions.
19514 /// This should be the last combine run over the x86 shuffle instructions. Once
19515 /// they have been fully optimized, this will recursively consider all chains
19516 /// of single-use shuffle instructions, build a generic model of the cumulative
19517 /// shuffle operation, and check for simpler instructions which implement this
19518 /// operation. We use this primarily for two purposes:
19520 /// 1) Collapse generic shuffles to specialized single instructions when
19521 /// equivalent. In most cases, this is just an encoding size win, but
19522 /// sometimes we will collapse multiple generic shuffles into a single
19523 /// special-purpose shuffle.
19524 /// 2) Look for sequences of shuffle instructions with 3 or more total
19525 /// instructions, and replace them with the slightly more expensive SSSE3
19526 /// PSHUFB instruction if available. We do this as the last combining step
19527 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19528 /// a suitable short sequence of other instructions. The PHUFB will either
19529 /// use a register or have to read from memory and so is slightly (but only
19530 /// slightly) more expensive than the other shuffle instructions.
19532 /// Because this is inherently a quadratic operation (for each shuffle in
19533 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19534 /// This should never be an issue in practice as the shuffle lowering doesn't
19535 /// produce sequences of more than 8 instructions.
19537 /// FIXME: We will currently miss some cases where the redundant shuffling
19538 /// would simplify under the threshold for PSHUFB formation because of
19539 /// combine-ordering. To fix this, we should do the redundant instruction
19540 /// combining in this recursive walk.
19541 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19542 ArrayRef<int> RootMask,
19543 int Depth, bool HasPSHUFB,
19545 TargetLowering::DAGCombinerInfo &DCI,
19546 const X86Subtarget *Subtarget) {
19547 // Bound the depth of our recursive combine because this is ultimately
19548 // quadratic in nature.
19552 // Directly rip through bitcasts to find the underlying operand.
19553 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19554 Op = Op.getOperand(0);
19556 MVT VT = Op.getSimpleValueType();
19557 if (!VT.isVector())
19558 return false; // Bail if we hit a non-vector.
19560 assert(Root.getSimpleValueType().isVector() &&
19561 "Shuffles operate on vector types!");
19562 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19563 "Can only combine shuffles of the same vector register size.");
19565 if (!isTargetShuffle(Op.getOpcode()))
19567 SmallVector<int, 16> OpMask;
19569 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19570 // We only can combine unary shuffles which we can decode the mask for.
19571 if (!HaveMask || !IsUnary)
19574 assert(VT.getVectorNumElements() == OpMask.size() &&
19575 "Different mask size from vector size!");
19576 assert(((RootMask.size() > OpMask.size() &&
19577 RootMask.size() % OpMask.size() == 0) ||
19578 (OpMask.size() > RootMask.size() &&
19579 OpMask.size() % RootMask.size() == 0) ||
19580 OpMask.size() == RootMask.size()) &&
19581 "The smaller number of elements must divide the larger.");
19582 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19583 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19584 assert(((RootRatio == 1 && OpRatio == 1) ||
19585 (RootRatio == 1) != (OpRatio == 1)) &&
19586 "Must not have a ratio for both incoming and op masks!");
19588 SmallVector<int, 16> Mask;
19589 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19591 // Merge this shuffle operation's mask into our accumulated mask. Note that
19592 // this shuffle's mask will be the first applied to the input, followed by the
19593 // root mask to get us all the way to the root value arrangement. The reason
19594 // for this order is that we are recursing up the operation chain.
19595 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19596 int RootIdx = i / RootRatio;
19597 if (RootMask[RootIdx] < 0) {
19598 // This is a zero or undef lane, we're done.
19599 Mask.push_back(RootMask[RootIdx]);
19603 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19604 int OpIdx = RootMaskedIdx / OpRatio;
19605 if (OpMask[OpIdx] < 0) {
19606 // The incoming lanes are zero or undef, it doesn't matter which ones we
19608 Mask.push_back(OpMask[OpIdx]);
19612 // Ok, we have non-zero lanes, map them through.
19613 Mask.push_back(OpMask[OpIdx] * OpRatio +
19614 RootMaskedIdx % OpRatio);
19617 // See if we can recurse into the operand to combine more things.
19618 switch (Op.getOpcode()) {
19619 case X86ISD::PSHUFB:
19621 case X86ISD::PSHUFD:
19622 case X86ISD::PSHUFHW:
19623 case X86ISD::PSHUFLW:
19624 if (Op.getOperand(0).hasOneUse() &&
19625 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19626 HasPSHUFB, DAG, DCI, Subtarget))
19630 case X86ISD::UNPCKL:
19631 case X86ISD::UNPCKH:
19632 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19633 // We can't check for single use, we have to check that this shuffle is the only user.
19634 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19635 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19636 HasPSHUFB, DAG, DCI, Subtarget))
19641 // Minor canonicalization of the accumulated shuffle mask to make it easier
19642 // to match below. All this does is detect masks with squential pairs of
19643 // elements, and shrink them to the half-width mask. It does this in a loop
19644 // so it will reduce the size of the mask to the minimal width mask which
19645 // performs an equivalent shuffle.
19646 SmallVector<int, 16> WidenedMask;
19647 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19648 Mask = std::move(WidenedMask);
19649 WidenedMask.clear();
19652 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19656 /// \brief Get the PSHUF-style mask from PSHUF node.
19658 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19659 /// PSHUF-style masks that can be reused with such instructions.
19660 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19661 MVT VT = N.getSimpleValueType();
19662 SmallVector<int, 4> Mask;
19664 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19668 // If we have more than 128-bits, only the low 128-bits of shuffle mask
19669 // matter. Check that the upper masks are repeats and remove them.
19670 if (VT.getSizeInBits() > 128) {
19671 int LaneElts = 128 / VT.getScalarSizeInBits();
19673 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19674 for (int j = 0; j < LaneElts; ++j)
19675 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19676 "Mask doesn't repeat in high 128-bit lanes!");
19678 Mask.resize(LaneElts);
19681 switch (N.getOpcode()) {
19682 case X86ISD::PSHUFD:
19684 case X86ISD::PSHUFLW:
19687 case X86ISD::PSHUFHW:
19688 Mask.erase(Mask.begin(), Mask.begin() + 4);
19689 for (int &M : Mask)
19693 llvm_unreachable("No valid shuffle instruction found!");
19697 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19699 /// We walk up the chain and look for a combinable shuffle, skipping over
19700 /// shuffles that we could hoist this shuffle's transformation past without
19701 /// altering anything.
19703 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19705 TargetLowering::DAGCombinerInfo &DCI) {
19706 assert(N.getOpcode() == X86ISD::PSHUFD &&
19707 "Called with something other than an x86 128-bit half shuffle!");
19710 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19711 // of the shuffles in the chain so that we can form a fresh chain to replace
19713 SmallVector<SDValue, 8> Chain;
19714 SDValue V = N.getOperand(0);
19715 for (; V.hasOneUse(); V = V.getOperand(0)) {
19716 switch (V.getOpcode()) {
19718 return SDValue(); // Nothing combined!
19721 // Skip bitcasts as we always know the type for the target specific
19725 case X86ISD::PSHUFD:
19726 // Found another dword shuffle.
19729 case X86ISD::PSHUFLW:
19730 // Check that the low words (being shuffled) are the identity in the
19731 // dword shuffle, and the high words are self-contained.
19732 if (Mask[0] != 0 || Mask[1] != 1 ||
19733 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19736 Chain.push_back(V);
19739 case X86ISD::PSHUFHW:
19740 // Check that the high words (being shuffled) are the identity in the
19741 // dword shuffle, and the low words are self-contained.
19742 if (Mask[2] != 2 || Mask[3] != 3 ||
19743 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19746 Chain.push_back(V);
19749 case X86ISD::UNPCKL:
19750 case X86ISD::UNPCKH:
19751 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19752 // shuffle into a preceding word shuffle.
19753 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19754 V.getSimpleValueType().getScalarType() != MVT::i16)
19757 // Search for a half-shuffle which we can combine with.
19758 unsigned CombineOp =
19759 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19760 if (V.getOperand(0) != V.getOperand(1) ||
19761 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19763 Chain.push_back(V);
19764 V = V.getOperand(0);
19766 switch (V.getOpcode()) {
19768 return SDValue(); // Nothing to combine.
19770 case X86ISD::PSHUFLW:
19771 case X86ISD::PSHUFHW:
19772 if (V.getOpcode() == CombineOp)
19775 Chain.push_back(V);
19779 V = V.getOperand(0);
19783 } while (V.hasOneUse());
19786 // Break out of the loop if we break out of the switch.
19790 if (!V.hasOneUse())
19791 // We fell out of the loop without finding a viable combining instruction.
19794 // Merge this node's mask and our incoming mask.
19795 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19796 for (int &M : Mask)
19798 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19799 getV4X86ShuffleImm8ForMask(Mask, DAG));
19801 // Rebuild the chain around this new shuffle.
19802 while (!Chain.empty()) {
19803 SDValue W = Chain.pop_back_val();
19805 if (V.getValueType() != W.getOperand(0).getValueType())
19806 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19808 switch (W.getOpcode()) {
19810 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19812 case X86ISD::UNPCKL:
19813 case X86ISD::UNPCKH:
19814 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19817 case X86ISD::PSHUFD:
19818 case X86ISD::PSHUFLW:
19819 case X86ISD::PSHUFHW:
19820 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19824 if (V.getValueType() != N.getValueType())
19825 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19827 // Return the new chain to replace N.
19831 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19833 /// We walk up the chain, skipping shuffles of the other half and looking
19834 /// through shuffles which switch halves trying to find a shuffle of the same
19835 /// pair of dwords.
19836 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19838 TargetLowering::DAGCombinerInfo &DCI) {
19840 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19841 "Called with something other than an x86 128-bit half shuffle!");
19843 unsigned CombineOpcode = N.getOpcode();
19845 // Walk up a single-use chain looking for a combinable shuffle.
19846 SDValue V = N.getOperand(0);
19847 for (; V.hasOneUse(); V = V.getOperand(0)) {
19848 switch (V.getOpcode()) {
19850 return false; // Nothing combined!
19853 // Skip bitcasts as we always know the type for the target specific
19857 case X86ISD::PSHUFLW:
19858 case X86ISD::PSHUFHW:
19859 if (V.getOpcode() == CombineOpcode)
19862 // Other-half shuffles are no-ops.
19865 // Break out of the loop if we break out of the switch.
19869 if (!V.hasOneUse())
19870 // We fell out of the loop without finding a viable combining instruction.
19873 // Combine away the bottom node as its shuffle will be accumulated into
19874 // a preceding shuffle.
19875 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19877 // Record the old value.
19880 // Merge this node's mask and our incoming mask (adjusted to account for all
19881 // the pshufd instructions encountered).
19882 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19883 for (int &M : Mask)
19885 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19886 getV4X86ShuffleImm8ForMask(Mask, DAG));
19888 // Check that the shuffles didn't cancel each other out. If not, we need to
19889 // combine to the new one.
19891 // Replace the combinable shuffle with the combined one, updating all users
19892 // so that we re-evaluate the chain here.
19893 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19898 /// \brief Try to combine x86 target specific shuffles.
19899 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19900 TargetLowering::DAGCombinerInfo &DCI,
19901 const X86Subtarget *Subtarget) {
19903 MVT VT = N.getSimpleValueType();
19904 SmallVector<int, 4> Mask;
19906 switch (N.getOpcode()) {
19907 case X86ISD::PSHUFD:
19908 case X86ISD::PSHUFLW:
19909 case X86ISD::PSHUFHW:
19910 Mask = getPSHUFShuffleMask(N);
19911 assert(Mask.size() == 4);
19917 // Nuke no-op shuffles that show up after combining.
19918 if (isNoopShuffleMask(Mask))
19919 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19921 // Look for simplifications involving one or two shuffle instructions.
19922 SDValue V = N.getOperand(0);
19923 switch (N.getOpcode()) {
19926 case X86ISD::PSHUFLW:
19927 case X86ISD::PSHUFHW:
19928 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19930 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19931 return SDValue(); // We combined away this shuffle, so we're done.
19933 // See if this reduces to a PSHUFD which is no more expensive and can
19934 // combine with more operations. Note that it has to at least flip the
19935 // dwords as otherwise it would have been removed as a no-op.
19936 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19937 int DMask[] = {0, 1, 2, 3};
19938 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19939 DMask[DOffset + 0] = DOffset + 1;
19940 DMask[DOffset + 1] = DOffset + 0;
19941 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19942 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19943 DCI.AddToWorklist(V.getNode());
19944 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19945 getV4X86ShuffleImm8ForMask(DMask, DAG));
19946 DCI.AddToWorklist(V.getNode());
19947 return DAG.getNode(ISD::BITCAST, DL, VT, V);
19950 // Look for shuffle patterns which can be implemented as a single unpack.
19951 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19952 // only works when we have a PSHUFD followed by two half-shuffles.
19953 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19954 (V.getOpcode() == X86ISD::PSHUFLW ||
19955 V.getOpcode() == X86ISD::PSHUFHW) &&
19956 V.getOpcode() != N.getOpcode() &&
19958 SDValue D = V.getOperand(0);
19959 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19960 D = D.getOperand(0);
19961 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19962 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19963 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19964 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19965 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19967 for (int i = 0; i < 4; ++i) {
19968 WordMask[i + NOffset] = Mask[i] + NOffset;
19969 WordMask[i + VOffset] = VMask[i] + VOffset;
19971 // Map the word mask through the DWord mask.
19973 for (int i = 0; i < 8; ++i)
19974 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19975 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19976 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
19977 // We can replace all three shuffles with an unpack.
19978 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
19979 DCI.AddToWorklist(V.getNode());
19980 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19989 case X86ISD::PSHUFD:
19990 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19999 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20001 /// We combine this directly on the abstract vector shuffle nodes so it is
20002 /// easier to generically match. We also insert dummy vector shuffle nodes for
20003 /// the operands which explicitly discard the lanes which are unused by this
20004 /// operation to try to flow through the rest of the combiner the fact that
20005 /// they're unused.
20006 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20008 EVT VT = N->getValueType(0);
20010 // We only handle target-independent shuffles.
20011 // FIXME: It would be easy and harmless to use the target shuffle mask
20012 // extraction tool to support more.
20013 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20016 auto *SVN = cast<ShuffleVectorSDNode>(N);
20017 ArrayRef<int> Mask = SVN->getMask();
20018 SDValue V1 = N->getOperand(0);
20019 SDValue V2 = N->getOperand(1);
20021 // We require the first shuffle operand to be the SUB node, and the second to
20022 // be the ADD node.
20023 // FIXME: We should support the commuted patterns.
20024 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20027 // If there are other uses of these operations we can't fold them.
20028 if (!V1->hasOneUse() || !V2->hasOneUse())
20031 // Ensure that both operations have the same operands. Note that we can
20032 // commute the FADD operands.
20033 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20034 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20035 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20038 // We're looking for blends between FADD and FSUB nodes. We insist on these
20039 // nodes being lined up in a specific expected pattern.
20040 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20041 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20042 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20045 // Only specific types are legal at this point, assert so we notice if and
20046 // when these change.
20047 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20048 VT == MVT::v4f64) &&
20049 "Unknown vector type encountered!");
20051 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20054 /// PerformShuffleCombine - Performs several different shuffle combines.
20055 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20056 TargetLowering::DAGCombinerInfo &DCI,
20057 const X86Subtarget *Subtarget) {
20059 SDValue N0 = N->getOperand(0);
20060 SDValue N1 = N->getOperand(1);
20061 EVT VT = N->getValueType(0);
20063 // Don't create instructions with illegal types after legalize types has run.
20064 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20065 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20068 // If we have legalized the vector types, look for blends of FADD and FSUB
20069 // nodes that we can fuse into an ADDSUB node.
20070 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20071 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20074 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20075 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20076 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20077 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20079 // During Type Legalization, when promoting illegal vector types,
20080 // the backend might introduce new shuffle dag nodes and bitcasts.
20082 // This code performs the following transformation:
20083 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20084 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20086 // We do this only if both the bitcast and the BINOP dag nodes have
20087 // one use. Also, perform this transformation only if the new binary
20088 // operation is legal. This is to avoid introducing dag nodes that
20089 // potentially need to be further expanded (or custom lowered) into a
20090 // less optimal sequence of dag nodes.
20091 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20092 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20093 N0.getOpcode() == ISD::BITCAST) {
20094 SDValue BC0 = N0.getOperand(0);
20095 EVT SVT = BC0.getValueType();
20096 unsigned Opcode = BC0.getOpcode();
20097 unsigned NumElts = VT.getVectorNumElements();
20099 if (BC0.hasOneUse() && SVT.isVector() &&
20100 SVT.getVectorNumElements() * 2 == NumElts &&
20101 TLI.isOperationLegal(Opcode, VT)) {
20102 bool CanFold = false;
20114 unsigned SVTNumElts = SVT.getVectorNumElements();
20115 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20116 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20117 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20118 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20119 CanFold = SVOp->getMaskElt(i) < 0;
20122 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20123 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20124 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20125 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20130 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20131 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20132 // consecutive, non-overlapping, and in the right order.
20133 SmallVector<SDValue, 16> Elts;
20134 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20135 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20137 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20141 if (isTargetShuffle(N->getOpcode())) {
20143 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20144 if (Shuffle.getNode())
20147 // Try recursively combining arbitrary sequences of x86 shuffle
20148 // instructions into higher-order shuffles. We do this after combining
20149 // specific PSHUF instruction sequences into their minimal form so that we
20150 // can evaluate how many specialized shuffle instructions are involved in
20151 // a particular chain.
20152 SmallVector<int, 1> NonceMask; // Just a placeholder.
20153 NonceMask.push_back(0);
20154 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20155 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20157 return SDValue(); // This routine will use CombineTo to replace N.
20163 /// PerformTruncateCombine - Converts truncate operation to
20164 /// a sequence of vector shuffle operations.
20165 /// It is possible when we truncate 256-bit vector to 128-bit vector
20166 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20167 TargetLowering::DAGCombinerInfo &DCI,
20168 const X86Subtarget *Subtarget) {
20172 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20173 /// specific shuffle of a load can be folded into a single element load.
20174 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20175 /// shuffles have been custom lowered so we need to handle those here.
20176 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20177 TargetLowering::DAGCombinerInfo &DCI) {
20178 if (DCI.isBeforeLegalizeOps())
20181 SDValue InVec = N->getOperand(0);
20182 SDValue EltNo = N->getOperand(1);
20184 if (!isa<ConstantSDNode>(EltNo))
20187 EVT OriginalVT = InVec.getValueType();
20189 if (InVec.getOpcode() == ISD::BITCAST) {
20190 // Don't duplicate a load with other uses.
20191 if (!InVec.hasOneUse())
20193 EVT BCVT = InVec.getOperand(0).getValueType();
20194 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20196 InVec = InVec.getOperand(0);
20199 EVT CurrentVT = InVec.getValueType();
20201 if (!isTargetShuffle(InVec.getOpcode()))
20204 // Don't duplicate a load with other uses.
20205 if (!InVec.hasOneUse())
20208 SmallVector<int, 16> ShuffleMask;
20210 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20211 ShuffleMask, UnaryShuffle))
20214 // Select the input vector, guarding against out of range extract vector.
20215 unsigned NumElems = CurrentVT.getVectorNumElements();
20216 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20217 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20218 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20219 : InVec.getOperand(1);
20221 // If inputs to shuffle are the same for both ops, then allow 2 uses
20222 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20223 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20225 if (LdNode.getOpcode() == ISD::BITCAST) {
20226 // Don't duplicate a load with other uses.
20227 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20230 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20231 LdNode = LdNode.getOperand(0);
20234 if (!ISD::isNormalLoad(LdNode.getNode()))
20237 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20239 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20242 EVT EltVT = N->getValueType(0);
20243 // If there's a bitcast before the shuffle, check if the load type and
20244 // alignment is valid.
20245 unsigned Align = LN0->getAlignment();
20246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20247 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20248 EltVT.getTypeForEVT(*DAG.getContext()));
20250 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20253 // All checks match so transform back to vector_shuffle so that DAG combiner
20254 // can finish the job
20257 // Create shuffle node taking into account the case that its a unary shuffle
20258 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20259 : InVec.getOperand(1);
20260 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20261 InVec.getOperand(0), Shuffle,
20263 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20264 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20268 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20269 /// special and don't usually play with other vector types, it's better to
20270 /// handle them early to be sure we emit efficient code by avoiding
20271 /// store-load conversions.
20272 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20273 if (N->getValueType(0) != MVT::x86mmx ||
20274 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20275 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20278 SDValue V = N->getOperand(0);
20279 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20280 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20281 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20282 N->getValueType(0), V.getOperand(0));
20287 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20288 /// generation and convert it from being a bunch of shuffles and extracts
20289 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20290 /// storing the value and loading scalars back, while for x64 we should
20291 /// use 64-bit extracts and shifts.
20292 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20293 TargetLowering::DAGCombinerInfo &DCI) {
20294 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20295 if (NewOp.getNode())
20298 SDValue InputVector = N->getOperand(0);
20300 // Detect mmx to i32 conversion through a v2i32 elt extract.
20301 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20302 N->getValueType(0) == MVT::i32 &&
20303 InputVector.getValueType() == MVT::v2i32) {
20305 // The bitcast source is a direct mmx result.
20306 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20307 if (MMXSrc.getValueType() == MVT::x86mmx)
20308 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20309 N->getValueType(0),
20310 InputVector.getNode()->getOperand(0));
20312 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20313 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20314 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20315 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20316 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20317 MMXSrcOp.getValueType() == MVT::v1i64 &&
20318 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20319 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20320 N->getValueType(0),
20321 MMXSrcOp.getOperand(0));
20324 // Only operate on vectors of 4 elements, where the alternative shuffling
20325 // gets to be more expensive.
20326 if (InputVector.getValueType() != MVT::v4i32)
20329 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20330 // single use which is a sign-extend or zero-extend, and all elements are
20332 SmallVector<SDNode *, 4> Uses;
20333 unsigned ExtractedElements = 0;
20334 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20335 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20336 if (UI.getUse().getResNo() != InputVector.getResNo())
20339 SDNode *Extract = *UI;
20340 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20343 if (Extract->getValueType(0) != MVT::i32)
20345 if (!Extract->hasOneUse())
20347 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20348 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20350 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20353 // Record which element was extracted.
20354 ExtractedElements |=
20355 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20357 Uses.push_back(Extract);
20360 // If not all the elements were used, this may not be worthwhile.
20361 if (ExtractedElements != 15)
20364 // Ok, we've now decided to do the transformation.
20365 // If 64-bit shifts are legal, use the extract-shift sequence,
20366 // otherwise bounce the vector off the cache.
20367 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20369 SDLoc dl(InputVector);
20371 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20372 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20373 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20374 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20375 DAG.getConstant(0, VecIdxTy));
20376 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20377 DAG.getConstant(1, VecIdxTy));
20379 SDValue ShAmt = DAG.getConstant(32,
20380 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20381 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20382 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20383 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20384 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20385 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20386 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20388 // Store the value to a temporary stack slot.
20389 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20390 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20391 MachinePointerInfo(), false, false, 0);
20393 EVT ElementType = InputVector.getValueType().getVectorElementType();
20394 unsigned EltSize = ElementType.getSizeInBits() / 8;
20396 // Replace each use (extract) with a load of the appropriate element.
20397 for (unsigned i = 0; i < 4; ++i) {
20398 uint64_t Offset = EltSize * i;
20399 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20401 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20402 StackPtr, OffsetVal);
20404 // Load the scalar.
20405 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20406 ScalarAddr, MachinePointerInfo(),
20407 false, false, false, 0);
20412 // Replace the extracts
20413 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20414 UE = Uses.end(); UI != UE; ++UI) {
20415 SDNode *Extract = *UI;
20417 SDValue Idx = Extract->getOperand(1);
20418 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20419 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20422 // The replacement was made in place; don't return anything.
20426 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20427 static std::pair<unsigned, bool>
20428 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20429 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20430 if (!VT.isVector())
20431 return std::make_pair(0, false);
20433 bool NeedSplit = false;
20434 switch (VT.getSimpleVT().SimpleTy) {
20435 default: return std::make_pair(0, false);
20438 if (!Subtarget->hasVLX())
20439 return std::make_pair(0, false);
20443 if (!Subtarget->hasBWI())
20444 return std::make_pair(0, false);
20448 if (!Subtarget->hasAVX512())
20449 return std::make_pair(0, false);
20454 if (!Subtarget->hasAVX2())
20456 if (!Subtarget->hasAVX())
20457 return std::make_pair(0, false);
20462 if (!Subtarget->hasSSE2())
20463 return std::make_pair(0, false);
20466 // SSE2 has only a small subset of the operations.
20467 bool hasUnsigned = Subtarget->hasSSE41() ||
20468 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20469 bool hasSigned = Subtarget->hasSSE41() ||
20470 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20472 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20475 // Check for x CC y ? x : y.
20476 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20477 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20482 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20485 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20488 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20491 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20493 // Check for x CC y ? y : x -- a min/max with reversed arms.
20494 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20495 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20500 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20503 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20506 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20509 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20513 return std::make_pair(Opc, NeedSplit);
20517 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20518 const X86Subtarget *Subtarget) {
20520 SDValue Cond = N->getOperand(0);
20521 SDValue LHS = N->getOperand(1);
20522 SDValue RHS = N->getOperand(2);
20524 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20525 SDValue CondSrc = Cond->getOperand(0);
20526 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20527 Cond = CondSrc->getOperand(0);
20530 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20533 // A vselect where all conditions and data are constants can be optimized into
20534 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20535 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20536 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20539 unsigned MaskValue = 0;
20540 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20543 MVT VT = N->getSimpleValueType(0);
20544 unsigned NumElems = VT.getVectorNumElements();
20545 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20546 for (unsigned i = 0; i < NumElems; ++i) {
20547 // Be sure we emit undef where we can.
20548 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20549 ShuffleMask[i] = -1;
20551 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20554 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20555 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20557 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20560 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20562 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20563 TargetLowering::DAGCombinerInfo &DCI,
20564 const X86Subtarget *Subtarget) {
20566 SDValue Cond = N->getOperand(0);
20567 // Get the LHS/RHS of the select.
20568 SDValue LHS = N->getOperand(1);
20569 SDValue RHS = N->getOperand(2);
20570 EVT VT = LHS.getValueType();
20571 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20573 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20574 // instructions match the semantics of the common C idiom x<y?x:y but not
20575 // x<=y?x:y, because of how they handle negative zero (which can be
20576 // ignored in unsafe-math mode).
20577 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20578 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20579 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20580 (Subtarget->hasSSE2() ||
20581 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20582 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20584 unsigned Opcode = 0;
20585 // Check for x CC y ? x : y.
20586 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20587 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20591 // Converting this to a min would handle NaNs incorrectly, and swapping
20592 // the operands would cause it to handle comparisons between positive
20593 // and negative zero incorrectly.
20594 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20595 if (!DAG.getTarget().Options.UnsafeFPMath &&
20596 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20598 std::swap(LHS, RHS);
20600 Opcode = X86ISD::FMIN;
20603 // Converting this to a min would handle comparisons between positive
20604 // and negative zero incorrectly.
20605 if (!DAG.getTarget().Options.UnsafeFPMath &&
20606 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20608 Opcode = X86ISD::FMIN;
20611 // Converting this to a min would handle both negative zeros and NaNs
20612 // incorrectly, but we can swap the operands to fix both.
20613 std::swap(LHS, RHS);
20617 Opcode = X86ISD::FMIN;
20621 // Converting this to a max would handle comparisons between positive
20622 // and negative zero incorrectly.
20623 if (!DAG.getTarget().Options.UnsafeFPMath &&
20624 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20626 Opcode = X86ISD::FMAX;
20629 // Converting this to a max would handle NaNs incorrectly, and swapping
20630 // the operands would cause it to handle comparisons between positive
20631 // and negative zero incorrectly.
20632 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20633 if (!DAG.getTarget().Options.UnsafeFPMath &&
20634 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20636 std::swap(LHS, RHS);
20638 Opcode = X86ISD::FMAX;
20641 // Converting this to a max would handle both negative zeros and NaNs
20642 // incorrectly, but we can swap the operands to fix both.
20643 std::swap(LHS, RHS);
20647 Opcode = X86ISD::FMAX;
20650 // Check for x CC y ? y : x -- a min/max with reversed arms.
20651 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20652 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20656 // Converting this to a min would handle comparisons between positive
20657 // and negative zero incorrectly, and swapping the operands would
20658 // cause it to handle NaNs incorrectly.
20659 if (!DAG.getTarget().Options.UnsafeFPMath &&
20660 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20661 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20663 std::swap(LHS, RHS);
20665 Opcode = X86ISD::FMIN;
20668 // Converting this to a min would handle NaNs incorrectly.
20669 if (!DAG.getTarget().Options.UnsafeFPMath &&
20670 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20672 Opcode = X86ISD::FMIN;
20675 // Converting this to a min would handle both negative zeros and NaNs
20676 // incorrectly, but we can swap the operands to fix both.
20677 std::swap(LHS, RHS);
20681 Opcode = X86ISD::FMIN;
20685 // Converting this to a max would handle NaNs incorrectly.
20686 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20688 Opcode = X86ISD::FMAX;
20691 // Converting this to a max would handle comparisons between positive
20692 // and negative zero incorrectly, and swapping the operands would
20693 // cause it to handle NaNs incorrectly.
20694 if (!DAG.getTarget().Options.UnsafeFPMath &&
20695 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20696 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20698 std::swap(LHS, RHS);
20700 Opcode = X86ISD::FMAX;
20703 // Converting this to a max would handle both negative zeros and NaNs
20704 // incorrectly, but we can swap the operands to fix both.
20705 std::swap(LHS, RHS);
20709 Opcode = X86ISD::FMAX;
20715 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20718 EVT CondVT = Cond.getValueType();
20719 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20720 CondVT.getVectorElementType() == MVT::i1) {
20721 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20722 // lowering on KNL. In this case we convert it to
20723 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20724 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20725 // Since SKX these selects have a proper lowering.
20726 EVT OpVT = LHS.getValueType();
20727 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20728 (OpVT.getVectorElementType() == MVT::i8 ||
20729 OpVT.getVectorElementType() == MVT::i16) &&
20730 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20731 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20732 DCI.AddToWorklist(Cond.getNode());
20733 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20736 // If this is a select between two integer constants, try to do some
20738 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20739 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20740 // Don't do this for crazy integer types.
20741 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20742 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20743 // so that TrueC (the true value) is larger than FalseC.
20744 bool NeedsCondInvert = false;
20746 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20747 // Efficiently invertible.
20748 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20749 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20750 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20751 NeedsCondInvert = true;
20752 std::swap(TrueC, FalseC);
20755 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20756 if (FalseC->getAPIntValue() == 0 &&
20757 TrueC->getAPIntValue().isPowerOf2()) {
20758 if (NeedsCondInvert) // Invert the condition if needed.
20759 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20760 DAG.getConstant(1, Cond.getValueType()));
20762 // Zero extend the condition if needed.
20763 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20765 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20766 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20767 DAG.getConstant(ShAmt, MVT::i8));
20770 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20771 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20772 if (NeedsCondInvert) // Invert the condition if needed.
20773 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20774 DAG.getConstant(1, Cond.getValueType()));
20776 // Zero extend the condition if needed.
20777 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20778 FalseC->getValueType(0), Cond);
20779 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20780 SDValue(FalseC, 0));
20783 // Optimize cases that will turn into an LEA instruction. This requires
20784 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20785 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20786 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20787 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20789 bool isFastMultiplier = false;
20791 switch ((unsigned char)Diff) {
20793 case 1: // result = add base, cond
20794 case 2: // result = lea base( , cond*2)
20795 case 3: // result = lea base(cond, cond*2)
20796 case 4: // result = lea base( , cond*4)
20797 case 5: // result = lea base(cond, cond*4)
20798 case 8: // result = lea base( , cond*8)
20799 case 9: // result = lea base(cond, cond*8)
20800 isFastMultiplier = true;
20805 if (isFastMultiplier) {
20806 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20807 if (NeedsCondInvert) // Invert the condition if needed.
20808 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20809 DAG.getConstant(1, Cond.getValueType()));
20811 // Zero extend the condition if needed.
20812 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20814 // Scale the condition by the difference.
20816 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20817 DAG.getConstant(Diff, Cond.getValueType()));
20819 // Add the base if non-zero.
20820 if (FalseC->getAPIntValue() != 0)
20821 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20822 SDValue(FalseC, 0));
20829 // Canonicalize max and min:
20830 // (x > y) ? x : y -> (x >= y) ? x : y
20831 // (x < y) ? x : y -> (x <= y) ? x : y
20832 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20833 // the need for an extra compare
20834 // against zero. e.g.
20835 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20837 // testl %edi, %edi
20839 // cmovgl %edi, %eax
20843 // cmovsl %eax, %edi
20844 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20845 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20846 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20847 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20852 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20853 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20854 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20855 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20860 // Early exit check
20861 if (!TLI.isTypeLegal(VT))
20864 // Match VSELECTs into subs with unsigned saturation.
20865 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20866 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20867 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20868 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20869 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20871 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20872 // left side invert the predicate to simplify logic below.
20874 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20876 CC = ISD::getSetCCInverse(CC, true);
20877 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20881 if (Other.getNode() && Other->getNumOperands() == 2 &&
20882 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20883 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20884 SDValue CondRHS = Cond->getOperand(1);
20886 // Look for a general sub with unsigned saturation first.
20887 // x >= y ? x-y : 0 --> subus x, y
20888 // x > y ? x-y : 0 --> subus x, y
20889 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20890 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20891 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20893 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20894 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20895 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20896 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20897 // If the RHS is a constant we have to reverse the const
20898 // canonicalization.
20899 // x > C-1 ? x+-C : 0 --> subus x, C
20900 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20901 CondRHSConst->getAPIntValue() ==
20902 (-OpRHSConst->getAPIntValue() - 1))
20903 return DAG.getNode(
20904 X86ISD::SUBUS, DL, VT, OpLHS,
20905 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20907 // Another special case: If C was a sign bit, the sub has been
20908 // canonicalized into a xor.
20909 // FIXME: Would it be better to use computeKnownBits to determine
20910 // whether it's safe to decanonicalize the xor?
20911 // x s< 0 ? x^C : 0 --> subus x, C
20912 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20913 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20914 OpRHSConst->getAPIntValue().isSignBit())
20915 // Note that we have to rebuild the RHS constant here to ensure we
20916 // don't rely on particular values of undef lanes.
20917 return DAG.getNode(
20918 X86ISD::SUBUS, DL, VT, OpLHS,
20919 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20924 // Try to match a min/max vector operation.
20925 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20926 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20927 unsigned Opc = ret.first;
20928 bool NeedSplit = ret.second;
20930 if (Opc && NeedSplit) {
20931 unsigned NumElems = VT.getVectorNumElements();
20932 // Extract the LHS vectors
20933 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20934 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20936 // Extract the RHS vectors
20937 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20938 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20940 // Create min/max for each subvector
20941 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20942 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20944 // Merge the result
20945 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20947 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20950 // Simplify vector selection if condition value type matches vselect
20952 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20953 assert(Cond.getValueType().isVector() &&
20954 "vector select expects a vector selector!");
20956 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20957 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20959 // Try invert the condition if true value is not all 1s and false value
20961 if (!TValIsAllOnes && !FValIsAllZeros &&
20962 // Check if the selector will be produced by CMPP*/PCMP*
20963 Cond.getOpcode() == ISD::SETCC &&
20964 // Check if SETCC has already been promoted
20965 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20966 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20967 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20969 if (TValIsAllZeros || FValIsAllOnes) {
20970 SDValue CC = Cond.getOperand(2);
20971 ISD::CondCode NewCC =
20972 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20973 Cond.getOperand(0).getValueType().isInteger());
20974 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20975 std::swap(LHS, RHS);
20976 TValIsAllOnes = FValIsAllOnes;
20977 FValIsAllZeros = TValIsAllZeros;
20981 if (TValIsAllOnes || FValIsAllZeros) {
20984 if (TValIsAllOnes && FValIsAllZeros)
20986 else if (TValIsAllOnes)
20987 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20988 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20989 else if (FValIsAllZeros)
20990 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20991 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20993 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20997 // We should generate an X86ISD::BLENDI from a vselect if its argument
20998 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20999 // constants. This specific pattern gets generated when we split a
21000 // selector for a 512 bit vector in a machine without AVX512 (but with
21001 // 256-bit vectors), during legalization:
21003 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21005 // Iff we find this pattern and the build_vectors are built from
21006 // constants, we translate the vselect into a shuffle_vector that we
21007 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21008 if ((N->getOpcode() == ISD::VSELECT ||
21009 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21010 !DCI.isBeforeLegalize()) {
21011 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21012 if (Shuffle.getNode())
21016 // If this is a *dynamic* select (non-constant condition) and we can match
21017 // this node with one of the variable blend instructions, restructure the
21018 // condition so that the blends can use the high bit of each element and use
21019 // SimplifyDemandedBits to simplify the condition operand.
21020 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21021 !DCI.isBeforeLegalize() &&
21022 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21023 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21025 // Don't optimize vector selects that map to mask-registers.
21029 // We can only handle the cases where VSELECT is directly legal on the
21030 // subtarget. We custom lower VSELECT nodes with constant conditions and
21031 // this makes it hard to see whether a dynamic VSELECT will correctly
21032 // lower, so we both check the operation's status and explicitly handle the
21033 // cases where a *dynamic* blend will fail even though a constant-condition
21034 // blend could be custom lowered.
21035 // FIXME: We should find a better way to handle this class of problems.
21036 // Potentially, we should combine constant-condition vselect nodes
21037 // pre-legalization into shuffles and not mark as many types as custom
21039 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21041 // FIXME: We don't support i16-element blends currently. We could and
21042 // should support them by making *all* the bits in the condition be set
21043 // rather than just the high bit and using an i8-element blend.
21044 if (VT.getScalarType() == MVT::i16)
21046 // Dynamic blending was only available from SSE4.1 onward.
21047 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21049 // Byte blends are only available in AVX2
21050 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21051 !Subtarget->hasAVX2())
21054 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21055 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21057 APInt KnownZero, KnownOne;
21058 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21059 DCI.isBeforeLegalizeOps());
21060 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21061 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21063 // If we changed the computation somewhere in the DAG, this change
21064 // will affect all users of Cond.
21065 // Make sure it is fine and update all the nodes so that we do not
21066 // use the generic VSELECT anymore. Otherwise, we may perform
21067 // wrong optimizations as we messed up with the actual expectation
21068 // for the vector boolean values.
21069 if (Cond != TLO.Old) {
21070 // Check all uses of that condition operand to check whether it will be
21071 // consumed by non-BLEND instructions, which may depend on all bits are
21073 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21075 if (I->getOpcode() != ISD::VSELECT)
21076 // TODO: Add other opcodes eventually lowered into BLEND.
21079 // Update all the users of the condition, before committing the change,
21080 // so that the VSELECT optimizations that expect the correct vector
21081 // boolean value will not be triggered.
21082 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21084 DAG.ReplaceAllUsesOfValueWith(
21086 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21087 Cond, I->getOperand(1), I->getOperand(2)));
21088 DCI.CommitTargetLoweringOpt(TLO);
21091 // At this point, only Cond is changed. Change the condition
21092 // just for N to keep the opportunity to optimize all other
21093 // users their own way.
21094 DAG.ReplaceAllUsesOfValueWith(
21096 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21097 TLO.New, N->getOperand(1), N->getOperand(2)));
21105 // Check whether a boolean test is testing a boolean value generated by
21106 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21109 // Simplify the following patterns:
21110 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21111 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21112 // to (Op EFLAGS Cond)
21114 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21115 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21116 // to (Op EFLAGS !Cond)
21118 // where Op could be BRCOND or CMOV.
21120 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21121 // Quit if not CMP and SUB with its value result used.
21122 if (Cmp.getOpcode() != X86ISD::CMP &&
21123 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21126 // Quit if not used as a boolean value.
21127 if (CC != X86::COND_E && CC != X86::COND_NE)
21130 // Check CMP operands. One of them should be 0 or 1 and the other should be
21131 // an SetCC or extended from it.
21132 SDValue Op1 = Cmp.getOperand(0);
21133 SDValue Op2 = Cmp.getOperand(1);
21136 const ConstantSDNode* C = nullptr;
21137 bool needOppositeCond = (CC == X86::COND_E);
21138 bool checkAgainstTrue = false; // Is it a comparison against 1?
21140 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21142 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21144 else // Quit if all operands are not constants.
21147 if (C->getZExtValue() == 1) {
21148 needOppositeCond = !needOppositeCond;
21149 checkAgainstTrue = true;
21150 } else if (C->getZExtValue() != 0)
21151 // Quit if the constant is neither 0 or 1.
21154 bool truncatedToBoolWithAnd = false;
21155 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21156 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21157 SetCC.getOpcode() == ISD::TRUNCATE ||
21158 SetCC.getOpcode() == ISD::AND) {
21159 if (SetCC.getOpcode() == ISD::AND) {
21161 ConstantSDNode *CS;
21162 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21163 CS->getZExtValue() == 1)
21165 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21166 CS->getZExtValue() == 1)
21170 SetCC = SetCC.getOperand(OpIdx);
21171 truncatedToBoolWithAnd = true;
21173 SetCC = SetCC.getOperand(0);
21176 switch (SetCC.getOpcode()) {
21177 case X86ISD::SETCC_CARRY:
21178 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21179 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21180 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21181 // truncated to i1 using 'and'.
21182 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21184 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21185 "Invalid use of SETCC_CARRY!");
21187 case X86ISD::SETCC:
21188 // Set the condition code or opposite one if necessary.
21189 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21190 if (needOppositeCond)
21191 CC = X86::GetOppositeBranchCondition(CC);
21192 return SetCC.getOperand(1);
21193 case X86ISD::CMOV: {
21194 // Check whether false/true value has canonical one, i.e. 0 or 1.
21195 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21196 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21197 // Quit if true value is not a constant.
21200 // Quit if false value is not a constant.
21202 SDValue Op = SetCC.getOperand(0);
21203 // Skip 'zext' or 'trunc' node.
21204 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21205 Op.getOpcode() == ISD::TRUNCATE)
21206 Op = Op.getOperand(0);
21207 // A special case for rdrand/rdseed, where 0 is set if false cond is
21209 if ((Op.getOpcode() != X86ISD::RDRAND &&
21210 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21213 // Quit if false value is not the constant 0 or 1.
21214 bool FValIsFalse = true;
21215 if (FVal && FVal->getZExtValue() != 0) {
21216 if (FVal->getZExtValue() != 1)
21218 // If FVal is 1, opposite cond is needed.
21219 needOppositeCond = !needOppositeCond;
21220 FValIsFalse = false;
21222 // Quit if TVal is not the constant opposite of FVal.
21223 if (FValIsFalse && TVal->getZExtValue() != 1)
21225 if (!FValIsFalse && TVal->getZExtValue() != 0)
21227 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21228 if (needOppositeCond)
21229 CC = X86::GetOppositeBranchCondition(CC);
21230 return SetCC.getOperand(3);
21237 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21239 /// (X86or (X86setcc) (X86setcc))
21240 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21241 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21242 X86::CondCode &CC1, SDValue &Flags,
21244 if (Cond->getOpcode() == X86ISD::CMP) {
21245 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21246 if (!CondOp1C || !CondOp1C->isNullValue())
21249 Cond = Cond->getOperand(0);
21254 SDValue SetCC0, SetCC1;
21255 switch (Cond->getOpcode()) {
21256 default: return false;
21263 SetCC0 = Cond->getOperand(0);
21264 SetCC1 = Cond->getOperand(1);
21268 // Make sure we have SETCC nodes, using the same flags value.
21269 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21270 SetCC1.getOpcode() != X86ISD::SETCC ||
21271 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21274 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21275 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21276 Flags = SetCC0->getOperand(1);
21280 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21281 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21282 TargetLowering::DAGCombinerInfo &DCI,
21283 const X86Subtarget *Subtarget) {
21286 // If the flag operand isn't dead, don't touch this CMOV.
21287 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21290 SDValue FalseOp = N->getOperand(0);
21291 SDValue TrueOp = N->getOperand(1);
21292 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21293 SDValue Cond = N->getOperand(3);
21295 if (CC == X86::COND_E || CC == X86::COND_NE) {
21296 switch (Cond.getOpcode()) {
21300 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21301 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21302 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21308 Flags = checkBoolTestSetCCCombine(Cond, CC);
21309 if (Flags.getNode() &&
21310 // Extra check as FCMOV only supports a subset of X86 cond.
21311 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21312 SDValue Ops[] = { FalseOp, TrueOp,
21313 DAG.getConstant(CC, MVT::i8), Flags };
21314 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21317 // If this is a select between two integer constants, try to do some
21318 // optimizations. Note that the operands are ordered the opposite of SELECT
21320 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21321 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21322 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21323 // larger than FalseC (the false value).
21324 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21325 CC = X86::GetOppositeBranchCondition(CC);
21326 std::swap(TrueC, FalseC);
21327 std::swap(TrueOp, FalseOp);
21330 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21331 // This is efficient for any integer data type (including i8/i16) and
21333 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21334 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21335 DAG.getConstant(CC, MVT::i8), Cond);
21337 // Zero extend the condition if needed.
21338 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21340 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21341 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21342 DAG.getConstant(ShAmt, MVT::i8));
21343 if (N->getNumValues() == 2) // Dead flag value?
21344 return DCI.CombineTo(N, Cond, SDValue());
21348 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21349 // for any integer data type, including i8/i16.
21350 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21351 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21352 DAG.getConstant(CC, MVT::i8), Cond);
21354 // Zero extend the condition if needed.
21355 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21356 FalseC->getValueType(0), Cond);
21357 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21358 SDValue(FalseC, 0));
21360 if (N->getNumValues() == 2) // Dead flag value?
21361 return DCI.CombineTo(N, Cond, SDValue());
21365 // Optimize cases that will turn into an LEA instruction. This requires
21366 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21367 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21368 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21369 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21371 bool isFastMultiplier = false;
21373 switch ((unsigned char)Diff) {
21375 case 1: // result = add base, cond
21376 case 2: // result = lea base( , cond*2)
21377 case 3: // result = lea base(cond, cond*2)
21378 case 4: // result = lea base( , cond*4)
21379 case 5: // result = lea base(cond, cond*4)
21380 case 8: // result = lea base( , cond*8)
21381 case 9: // result = lea base(cond, cond*8)
21382 isFastMultiplier = true;
21387 if (isFastMultiplier) {
21388 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21389 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21390 DAG.getConstant(CC, MVT::i8), Cond);
21391 // Zero extend the condition if needed.
21392 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21394 // Scale the condition by the difference.
21396 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21397 DAG.getConstant(Diff, Cond.getValueType()));
21399 // Add the base if non-zero.
21400 if (FalseC->getAPIntValue() != 0)
21401 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21402 SDValue(FalseC, 0));
21403 if (N->getNumValues() == 2) // Dead flag value?
21404 return DCI.CombineTo(N, Cond, SDValue());
21411 // Handle these cases:
21412 // (select (x != c), e, c) -> select (x != c), e, x),
21413 // (select (x == c), c, e) -> select (x == c), x, e)
21414 // where the c is an integer constant, and the "select" is the combination
21415 // of CMOV and CMP.
21417 // The rationale for this change is that the conditional-move from a constant
21418 // needs two instructions, however, conditional-move from a register needs
21419 // only one instruction.
21421 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21422 // some instruction-combining opportunities. This opt needs to be
21423 // postponed as late as possible.
21425 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21426 // the DCI.xxxx conditions are provided to postpone the optimization as
21427 // late as possible.
21429 ConstantSDNode *CmpAgainst = nullptr;
21430 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21431 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21432 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21434 if (CC == X86::COND_NE &&
21435 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21436 CC = X86::GetOppositeBranchCondition(CC);
21437 std::swap(TrueOp, FalseOp);
21440 if (CC == X86::COND_E &&
21441 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21442 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21443 DAG.getConstant(CC, MVT::i8), Cond };
21444 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21449 // Fold and/or of setcc's to double CMOV:
21450 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21451 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21453 // This combine lets us generate:
21454 // cmovcc1 (jcc1 if we don't have CMOV)
21460 // cmovne (jne if we don't have CMOV)
21461 // When we can't use the CMOV instruction, it might increase branch
21463 // When we can use CMOV, or when there is no mispredict, this improves
21464 // throughput and reduces register pressure.
21466 if (CC == X86::COND_NE) {
21468 X86::CondCode CC0, CC1;
21470 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21472 std::swap(FalseOp, TrueOp);
21473 CC0 = X86::GetOppositeBranchCondition(CC0);
21474 CC1 = X86::GetOppositeBranchCondition(CC1);
21477 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21479 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21480 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21481 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21482 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21490 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21491 const X86Subtarget *Subtarget) {
21492 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21494 default: return SDValue();
21495 // SSE/AVX/AVX2 blend intrinsics.
21496 case Intrinsic::x86_avx2_pblendvb:
21497 // Don't try to simplify this intrinsic if we don't have AVX2.
21498 if (!Subtarget->hasAVX2())
21501 case Intrinsic::x86_avx_blendv_pd_256:
21502 case Intrinsic::x86_avx_blendv_ps_256:
21503 // Don't try to simplify this intrinsic if we don't have AVX.
21504 if (!Subtarget->hasAVX())
21507 case Intrinsic::x86_sse41_blendvps:
21508 case Intrinsic::x86_sse41_blendvpd:
21509 case Intrinsic::x86_sse41_pblendvb: {
21510 SDValue Op0 = N->getOperand(1);
21511 SDValue Op1 = N->getOperand(2);
21512 SDValue Mask = N->getOperand(3);
21514 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21515 if (!Subtarget->hasSSE41())
21518 // fold (blend A, A, Mask) -> A
21521 // fold (blend A, B, allZeros) -> A
21522 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21524 // fold (blend A, B, allOnes) -> B
21525 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21528 // Simplify the case where the mask is a constant i32 value.
21529 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21530 if (C->isNullValue())
21532 if (C->isAllOnesValue())
21539 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21540 case Intrinsic::x86_sse2_psrai_w:
21541 case Intrinsic::x86_sse2_psrai_d:
21542 case Intrinsic::x86_avx2_psrai_w:
21543 case Intrinsic::x86_avx2_psrai_d:
21544 case Intrinsic::x86_sse2_psra_w:
21545 case Intrinsic::x86_sse2_psra_d:
21546 case Intrinsic::x86_avx2_psra_w:
21547 case Intrinsic::x86_avx2_psra_d: {
21548 SDValue Op0 = N->getOperand(1);
21549 SDValue Op1 = N->getOperand(2);
21550 EVT VT = Op0.getValueType();
21551 assert(VT.isVector() && "Expected a vector type!");
21553 if (isa<BuildVectorSDNode>(Op1))
21554 Op1 = Op1.getOperand(0);
21556 if (!isa<ConstantSDNode>(Op1))
21559 EVT SVT = VT.getVectorElementType();
21560 unsigned SVTBits = SVT.getSizeInBits();
21562 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21563 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21564 uint64_t ShAmt = C.getZExtValue();
21566 // Don't try to convert this shift into a ISD::SRA if the shift
21567 // count is bigger than or equal to the element size.
21568 if (ShAmt >= SVTBits)
21571 // Trivial case: if the shift count is zero, then fold this
21572 // into the first operand.
21576 // Replace this packed shift intrinsic with a target independent
21578 SDValue Splat = DAG.getConstant(C, VT);
21579 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21584 /// PerformMulCombine - Optimize a single multiply with constant into two
21585 /// in order to implement it with two cheaper instructions, e.g.
21586 /// LEA + SHL, LEA + LEA.
21587 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21588 TargetLowering::DAGCombinerInfo &DCI) {
21589 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21592 EVT VT = N->getValueType(0);
21593 if (VT != MVT::i64 && VT != MVT::i32)
21596 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21599 uint64_t MulAmt = C->getZExtValue();
21600 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21603 uint64_t MulAmt1 = 0;
21604 uint64_t MulAmt2 = 0;
21605 if ((MulAmt % 9) == 0) {
21607 MulAmt2 = MulAmt / 9;
21608 } else if ((MulAmt % 5) == 0) {
21610 MulAmt2 = MulAmt / 5;
21611 } else if ((MulAmt % 3) == 0) {
21613 MulAmt2 = MulAmt / 3;
21616 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21619 if (isPowerOf2_64(MulAmt2) &&
21620 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21621 // If second multiplifer is pow2, issue it first. We want the multiply by
21622 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21624 std::swap(MulAmt1, MulAmt2);
21627 if (isPowerOf2_64(MulAmt1))
21628 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21629 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21631 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21632 DAG.getConstant(MulAmt1, VT));
21634 if (isPowerOf2_64(MulAmt2))
21635 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21636 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21638 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21639 DAG.getConstant(MulAmt2, VT));
21641 // Do not add new nodes to DAG combiner worklist.
21642 DCI.CombineTo(N, NewMul, false);
21647 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21648 SDValue N0 = N->getOperand(0);
21649 SDValue N1 = N->getOperand(1);
21650 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21651 EVT VT = N0.getValueType();
21653 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21654 // since the result of setcc_c is all zero's or all ones.
21655 if (VT.isInteger() && !VT.isVector() &&
21656 N1C && N0.getOpcode() == ISD::AND &&
21657 N0.getOperand(1).getOpcode() == ISD::Constant) {
21658 SDValue N00 = N0.getOperand(0);
21659 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21660 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21661 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21662 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21663 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21664 APInt ShAmt = N1C->getAPIntValue();
21665 Mask = Mask.shl(ShAmt);
21667 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21668 N00, DAG.getConstant(Mask, VT));
21672 // Hardware support for vector shifts is sparse which makes us scalarize the
21673 // vector operations in many cases. Also, on sandybridge ADD is faster than
21675 // (shl V, 1) -> add V,V
21676 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21677 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21678 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21679 // We shift all of the values by one. In many cases we do not have
21680 // hardware support for this operation. This is better expressed as an ADD
21682 if (N1SplatC->getZExtValue() == 1)
21683 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21689 /// \brief Returns a vector of 0s if the node in input is a vector logical
21690 /// shift by a constant amount which is known to be bigger than or equal
21691 /// to the vector element size in bits.
21692 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21693 const X86Subtarget *Subtarget) {
21694 EVT VT = N->getValueType(0);
21696 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21697 (!Subtarget->hasInt256() ||
21698 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21701 SDValue Amt = N->getOperand(1);
21703 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21704 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21705 APInt ShiftAmt = AmtSplat->getAPIntValue();
21706 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21708 // SSE2/AVX2 logical shifts always return a vector of 0s
21709 // if the shift amount is bigger than or equal to
21710 // the element size. The constant shift amount will be
21711 // encoded as a 8-bit immediate.
21712 if (ShiftAmt.trunc(8).uge(MaxAmount))
21713 return getZeroVector(VT, Subtarget, DAG, DL);
21719 /// PerformShiftCombine - Combine shifts.
21720 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21721 TargetLowering::DAGCombinerInfo &DCI,
21722 const X86Subtarget *Subtarget) {
21723 if (N->getOpcode() == ISD::SHL) {
21724 SDValue V = PerformSHLCombine(N, DAG);
21725 if (V.getNode()) return V;
21728 if (N->getOpcode() != ISD::SRA) {
21729 // Try to fold this logical shift into a zero vector.
21730 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21731 if (V.getNode()) return V;
21737 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21738 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21739 // and friends. Likewise for OR -> CMPNEQSS.
21740 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21741 TargetLowering::DAGCombinerInfo &DCI,
21742 const X86Subtarget *Subtarget) {
21745 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21746 // we're requiring SSE2 for both.
21747 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21748 SDValue N0 = N->getOperand(0);
21749 SDValue N1 = N->getOperand(1);
21750 SDValue CMP0 = N0->getOperand(1);
21751 SDValue CMP1 = N1->getOperand(1);
21754 // The SETCCs should both refer to the same CMP.
21755 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21758 SDValue CMP00 = CMP0->getOperand(0);
21759 SDValue CMP01 = CMP0->getOperand(1);
21760 EVT VT = CMP00.getValueType();
21762 if (VT == MVT::f32 || VT == MVT::f64) {
21763 bool ExpectingFlags = false;
21764 // Check for any users that want flags:
21765 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21766 !ExpectingFlags && UI != UE; ++UI)
21767 switch (UI->getOpcode()) {
21772 ExpectingFlags = true;
21774 case ISD::CopyToReg:
21775 case ISD::SIGN_EXTEND:
21776 case ISD::ZERO_EXTEND:
21777 case ISD::ANY_EXTEND:
21781 if (!ExpectingFlags) {
21782 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21783 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21785 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21786 X86::CondCode tmp = cc0;
21791 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21792 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21793 // FIXME: need symbolic constants for these magic numbers.
21794 // See X86ATTInstPrinter.cpp:printSSECC().
21795 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21796 if (Subtarget->hasAVX512()) {
21797 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21798 CMP01, DAG.getConstant(x86cc, MVT::i8));
21799 if (N->getValueType(0) != MVT::i1)
21800 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21804 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21805 CMP00.getValueType(), CMP00, CMP01,
21806 DAG.getConstant(x86cc, MVT::i8));
21808 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21809 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21811 if (is64BitFP && !Subtarget->is64Bit()) {
21812 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21813 // 64-bit integer, since that's not a legal type. Since
21814 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21815 // bits, but can do this little dance to extract the lowest 32 bits
21816 // and work with those going forward.
21817 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21819 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21821 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21822 Vector32, DAG.getIntPtrConstant(0));
21826 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21827 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21828 DAG.getConstant(1, IntVT));
21829 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21830 return OneBitOfTruth;
21838 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21839 /// so it can be folded inside ANDNP.
21840 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21841 EVT VT = N->getValueType(0);
21843 // Match direct AllOnes for 128 and 256-bit vectors
21844 if (ISD::isBuildVectorAllOnes(N))
21847 // Look through a bit convert.
21848 if (N->getOpcode() == ISD::BITCAST)
21849 N = N->getOperand(0).getNode();
21851 // Sometimes the operand may come from a insert_subvector building a 256-bit
21853 if (VT.is256BitVector() &&
21854 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21855 SDValue V1 = N->getOperand(0);
21856 SDValue V2 = N->getOperand(1);
21858 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21859 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21860 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21861 ISD::isBuildVectorAllOnes(V2.getNode()))
21868 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21869 // register. In most cases we actually compare or select YMM-sized registers
21870 // and mixing the two types creates horrible code. This method optimizes
21871 // some of the transition sequences.
21872 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21873 TargetLowering::DAGCombinerInfo &DCI,
21874 const X86Subtarget *Subtarget) {
21875 EVT VT = N->getValueType(0);
21876 if (!VT.is256BitVector())
21879 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21880 N->getOpcode() == ISD::ZERO_EXTEND ||
21881 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21883 SDValue Narrow = N->getOperand(0);
21884 EVT NarrowVT = Narrow->getValueType(0);
21885 if (!NarrowVT.is128BitVector())
21888 if (Narrow->getOpcode() != ISD::XOR &&
21889 Narrow->getOpcode() != ISD::AND &&
21890 Narrow->getOpcode() != ISD::OR)
21893 SDValue N0 = Narrow->getOperand(0);
21894 SDValue N1 = Narrow->getOperand(1);
21897 // The Left side has to be a trunc.
21898 if (N0.getOpcode() != ISD::TRUNCATE)
21901 // The type of the truncated inputs.
21902 EVT WideVT = N0->getOperand(0)->getValueType(0);
21906 // The right side has to be a 'trunc' or a constant vector.
21907 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21908 ConstantSDNode *RHSConstSplat = nullptr;
21909 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21910 RHSConstSplat = RHSBV->getConstantSplatNode();
21911 if (!RHSTrunc && !RHSConstSplat)
21914 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21916 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21919 // Set N0 and N1 to hold the inputs to the new wide operation.
21920 N0 = N0->getOperand(0);
21921 if (RHSConstSplat) {
21922 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21923 SDValue(RHSConstSplat, 0));
21924 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21925 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21926 } else if (RHSTrunc) {
21927 N1 = N1->getOperand(0);
21930 // Generate the wide operation.
21931 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21932 unsigned Opcode = N->getOpcode();
21934 case ISD::ANY_EXTEND:
21936 case ISD::ZERO_EXTEND: {
21937 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21938 APInt Mask = APInt::getAllOnesValue(InBits);
21939 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21940 return DAG.getNode(ISD::AND, DL, VT,
21941 Op, DAG.getConstant(Mask, VT));
21943 case ISD::SIGN_EXTEND:
21944 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21945 Op, DAG.getValueType(NarrowVT));
21947 llvm_unreachable("Unexpected opcode");
21951 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21952 TargetLowering::DAGCombinerInfo &DCI,
21953 const X86Subtarget *Subtarget) {
21954 SDValue N0 = N->getOperand(0);
21955 SDValue N1 = N->getOperand(1);
21958 // A vector zext_in_reg may be represented as a shuffle,
21959 // feeding into a bitcast (this represents anyext) feeding into
21960 // an and with a mask.
21961 // We'd like to try to combine that into a shuffle with zero
21962 // plus a bitcast, removing the and.
21963 if (N0.getOpcode() != ISD::BITCAST ||
21964 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21967 // The other side of the AND should be a splat of 2^C, where C
21968 // is the number of bits in the source type.
21969 if (N1.getOpcode() == ISD::BITCAST)
21970 N1 = N1.getOperand(0);
21971 if (N1.getOpcode() != ISD::BUILD_VECTOR)
21973 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21975 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21976 EVT SrcType = Shuffle->getValueType(0);
21978 // We expect a single-source shuffle
21979 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21982 unsigned SrcSize = SrcType.getScalarSizeInBits();
21984 APInt SplatValue, SplatUndef;
21985 unsigned SplatBitSize;
21987 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21988 SplatBitSize, HasAnyUndefs))
21991 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21992 // Make sure the splat matches the mask we expect
21993 if (SplatBitSize > ResSize ||
21994 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21997 // Make sure the input and output size make sense
21998 if (SrcSize >= ResSize || ResSize % SrcSize)
22001 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22002 // The number of u's between each two values depends on the ratio between
22003 // the source and dest type.
22004 unsigned ZextRatio = ResSize / SrcSize;
22005 bool IsZext = true;
22006 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22007 if (i % ZextRatio) {
22008 if (Shuffle->getMaskElt(i) > 0) {
22014 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22015 // Expected element number
22025 // Ok, perform the transformation - replace the shuffle with
22026 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22027 // (instead of undef) where the k elements come from the zero vector.
22028 SmallVector<int, 8> Mask;
22029 unsigned NumElems = SrcType.getVectorNumElements();
22030 for (unsigned i = 0; i < NumElems; ++i)
22032 Mask.push_back(NumElems);
22034 Mask.push_back(i / ZextRatio);
22036 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22037 Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22038 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22041 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22042 TargetLowering::DAGCombinerInfo &DCI,
22043 const X86Subtarget *Subtarget) {
22044 if (DCI.isBeforeLegalizeOps())
22047 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22050 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22053 EVT VT = N->getValueType(0);
22054 SDValue N0 = N->getOperand(0);
22055 SDValue N1 = N->getOperand(1);
22058 // Create BEXTR instructions
22059 // BEXTR is ((X >> imm) & (2**size-1))
22060 if (VT == MVT::i32 || VT == MVT::i64) {
22061 // Check for BEXTR.
22062 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22063 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22064 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22065 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22066 if (MaskNode && ShiftNode) {
22067 uint64_t Mask = MaskNode->getZExtValue();
22068 uint64_t Shift = ShiftNode->getZExtValue();
22069 if (isMask_64(Mask)) {
22070 uint64_t MaskSize = countPopulation(Mask);
22071 if (Shift + MaskSize <= VT.getSizeInBits())
22072 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22073 DAG.getConstant(Shift | (MaskSize << 8), VT));
22081 // Want to form ANDNP nodes:
22082 // 1) In the hopes of then easily combining them with OR and AND nodes
22083 // to form PBLEND/PSIGN.
22084 // 2) To match ANDN packed intrinsics
22085 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22088 // Check LHS for vnot
22089 if (N0.getOpcode() == ISD::XOR &&
22090 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22091 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22092 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22094 // Check RHS for vnot
22095 if (N1.getOpcode() == ISD::XOR &&
22096 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22097 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22098 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22103 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22104 TargetLowering::DAGCombinerInfo &DCI,
22105 const X86Subtarget *Subtarget) {
22106 if (DCI.isBeforeLegalizeOps())
22109 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22113 SDValue N0 = N->getOperand(0);
22114 SDValue N1 = N->getOperand(1);
22115 EVT VT = N->getValueType(0);
22117 // look for psign/blend
22118 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22119 if (!Subtarget->hasSSSE3() ||
22120 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22123 // Canonicalize pandn to RHS
22124 if (N0.getOpcode() == X86ISD::ANDNP)
22126 // or (and (m, y), (pandn m, x))
22127 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22128 SDValue Mask = N1.getOperand(0);
22129 SDValue X = N1.getOperand(1);
22131 if (N0.getOperand(0) == Mask)
22132 Y = N0.getOperand(1);
22133 if (N0.getOperand(1) == Mask)
22134 Y = N0.getOperand(0);
22136 // Check to see if the mask appeared in both the AND and ANDNP and
22140 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22141 // Look through mask bitcast.
22142 if (Mask.getOpcode() == ISD::BITCAST)
22143 Mask = Mask.getOperand(0);
22144 if (X.getOpcode() == ISD::BITCAST)
22145 X = X.getOperand(0);
22146 if (Y.getOpcode() == ISD::BITCAST)
22147 Y = Y.getOperand(0);
22149 EVT MaskVT = Mask.getValueType();
22151 // Validate that the Mask operand is a vector sra node.
22152 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22153 // there is no psrai.b
22154 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22155 unsigned SraAmt = ~0;
22156 if (Mask.getOpcode() == ISD::SRA) {
22157 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22158 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22159 SraAmt = AmtConst->getZExtValue();
22160 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22161 SDValue SraC = Mask.getOperand(1);
22162 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22164 if ((SraAmt + 1) != EltBits)
22169 // Now we know we at least have a plendvb with the mask val. See if
22170 // we can form a psignb/w/d.
22171 // psign = x.type == y.type == mask.type && y = sub(0, x);
22172 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22173 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22174 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22175 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22176 "Unsupported VT for PSIGN");
22177 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22178 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22180 // PBLENDVB only available on SSE 4.1
22181 if (!Subtarget->hasSSE41())
22184 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22186 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22187 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22188 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22189 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22190 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22194 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22197 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22198 MachineFunction &MF = DAG.getMachineFunction();
22200 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22202 // SHLD/SHRD instructions have lower register pressure, but on some
22203 // platforms they have higher latency than the equivalent
22204 // series of shifts/or that would otherwise be generated.
22205 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22206 // have higher latencies and we are not optimizing for size.
22207 if (!OptForSize && Subtarget->isSHLDSlow())
22210 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22212 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22214 if (!N0.hasOneUse() || !N1.hasOneUse())
22217 SDValue ShAmt0 = N0.getOperand(1);
22218 if (ShAmt0.getValueType() != MVT::i8)
22220 SDValue ShAmt1 = N1.getOperand(1);
22221 if (ShAmt1.getValueType() != MVT::i8)
22223 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22224 ShAmt0 = ShAmt0.getOperand(0);
22225 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22226 ShAmt1 = ShAmt1.getOperand(0);
22229 unsigned Opc = X86ISD::SHLD;
22230 SDValue Op0 = N0.getOperand(0);
22231 SDValue Op1 = N1.getOperand(0);
22232 if (ShAmt0.getOpcode() == ISD::SUB) {
22233 Opc = X86ISD::SHRD;
22234 std::swap(Op0, Op1);
22235 std::swap(ShAmt0, ShAmt1);
22238 unsigned Bits = VT.getSizeInBits();
22239 if (ShAmt1.getOpcode() == ISD::SUB) {
22240 SDValue Sum = ShAmt1.getOperand(0);
22241 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22242 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22243 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22244 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22245 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22246 return DAG.getNode(Opc, DL, VT,
22248 DAG.getNode(ISD::TRUNCATE, DL,
22251 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22252 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22254 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22255 return DAG.getNode(Opc, DL, VT,
22256 N0.getOperand(0), N1.getOperand(0),
22257 DAG.getNode(ISD::TRUNCATE, DL,
22264 // Generate NEG and CMOV for integer abs.
22265 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22266 EVT VT = N->getValueType(0);
22268 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22269 // 8-bit integer abs to NEG and CMOV.
22270 if (VT.isInteger() && VT.getSizeInBits() == 8)
22273 SDValue N0 = N->getOperand(0);
22274 SDValue N1 = N->getOperand(1);
22277 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22278 // and change it to SUB and CMOV.
22279 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22280 N0.getOpcode() == ISD::ADD &&
22281 N0.getOperand(1) == N1 &&
22282 N1.getOpcode() == ISD::SRA &&
22283 N1.getOperand(0) == N0.getOperand(0))
22284 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22285 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22286 // Generate SUB & CMOV.
22287 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22288 DAG.getConstant(0, VT), N0.getOperand(0));
22290 SDValue Ops[] = { N0.getOperand(0), Neg,
22291 DAG.getConstant(X86::COND_GE, MVT::i8),
22292 SDValue(Neg.getNode(), 1) };
22293 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22298 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22299 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22300 TargetLowering::DAGCombinerInfo &DCI,
22301 const X86Subtarget *Subtarget) {
22302 if (DCI.isBeforeLegalizeOps())
22305 if (Subtarget->hasCMov()) {
22306 SDValue RV = performIntegerAbsCombine(N, DAG);
22314 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22315 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22316 TargetLowering::DAGCombinerInfo &DCI,
22317 const X86Subtarget *Subtarget) {
22318 LoadSDNode *Ld = cast<LoadSDNode>(N);
22319 EVT RegVT = Ld->getValueType(0);
22320 EVT MemVT = Ld->getMemoryVT();
22322 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22324 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22325 // into two 16-byte operations.
22326 ISD::LoadExtType Ext = Ld->getExtensionType();
22327 unsigned Alignment = Ld->getAlignment();
22328 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22329 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22330 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22331 unsigned NumElems = RegVT.getVectorNumElements();
22335 SDValue Ptr = Ld->getBasePtr();
22336 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22338 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22340 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22341 Ld->getPointerInfo(), Ld->isVolatile(),
22342 Ld->isNonTemporal(), Ld->isInvariant(),
22344 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22345 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22346 Ld->getPointerInfo(), Ld->isVolatile(),
22347 Ld->isNonTemporal(), Ld->isInvariant(),
22348 std::min(16U, Alignment));
22349 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22351 Load2.getValue(1));
22353 SDValue NewVec = DAG.getUNDEF(RegVT);
22354 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22355 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22356 return DCI.CombineTo(N, NewVec, TF, true);
22362 /// PerformMLOADCombine - Resolve extending loads
22363 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22364 TargetLowering::DAGCombinerInfo &DCI,
22365 const X86Subtarget *Subtarget) {
22366 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22367 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22370 EVT VT = Mld->getValueType(0);
22371 unsigned NumElems = VT.getVectorNumElements();
22372 EVT LdVT = Mld->getMemoryVT();
22375 assert(LdVT != VT && "Cannot extend to the same type");
22376 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22377 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22378 // From, To sizes and ElemCount must be pow of two
22379 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22380 "Unexpected size for extending masked load");
22382 unsigned SizeRatio = ToSz / FromSz;
22383 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22385 // Create a type on which we perform the shuffle
22386 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22387 LdVT.getScalarType(), NumElems*SizeRatio);
22388 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22390 // Convert Src0 value
22391 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22392 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22393 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22394 for (unsigned i = 0; i != NumElems; ++i)
22395 ShuffleVec[i] = i * SizeRatio;
22397 // Can't shuffle using an illegal type.
22398 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22399 && "WideVecVT should be legal");
22400 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22401 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22403 // Prepare the new mask
22405 SDValue Mask = Mld->getMask();
22406 if (Mask.getValueType() == VT) {
22407 // Mask and original value have the same type
22408 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22409 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22410 for (unsigned i = 0; i != NumElems; ++i)
22411 ShuffleVec[i] = i * SizeRatio;
22412 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22413 ShuffleVec[i] = NumElems*SizeRatio;
22414 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22415 DAG.getConstant(0, WideVecVT),
22419 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22420 unsigned WidenNumElts = NumElems*SizeRatio;
22421 unsigned MaskNumElts = VT.getVectorNumElements();
22422 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22425 unsigned NumConcat = WidenNumElts / MaskNumElts;
22426 SmallVector<SDValue, 16> Ops(NumConcat);
22427 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22429 for (unsigned i = 1; i != NumConcat; ++i)
22432 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22435 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22436 Mld->getBasePtr(), NewMask, WideSrc0,
22437 Mld->getMemoryVT(), Mld->getMemOperand(),
22439 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22440 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22443 /// PerformMSTORECombine - Resolve truncating stores
22444 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22445 const X86Subtarget *Subtarget) {
22446 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22447 if (!Mst->isTruncatingStore())
22450 EVT VT = Mst->getValue().getValueType();
22451 unsigned NumElems = VT.getVectorNumElements();
22452 EVT StVT = Mst->getMemoryVT();
22455 assert(StVT != VT && "Cannot truncate to the same type");
22456 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22457 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22459 // From, To sizes and ElemCount must be pow of two
22460 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22461 "Unexpected size for truncating masked store");
22462 // We are going to use the original vector elt for storing.
22463 // Accumulated smaller vector elements must be a multiple of the store size.
22464 assert (((NumElems * FromSz) % ToSz) == 0 &&
22465 "Unexpected ratio for truncating masked store");
22467 unsigned SizeRatio = FromSz / ToSz;
22468 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22470 // Create a type on which we perform the shuffle
22471 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22472 StVT.getScalarType(), NumElems*SizeRatio);
22474 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22476 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22477 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22478 for (unsigned i = 0; i != NumElems; ++i)
22479 ShuffleVec[i] = i * SizeRatio;
22481 // Can't shuffle using an illegal type.
22482 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22483 && "WideVecVT should be legal");
22485 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22486 DAG.getUNDEF(WideVecVT),
22490 SDValue Mask = Mst->getMask();
22491 if (Mask.getValueType() == VT) {
22492 // Mask and original value have the same type
22493 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22494 for (unsigned i = 0; i != NumElems; ++i)
22495 ShuffleVec[i] = i * SizeRatio;
22496 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22497 ShuffleVec[i] = NumElems*SizeRatio;
22498 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22499 DAG.getConstant(0, WideVecVT),
22503 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22504 unsigned WidenNumElts = NumElems*SizeRatio;
22505 unsigned MaskNumElts = VT.getVectorNumElements();
22506 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22509 unsigned NumConcat = WidenNumElts / MaskNumElts;
22510 SmallVector<SDValue, 16> Ops(NumConcat);
22511 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22513 for (unsigned i = 1; i != NumConcat; ++i)
22516 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22519 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22520 NewMask, StVT, Mst->getMemOperand(), false);
22522 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22523 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22524 const X86Subtarget *Subtarget) {
22525 StoreSDNode *St = cast<StoreSDNode>(N);
22526 EVT VT = St->getValue().getValueType();
22527 EVT StVT = St->getMemoryVT();
22529 SDValue StoredVal = St->getOperand(1);
22530 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22532 // If we are saving a concatenation of two XMM registers and 32-byte stores
22533 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22534 unsigned Alignment = St->getAlignment();
22535 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22536 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22537 StVT == VT && !IsAligned) {
22538 unsigned NumElems = VT.getVectorNumElements();
22542 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22543 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22545 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22546 SDValue Ptr0 = St->getBasePtr();
22547 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22549 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22550 St->getPointerInfo(), St->isVolatile(),
22551 St->isNonTemporal(), Alignment);
22552 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22553 St->getPointerInfo(), St->isVolatile(),
22554 St->isNonTemporal(),
22555 std::min(16U, Alignment));
22556 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22559 // Optimize trunc store (of multiple scalars) to shuffle and store.
22560 // First, pack all of the elements in one place. Next, store to memory
22561 // in fewer chunks.
22562 if (St->isTruncatingStore() && VT.isVector()) {
22563 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22564 unsigned NumElems = VT.getVectorNumElements();
22565 assert(StVT != VT && "Cannot truncate to the same type");
22566 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22567 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22569 // From, To sizes and ElemCount must be pow of two
22570 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22571 // We are going to use the original vector elt for storing.
22572 // Accumulated smaller vector elements must be a multiple of the store size.
22573 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22575 unsigned SizeRatio = FromSz / ToSz;
22577 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22579 // Create a type on which we perform the shuffle
22580 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22581 StVT.getScalarType(), NumElems*SizeRatio);
22583 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22585 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22586 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22587 for (unsigned i = 0; i != NumElems; ++i)
22588 ShuffleVec[i] = i * SizeRatio;
22590 // Can't shuffle using an illegal type.
22591 if (!TLI.isTypeLegal(WideVecVT))
22594 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22595 DAG.getUNDEF(WideVecVT),
22597 // At this point all of the data is stored at the bottom of the
22598 // register. We now need to save it to mem.
22600 // Find the largest store unit
22601 MVT StoreType = MVT::i8;
22602 for (MVT Tp : MVT::integer_valuetypes()) {
22603 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22607 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22608 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22609 (64 <= NumElems * ToSz))
22610 StoreType = MVT::f64;
22612 // Bitcast the original vector into a vector of store-size units
22613 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22614 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22615 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22616 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22617 SmallVector<SDValue, 8> Chains;
22618 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22619 TLI.getPointerTy());
22620 SDValue Ptr = St->getBasePtr();
22622 // Perform one or more big stores into memory.
22623 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22624 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22625 StoreType, ShuffWide,
22626 DAG.getIntPtrConstant(i));
22627 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22628 St->getPointerInfo(), St->isVolatile(),
22629 St->isNonTemporal(), St->getAlignment());
22630 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22631 Chains.push_back(Ch);
22634 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22637 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22638 // the FP state in cases where an emms may be missing.
22639 // A preferable solution to the general problem is to figure out the right
22640 // places to insert EMMS. This qualifies as a quick hack.
22642 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22643 if (VT.getSizeInBits() != 64)
22646 const Function *F = DAG.getMachineFunction().getFunction();
22647 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22648 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22649 && Subtarget->hasSSE2();
22650 if ((VT.isVector() ||
22651 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22652 isa<LoadSDNode>(St->getValue()) &&
22653 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22654 St->getChain().hasOneUse() && !St->isVolatile()) {
22655 SDNode* LdVal = St->getValue().getNode();
22656 LoadSDNode *Ld = nullptr;
22657 int TokenFactorIndex = -1;
22658 SmallVector<SDValue, 8> Ops;
22659 SDNode* ChainVal = St->getChain().getNode();
22660 // Must be a store of a load. We currently handle two cases: the load
22661 // is a direct child, and it's under an intervening TokenFactor. It is
22662 // possible to dig deeper under nested TokenFactors.
22663 if (ChainVal == LdVal)
22664 Ld = cast<LoadSDNode>(St->getChain());
22665 else if (St->getValue().hasOneUse() &&
22666 ChainVal->getOpcode() == ISD::TokenFactor) {
22667 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22668 if (ChainVal->getOperand(i).getNode() == LdVal) {
22669 TokenFactorIndex = i;
22670 Ld = cast<LoadSDNode>(St->getValue());
22672 Ops.push_back(ChainVal->getOperand(i));
22676 if (!Ld || !ISD::isNormalLoad(Ld))
22679 // If this is not the MMX case, i.e. we are just turning i64 load/store
22680 // into f64 load/store, avoid the transformation if there are multiple
22681 // uses of the loaded value.
22682 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22687 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22688 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22690 if (Subtarget->is64Bit() || F64IsLegal) {
22691 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22692 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22693 Ld->getPointerInfo(), Ld->isVolatile(),
22694 Ld->isNonTemporal(), Ld->isInvariant(),
22695 Ld->getAlignment());
22696 SDValue NewChain = NewLd.getValue(1);
22697 if (TokenFactorIndex != -1) {
22698 Ops.push_back(NewChain);
22699 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22701 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22702 St->getPointerInfo(),
22703 St->isVolatile(), St->isNonTemporal(),
22704 St->getAlignment());
22707 // Otherwise, lower to two pairs of 32-bit loads / stores.
22708 SDValue LoAddr = Ld->getBasePtr();
22709 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22710 DAG.getConstant(4, MVT::i32));
22712 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22713 Ld->getPointerInfo(),
22714 Ld->isVolatile(), Ld->isNonTemporal(),
22715 Ld->isInvariant(), Ld->getAlignment());
22716 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22717 Ld->getPointerInfo().getWithOffset(4),
22718 Ld->isVolatile(), Ld->isNonTemporal(),
22720 MinAlign(Ld->getAlignment(), 4));
22722 SDValue NewChain = LoLd.getValue(1);
22723 if (TokenFactorIndex != -1) {
22724 Ops.push_back(LoLd);
22725 Ops.push_back(HiLd);
22726 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22729 LoAddr = St->getBasePtr();
22730 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22731 DAG.getConstant(4, MVT::i32));
22733 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22734 St->getPointerInfo(),
22735 St->isVolatile(), St->isNonTemporal(),
22736 St->getAlignment());
22737 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22738 St->getPointerInfo().getWithOffset(4),
22740 St->isNonTemporal(),
22741 MinAlign(St->getAlignment(), 4));
22742 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22747 /// Return 'true' if this vector operation is "horizontal"
22748 /// and return the operands for the horizontal operation in LHS and RHS. A
22749 /// horizontal operation performs the binary operation on successive elements
22750 /// of its first operand, then on successive elements of its second operand,
22751 /// returning the resulting values in a vector. For example, if
22752 /// A = < float a0, float a1, float a2, float a3 >
22754 /// B = < float b0, float b1, float b2, float b3 >
22755 /// then the result of doing a horizontal operation on A and B is
22756 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22757 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22758 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22759 /// set to A, RHS to B, and the routine returns 'true'.
22760 /// Note that the binary operation should have the property that if one of the
22761 /// operands is UNDEF then the result is UNDEF.
22762 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22763 // Look for the following pattern: if
22764 // A = < float a0, float a1, float a2, float a3 >
22765 // B = < float b0, float b1, float b2, float b3 >
22767 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22768 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22769 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22770 // which is A horizontal-op B.
22772 // At least one of the operands should be a vector shuffle.
22773 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22774 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22777 MVT VT = LHS.getSimpleValueType();
22779 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22780 "Unsupported vector type for horizontal add/sub");
22782 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22783 // operate independently on 128-bit lanes.
22784 unsigned NumElts = VT.getVectorNumElements();
22785 unsigned NumLanes = VT.getSizeInBits()/128;
22786 unsigned NumLaneElts = NumElts / NumLanes;
22787 assert((NumLaneElts % 2 == 0) &&
22788 "Vector type should have an even number of elements in each lane");
22789 unsigned HalfLaneElts = NumLaneElts/2;
22791 // View LHS in the form
22792 // LHS = VECTOR_SHUFFLE A, B, LMask
22793 // If LHS is not a shuffle then pretend it is the shuffle
22794 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22795 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22798 SmallVector<int, 16> LMask(NumElts);
22799 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22800 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22801 A = LHS.getOperand(0);
22802 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22803 B = LHS.getOperand(1);
22804 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22805 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22807 if (LHS.getOpcode() != ISD::UNDEF)
22809 for (unsigned i = 0; i != NumElts; ++i)
22813 // Likewise, view RHS in the form
22814 // RHS = VECTOR_SHUFFLE C, D, RMask
22816 SmallVector<int, 16> RMask(NumElts);
22817 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22818 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22819 C = RHS.getOperand(0);
22820 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22821 D = RHS.getOperand(1);
22822 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22823 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22825 if (RHS.getOpcode() != ISD::UNDEF)
22827 for (unsigned i = 0; i != NumElts; ++i)
22831 // Check that the shuffles are both shuffling the same vectors.
22832 if (!(A == C && B == D) && !(A == D && B == C))
22835 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22836 if (!A.getNode() && !B.getNode())
22839 // If A and B occur in reverse order in RHS, then "swap" them (which means
22840 // rewriting the mask).
22842 ShuffleVectorSDNode::commuteMask(RMask);
22844 // At this point LHS and RHS are equivalent to
22845 // LHS = VECTOR_SHUFFLE A, B, LMask
22846 // RHS = VECTOR_SHUFFLE A, B, RMask
22847 // Check that the masks correspond to performing a horizontal operation.
22848 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22849 for (unsigned i = 0; i != NumLaneElts; ++i) {
22850 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22852 // Ignore any UNDEF components.
22853 if (LIdx < 0 || RIdx < 0 ||
22854 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22855 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22858 // Check that successive elements are being operated on. If not, this is
22859 // not a horizontal operation.
22860 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22861 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22862 if (!(LIdx == Index && RIdx == Index + 1) &&
22863 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22868 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22869 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22873 /// Do target-specific dag combines on floating point adds.
22874 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22875 const X86Subtarget *Subtarget) {
22876 EVT VT = N->getValueType(0);
22877 SDValue LHS = N->getOperand(0);
22878 SDValue RHS = N->getOperand(1);
22880 // Try to synthesize horizontal adds from adds of shuffles.
22881 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22882 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22883 isHorizontalBinOp(LHS, RHS, true))
22884 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22888 /// Do target-specific dag combines on floating point subs.
22889 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22890 const X86Subtarget *Subtarget) {
22891 EVT VT = N->getValueType(0);
22892 SDValue LHS = N->getOperand(0);
22893 SDValue RHS = N->getOperand(1);
22895 // Try to synthesize horizontal subs from subs of shuffles.
22896 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22897 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22898 isHorizontalBinOp(LHS, RHS, false))
22899 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22903 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22904 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22905 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22907 // F[X]OR(0.0, x) -> x
22908 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22909 if (C->getValueAPF().isPosZero())
22910 return N->getOperand(1);
22912 // F[X]OR(x, 0.0) -> x
22913 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22914 if (C->getValueAPF().isPosZero())
22915 return N->getOperand(0);
22919 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22920 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22921 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22923 // Only perform optimizations if UnsafeMath is used.
22924 if (!DAG.getTarget().Options.UnsafeFPMath)
22927 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22928 // into FMINC and FMAXC, which are Commutative operations.
22929 unsigned NewOp = 0;
22930 switch (N->getOpcode()) {
22931 default: llvm_unreachable("unknown opcode");
22932 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22933 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22936 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22937 N->getOperand(0), N->getOperand(1));
22940 /// Do target-specific dag combines on X86ISD::FAND nodes.
22941 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22942 // FAND(0.0, x) -> 0.0
22943 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22944 if (C->getValueAPF().isPosZero())
22945 return N->getOperand(0);
22947 // FAND(x, 0.0) -> 0.0
22948 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22949 if (C->getValueAPF().isPosZero())
22950 return N->getOperand(1);
22955 /// Do target-specific dag combines on X86ISD::FANDN nodes
22956 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22957 // FANDN(0.0, x) -> x
22958 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22959 if (C->getValueAPF().isPosZero())
22960 return N->getOperand(1);
22962 // FANDN(x, 0.0) -> 0.0
22963 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22964 if (C->getValueAPF().isPosZero())
22965 return N->getOperand(1);
22970 static SDValue PerformBTCombine(SDNode *N,
22972 TargetLowering::DAGCombinerInfo &DCI) {
22973 // BT ignores high bits in the bit index operand.
22974 SDValue Op1 = N->getOperand(1);
22975 if (Op1.hasOneUse()) {
22976 unsigned BitWidth = Op1.getValueSizeInBits();
22977 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22978 APInt KnownZero, KnownOne;
22979 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22980 !DCI.isBeforeLegalizeOps());
22981 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22982 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22983 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22984 DCI.CommitTargetLoweringOpt(TLO);
22989 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22990 SDValue Op = N->getOperand(0);
22991 if (Op.getOpcode() == ISD::BITCAST)
22992 Op = Op.getOperand(0);
22993 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22994 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22995 VT.getVectorElementType().getSizeInBits() ==
22996 OpVT.getVectorElementType().getSizeInBits()) {
22997 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23002 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23003 const X86Subtarget *Subtarget) {
23004 EVT VT = N->getValueType(0);
23005 if (!VT.isVector())
23008 SDValue N0 = N->getOperand(0);
23009 SDValue N1 = N->getOperand(1);
23010 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23013 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23014 // both SSE and AVX2 since there is no sign-extended shift right
23015 // operation on a vector with 64-bit elements.
23016 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23017 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23018 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23019 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23020 SDValue N00 = N0.getOperand(0);
23022 // EXTLOAD has a better solution on AVX2,
23023 // it may be replaced with X86ISD::VSEXT node.
23024 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23025 if (!ISD::isNormalLoad(N00.getNode()))
23028 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23029 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23031 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23037 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23038 TargetLowering::DAGCombinerInfo &DCI,
23039 const X86Subtarget *Subtarget) {
23040 SDValue N0 = N->getOperand(0);
23041 EVT VT = N->getValueType(0);
23043 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23044 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23045 // This exposes the sext to the sdivrem lowering, so that it directly extends
23046 // from AH (which we otherwise need to do contortions to access).
23047 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23048 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23050 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23051 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23052 N0.getOperand(0), N0.getOperand(1));
23053 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23054 return R.getValue(1);
23057 if (!DCI.isBeforeLegalizeOps())
23060 if (!Subtarget->hasFp256())
23063 if (VT.isVector() && VT.getSizeInBits() == 256) {
23064 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23072 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23073 const X86Subtarget* Subtarget) {
23075 EVT VT = N->getValueType(0);
23077 // Let legalize expand this if it isn't a legal type yet.
23078 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23081 EVT ScalarVT = VT.getScalarType();
23082 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23083 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23086 SDValue A = N->getOperand(0);
23087 SDValue B = N->getOperand(1);
23088 SDValue C = N->getOperand(2);
23090 bool NegA = (A.getOpcode() == ISD::FNEG);
23091 bool NegB = (B.getOpcode() == ISD::FNEG);
23092 bool NegC = (C.getOpcode() == ISD::FNEG);
23094 // Negative multiplication when NegA xor NegB
23095 bool NegMul = (NegA != NegB);
23097 A = A.getOperand(0);
23099 B = B.getOperand(0);
23101 C = C.getOperand(0);
23105 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23107 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23109 return DAG.getNode(Opcode, dl, VT, A, B, C);
23112 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23113 TargetLowering::DAGCombinerInfo &DCI,
23114 const X86Subtarget *Subtarget) {
23115 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23116 // (and (i32 x86isd::setcc_carry), 1)
23117 // This eliminates the zext. This transformation is necessary because
23118 // ISD::SETCC is always legalized to i8.
23120 SDValue N0 = N->getOperand(0);
23121 EVT VT = N->getValueType(0);
23123 if (N0.getOpcode() == ISD::AND &&
23125 N0.getOperand(0).hasOneUse()) {
23126 SDValue N00 = N0.getOperand(0);
23127 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23128 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23129 if (!C || C->getZExtValue() != 1)
23131 return DAG.getNode(ISD::AND, dl, VT,
23132 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23133 N00.getOperand(0), N00.getOperand(1)),
23134 DAG.getConstant(1, VT));
23138 if (N0.getOpcode() == ISD::TRUNCATE &&
23140 N0.getOperand(0).hasOneUse()) {
23141 SDValue N00 = N0.getOperand(0);
23142 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23143 return DAG.getNode(ISD::AND, dl, VT,
23144 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23145 N00.getOperand(0), N00.getOperand(1)),
23146 DAG.getConstant(1, VT));
23149 if (VT.is256BitVector()) {
23150 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23155 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23156 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23157 // This exposes the zext to the udivrem lowering, so that it directly extends
23158 // from AH (which we otherwise need to do contortions to access).
23159 if (N0.getOpcode() == ISD::UDIVREM &&
23160 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23161 (VT == MVT::i32 || VT == MVT::i64)) {
23162 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23163 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23164 N0.getOperand(0), N0.getOperand(1));
23165 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23166 return R.getValue(1);
23172 // Optimize x == -y --> x+y == 0
23173 // x != -y --> x+y != 0
23174 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23175 const X86Subtarget* Subtarget) {
23176 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23177 SDValue LHS = N->getOperand(0);
23178 SDValue RHS = N->getOperand(1);
23179 EVT VT = N->getValueType(0);
23182 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23184 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23185 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23186 LHS.getOperand(1));
23187 return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23188 DAG.getConstant(0, addV.getValueType()), CC);
23190 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23192 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23193 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23194 RHS.getOperand(1));
23195 return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23196 DAG.getConstant(0, addV.getValueType()), CC);
23199 if (VT.getScalarType() == MVT::i1 &&
23200 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23202 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23203 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23204 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23206 if (!IsSEXT0 || !IsVZero1) {
23207 // Swap the operands and update the condition code.
23208 std::swap(LHS, RHS);
23209 CC = ISD::getSetCCSwappedOperands(CC);
23211 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23212 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23213 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23216 if (IsSEXT0 && IsVZero1) {
23217 assert(VT == LHS.getOperand(0).getValueType() &&
23218 "Uexpected operand type");
23219 if (CC == ISD::SETGT)
23220 return DAG.getConstant(0, VT);
23221 if (CC == ISD::SETLE)
23222 return DAG.getConstant(1, VT);
23223 if (CC == ISD::SETEQ || CC == ISD::SETGE)
23224 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23226 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23227 "Unexpected condition code!");
23228 return LHS.getOperand(0);
23235 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23236 SelectionDAG &DAG) {
23238 MVT VT = Load->getSimpleValueType(0);
23239 MVT EVT = VT.getVectorElementType();
23240 SDValue Addr = Load->getOperand(1);
23241 SDValue NewAddr = DAG.getNode(
23242 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23243 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23246 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23247 DAG.getMachineFunction().getMachineMemOperand(
23248 Load->getMemOperand(), 0, EVT.getStoreSize()));
23252 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23253 const X86Subtarget *Subtarget) {
23255 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23256 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23257 "X86insertps is only defined for v4x32");
23259 SDValue Ld = N->getOperand(1);
23260 if (MayFoldLoad(Ld)) {
23261 // Extract the countS bits from the immediate so we can get the proper
23262 // address when narrowing the vector load to a specific element.
23263 // When the second source op is a memory address, insertps doesn't use
23264 // countS and just gets an f32 from that address.
23265 unsigned DestIndex =
23266 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23268 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23270 // Create this as a scalar to vector to match the instruction pattern.
23271 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23272 // countS bits are ignored when loading from memory on insertps, which
23273 // means we don't need to explicitly set them to 0.
23274 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23275 LoadScalarToVector, N->getOperand(2));
23280 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23281 SDValue V0 = N->getOperand(0);
23282 SDValue V1 = N->getOperand(1);
23284 EVT VT = N->getValueType(0);
23286 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23287 // operands and changing the mask to 1. This saves us a bunch of
23288 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23289 // x86InstrInfo knows how to commute this back after instruction selection
23290 // if it would help register allocation.
23292 // TODO: If optimizing for size or a processor that doesn't suffer from
23293 // partial register update stalls, this should be transformed into a MOVSD
23294 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23296 if (VT == MVT::v2f64)
23297 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23298 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23299 SDValue NewMask = DAG.getConstant(1, MVT::i8);
23300 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23306 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23307 // as "sbb reg,reg", since it can be extended without zext and produces
23308 // an all-ones bit which is more useful than 0/1 in some cases.
23309 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23312 return DAG.getNode(ISD::AND, DL, VT,
23313 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23314 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23315 DAG.getConstant(1, VT));
23316 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23317 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23318 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23319 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23322 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23323 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23324 TargetLowering::DAGCombinerInfo &DCI,
23325 const X86Subtarget *Subtarget) {
23327 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23328 SDValue EFLAGS = N->getOperand(1);
23330 if (CC == X86::COND_A) {
23331 // Try to convert COND_A into COND_B in an attempt to facilitate
23332 // materializing "setb reg".
23334 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23335 // cannot take an immediate as its first operand.
23337 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23338 EFLAGS.getValueType().isInteger() &&
23339 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23340 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23341 EFLAGS.getNode()->getVTList(),
23342 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23343 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23344 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23348 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23349 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23351 if (CC == X86::COND_B)
23352 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23356 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23357 if (Flags.getNode()) {
23358 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23359 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23365 // Optimize branch condition evaluation.
23367 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23368 TargetLowering::DAGCombinerInfo &DCI,
23369 const X86Subtarget *Subtarget) {
23371 SDValue Chain = N->getOperand(0);
23372 SDValue Dest = N->getOperand(1);
23373 SDValue EFLAGS = N->getOperand(3);
23374 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23378 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23379 if (Flags.getNode()) {
23380 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23381 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23388 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23389 SelectionDAG &DAG) {
23390 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23391 // optimize away operation when it's from a constant.
23393 // The general transformation is:
23394 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23395 // AND(VECTOR_CMP(x,y), constant2)
23396 // constant2 = UNARYOP(constant)
23398 // Early exit if this isn't a vector operation, the operand of the
23399 // unary operation isn't a bitwise AND, or if the sizes of the operations
23400 // aren't the same.
23401 EVT VT = N->getValueType(0);
23402 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23403 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23404 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23407 // Now check that the other operand of the AND is a constant. We could
23408 // make the transformation for non-constant splats as well, but it's unclear
23409 // that would be a benefit as it would not eliminate any operations, just
23410 // perform one more step in scalar code before moving to the vector unit.
23411 if (BuildVectorSDNode *BV =
23412 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23413 // Bail out if the vector isn't a constant.
23414 if (!BV->isConstant())
23417 // Everything checks out. Build up the new and improved node.
23419 EVT IntVT = BV->getValueType(0);
23420 // Create a new constant of the appropriate type for the transformed
23422 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23423 // The AND node needs bitcasts to/from an integer vector type around it.
23424 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23425 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23426 N->getOperand(0)->getOperand(0), MaskConst);
23427 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23434 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23435 const X86Subtarget *Subtarget) {
23436 // First try to optimize away the conversion entirely when it's
23437 // conditionally from a constant. Vectors only.
23438 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23439 if (Res != SDValue())
23442 // Now move on to more general possibilities.
23443 SDValue Op0 = N->getOperand(0);
23444 EVT InVT = Op0->getValueType(0);
23446 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23447 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23449 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23450 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23451 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23454 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23455 // a 32-bit target where SSE doesn't support i64->FP operations.
23456 if (Op0.getOpcode() == ISD::LOAD) {
23457 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23458 EVT VT = Ld->getValueType(0);
23459 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23460 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23461 !Subtarget->is64Bit() && VT == MVT::i64) {
23462 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23463 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23464 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23471 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23472 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23473 X86TargetLowering::DAGCombinerInfo &DCI) {
23474 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23475 // the result is either zero or one (depending on the input carry bit).
23476 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23477 if (X86::isZeroNode(N->getOperand(0)) &&
23478 X86::isZeroNode(N->getOperand(1)) &&
23479 // We don't have a good way to replace an EFLAGS use, so only do this when
23481 SDValue(N, 1).use_empty()) {
23483 EVT VT = N->getValueType(0);
23484 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23485 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23486 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23487 DAG.getConstant(X86::COND_B,MVT::i8),
23489 DAG.getConstant(1, VT));
23490 return DCI.CombineTo(N, Res1, CarryOut);
23496 // fold (add Y, (sete X, 0)) -> adc 0, Y
23497 // (add Y, (setne X, 0)) -> sbb -1, Y
23498 // (sub (sete X, 0), Y) -> sbb 0, Y
23499 // (sub (setne X, 0), Y) -> adc -1, Y
23500 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23503 // Look through ZExts.
23504 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23505 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23508 SDValue SetCC = Ext.getOperand(0);
23509 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23512 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23513 if (CC != X86::COND_E && CC != X86::COND_NE)
23516 SDValue Cmp = SetCC.getOperand(1);
23517 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23518 !X86::isZeroNode(Cmp.getOperand(1)) ||
23519 !Cmp.getOperand(0).getValueType().isInteger())
23522 SDValue CmpOp0 = Cmp.getOperand(0);
23523 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23524 DAG.getConstant(1, CmpOp0.getValueType()));
23526 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23527 if (CC == X86::COND_NE)
23528 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23529 DL, OtherVal.getValueType(), OtherVal,
23530 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23531 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23532 DL, OtherVal.getValueType(), OtherVal,
23533 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23536 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23537 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23538 const X86Subtarget *Subtarget) {
23539 EVT VT = N->getValueType(0);
23540 SDValue Op0 = N->getOperand(0);
23541 SDValue Op1 = N->getOperand(1);
23543 // Try to synthesize horizontal adds from adds of shuffles.
23544 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23545 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23546 isHorizontalBinOp(Op0, Op1, true))
23547 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23549 return OptimizeConditionalInDecrement(N, DAG);
23552 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23553 const X86Subtarget *Subtarget) {
23554 SDValue Op0 = N->getOperand(0);
23555 SDValue Op1 = N->getOperand(1);
23557 // X86 can't encode an immediate LHS of a sub. See if we can push the
23558 // negation into a preceding instruction.
23559 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23560 // If the RHS of the sub is a XOR with one use and a constant, invert the
23561 // immediate. Then add one to the LHS of the sub so we can turn
23562 // X-Y -> X+~Y+1, saving one register.
23563 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23564 isa<ConstantSDNode>(Op1.getOperand(1))) {
23565 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23566 EVT VT = Op0.getValueType();
23567 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23569 DAG.getConstant(~XorC, VT));
23570 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23571 DAG.getConstant(C->getAPIntValue()+1, VT));
23575 // Try to synthesize horizontal adds from adds of shuffles.
23576 EVT VT = N->getValueType(0);
23577 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23578 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23579 isHorizontalBinOp(Op0, Op1, true))
23580 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23582 return OptimizeConditionalInDecrement(N, DAG);
23585 /// performVZEXTCombine - Performs build vector combines
23586 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23587 TargetLowering::DAGCombinerInfo &DCI,
23588 const X86Subtarget *Subtarget) {
23590 MVT VT = N->getSimpleValueType(0);
23591 SDValue Op = N->getOperand(0);
23592 MVT OpVT = Op.getSimpleValueType();
23593 MVT OpEltVT = OpVT.getVectorElementType();
23594 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23596 // (vzext (bitcast (vzext (x)) -> (vzext x)
23598 while (V.getOpcode() == ISD::BITCAST)
23599 V = V.getOperand(0);
23601 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23602 MVT InnerVT = V.getSimpleValueType();
23603 MVT InnerEltVT = InnerVT.getVectorElementType();
23605 // If the element sizes match exactly, we can just do one larger vzext. This
23606 // is always an exact type match as vzext operates on integer types.
23607 if (OpEltVT == InnerEltVT) {
23608 assert(OpVT == InnerVT && "Types must match for vzext!");
23609 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23612 // The only other way we can combine them is if only a single element of the
23613 // inner vzext is used in the input to the outer vzext.
23614 if (InnerEltVT.getSizeInBits() < InputBits)
23617 // In this case, the inner vzext is completely dead because we're going to
23618 // only look at bits inside of the low element. Just do the outer vzext on
23619 // a bitcast of the input to the inner.
23620 return DAG.getNode(X86ISD::VZEXT, DL, VT,
23621 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23624 // Check if we can bypass extracting and re-inserting an element of an input
23625 // vector. Essentialy:
23626 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23627 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23628 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23629 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23630 SDValue ExtractedV = V.getOperand(0);
23631 SDValue OrigV = ExtractedV.getOperand(0);
23632 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23633 if (ExtractIdx->getZExtValue() == 0) {
23634 MVT OrigVT = OrigV.getSimpleValueType();
23635 // Extract a subvector if necessary...
23636 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23637 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23638 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23639 OrigVT.getVectorNumElements() / Ratio);
23640 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23641 DAG.getIntPtrConstant(0));
23643 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23644 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23651 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23652 DAGCombinerInfo &DCI) const {
23653 SelectionDAG &DAG = DCI.DAG;
23654 switch (N->getOpcode()) {
23656 case ISD::EXTRACT_VECTOR_ELT:
23657 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23660 case X86ISD::SHRUNKBLEND:
23661 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23662 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
23663 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23664 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23665 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23666 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23667 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23670 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23671 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23672 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23673 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23674 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23675 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23676 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23677 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
23678 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23679 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23680 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23682 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23684 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23685 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23686 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23687 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23688 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23689 case ISD::ANY_EXTEND:
23690 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23691 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23692 case ISD::SIGN_EXTEND_INREG:
23693 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23694 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23695 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23696 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23697 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23698 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23699 case X86ISD::SHUFP: // Handle all target specific shuffles
23700 case X86ISD::PALIGNR:
23701 case X86ISD::UNPCKH:
23702 case X86ISD::UNPCKL:
23703 case X86ISD::MOVHLPS:
23704 case X86ISD::MOVLHPS:
23705 case X86ISD::PSHUFB:
23706 case X86ISD::PSHUFD:
23707 case X86ISD::PSHUFHW:
23708 case X86ISD::PSHUFLW:
23709 case X86ISD::MOVSS:
23710 case X86ISD::MOVSD:
23711 case X86ISD::VPERMILPI:
23712 case X86ISD::VPERM2X128:
23713 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23714 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23715 case ISD::INTRINSIC_WO_CHAIN:
23716 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23717 case X86ISD::INSERTPS: {
23718 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23719 return PerformINSERTPSCombine(N, DAG, Subtarget);
23722 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
23723 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23729 /// isTypeDesirableForOp - Return true if the target has native support for
23730 /// the specified value type and it is 'desirable' to use the type for the
23731 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23732 /// instruction encodings are longer and some i16 instructions are slow.
23733 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23734 if (!isTypeLegal(VT))
23736 if (VT != MVT::i16)
23743 case ISD::SIGN_EXTEND:
23744 case ISD::ZERO_EXTEND:
23745 case ISD::ANY_EXTEND:
23758 /// IsDesirableToPromoteOp - This method query the target whether it is
23759 /// beneficial for dag combiner to promote the specified node. If true, it
23760 /// should return the desired promotion type by reference.
23761 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23762 EVT VT = Op.getValueType();
23763 if (VT != MVT::i16)
23766 bool Promote = false;
23767 bool Commute = false;
23768 switch (Op.getOpcode()) {
23771 LoadSDNode *LD = cast<LoadSDNode>(Op);
23772 // If the non-extending load has a single use and it's not live out, then it
23773 // might be folded.
23774 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23775 Op.hasOneUse()*/) {
23776 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23777 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23778 // The only case where we'd want to promote LOAD (rather then it being
23779 // promoted as an operand is when it's only use is liveout.
23780 if (UI->getOpcode() != ISD::CopyToReg)
23787 case ISD::SIGN_EXTEND:
23788 case ISD::ZERO_EXTEND:
23789 case ISD::ANY_EXTEND:
23794 SDValue N0 = Op.getOperand(0);
23795 // Look out for (store (shl (load), x)).
23796 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23809 SDValue N0 = Op.getOperand(0);
23810 SDValue N1 = Op.getOperand(1);
23811 if (!Commute && MayFoldLoad(N1))
23813 // Avoid disabling potential load folding opportunities.
23814 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23816 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23826 //===----------------------------------------------------------------------===//
23827 // X86 Inline Assembly Support
23828 //===----------------------------------------------------------------------===//
23830 // Helper to match a string separated by whitespace.
23831 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23832 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23834 for (StringRef Piece : Pieces) {
23835 if (!S.startswith(Piece)) // Check if the piece matches.
23838 S = S.substr(Piece.size());
23839 StringRef::size_type Pos = S.find_first_not_of(" \t");
23840 if (Pos == 0) // We matched a prefix.
23849 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23851 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23852 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23853 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23854 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23856 if (AsmPieces.size() == 3)
23858 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23865 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23866 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23868 std::string AsmStr = IA->getAsmString();
23870 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23871 if (!Ty || Ty->getBitWidth() % 16 != 0)
23874 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23875 SmallVector<StringRef, 4> AsmPieces;
23876 SplitString(AsmStr, AsmPieces, ";\n");
23878 switch (AsmPieces.size()) {
23879 default: return false;
23881 // FIXME: this should verify that we are targeting a 486 or better. If not,
23882 // we will turn this bswap into something that will be lowered to logical
23883 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23884 // lower so don't worry about this.
23886 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23887 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23888 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23889 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23890 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23891 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23892 // No need to check constraints, nothing other than the equivalent of
23893 // "=r,0" would be valid here.
23894 return IntrinsicLowering::LowerToByteSwap(CI);
23897 // rorw $$8, ${0:w} --> llvm.bswap.i16
23898 if (CI->getType()->isIntegerTy(16) &&
23899 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23900 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23901 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23903 const std::string &ConstraintsStr = IA->getConstraintString();
23904 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23905 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23906 if (clobbersFlagRegisters(AsmPieces))
23907 return IntrinsicLowering::LowerToByteSwap(CI);
23911 if (CI->getType()->isIntegerTy(32) &&
23912 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23913 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23914 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23915 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23917 const std::string &ConstraintsStr = IA->getConstraintString();
23918 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23919 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23920 if (clobbersFlagRegisters(AsmPieces))
23921 return IntrinsicLowering::LowerToByteSwap(CI);
23924 if (CI->getType()->isIntegerTy(64)) {
23925 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23926 if (Constraints.size() >= 2 &&
23927 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23928 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23929 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23930 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23931 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23932 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23933 return IntrinsicLowering::LowerToByteSwap(CI);
23941 /// getConstraintType - Given a constraint letter, return the type of
23942 /// constraint it is for this target.
23943 X86TargetLowering::ConstraintType
23944 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23945 if (Constraint.size() == 1) {
23946 switch (Constraint[0]) {
23957 return C_RegisterClass;
23981 return TargetLowering::getConstraintType(Constraint);
23984 /// Examine constraint type and operand type and determine a weight value.
23985 /// This object must already have been set up with the operand type
23986 /// and the current alternative constraint selected.
23987 TargetLowering::ConstraintWeight
23988 X86TargetLowering::getSingleConstraintMatchWeight(
23989 AsmOperandInfo &info, const char *constraint) const {
23990 ConstraintWeight weight = CW_Invalid;
23991 Value *CallOperandVal = info.CallOperandVal;
23992 // If we don't have a value, we can't do a match,
23993 // but allow it at the lowest weight.
23994 if (!CallOperandVal)
23996 Type *type = CallOperandVal->getType();
23997 // Look at the constraint type.
23998 switch (*constraint) {
24000 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24011 if (CallOperandVal->getType()->isIntegerTy())
24012 weight = CW_SpecificReg;
24017 if (type->isFloatingPointTy())
24018 weight = CW_SpecificReg;
24021 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24022 weight = CW_SpecificReg;
24026 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24027 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24028 weight = CW_Register;
24031 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24032 if (C->getZExtValue() <= 31)
24033 weight = CW_Constant;
24037 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24038 if (C->getZExtValue() <= 63)
24039 weight = CW_Constant;
24043 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24044 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24045 weight = CW_Constant;
24049 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24050 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24051 weight = CW_Constant;
24055 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24056 if (C->getZExtValue() <= 3)
24057 weight = CW_Constant;
24061 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24062 if (C->getZExtValue() <= 0xff)
24063 weight = CW_Constant;
24068 if (dyn_cast<ConstantFP>(CallOperandVal)) {
24069 weight = CW_Constant;
24073 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24074 if ((C->getSExtValue() >= -0x80000000LL) &&
24075 (C->getSExtValue() <= 0x7fffffffLL))
24076 weight = CW_Constant;
24080 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24081 if (C->getZExtValue() <= 0xffffffff)
24082 weight = CW_Constant;
24089 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24090 /// with another that has more specific requirements based on the type of the
24091 /// corresponding operand.
24092 const char *X86TargetLowering::
24093 LowerXConstraint(EVT ConstraintVT) const {
24094 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24095 // 'f' like normal targets.
24096 if (ConstraintVT.isFloatingPoint()) {
24097 if (Subtarget->hasSSE2())
24099 if (Subtarget->hasSSE1())
24103 return TargetLowering::LowerXConstraint(ConstraintVT);
24106 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24107 /// vector. If it is invalid, don't add anything to Ops.
24108 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24109 std::string &Constraint,
24110 std::vector<SDValue>&Ops,
24111 SelectionDAG &DAG) const {
24114 // Only support length 1 constraints for now.
24115 if (Constraint.length() > 1) return;
24117 char ConstraintLetter = Constraint[0];
24118 switch (ConstraintLetter) {
24121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24122 if (C->getZExtValue() <= 31) {
24123 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24130 if (C->getZExtValue() <= 63) {
24131 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24137 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24138 if (isInt<8>(C->getSExtValue())) {
24139 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24145 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24146 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24147 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24148 Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24154 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24155 if (C->getZExtValue() <= 3) {
24156 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24162 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24163 if (C->getZExtValue() <= 255) {
24164 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24170 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24171 if (C->getZExtValue() <= 127) {
24172 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24178 // 32-bit signed value
24179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24180 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24181 C->getSExtValue())) {
24182 // Widen to 64 bits here to get it sign extended.
24183 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24186 // FIXME gcc accepts some relocatable values here too, but only in certain
24187 // memory models; it's complicated.
24192 // 32-bit unsigned value
24193 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24194 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24195 C->getZExtValue())) {
24196 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24200 // FIXME gcc accepts some relocatable values here too, but only in certain
24201 // memory models; it's complicated.
24205 // Literal immediates are always ok.
24206 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24207 // Widen to 64 bits here to get it sign extended.
24208 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24212 // In any sort of PIC mode addresses need to be computed at runtime by
24213 // adding in a register or some sort of table lookup. These can't
24214 // be used as immediates.
24215 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24218 // If we are in non-pic codegen mode, we allow the address of a global (with
24219 // an optional displacement) to be used with 'i'.
24220 GlobalAddressSDNode *GA = nullptr;
24221 int64_t Offset = 0;
24223 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24225 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24226 Offset += GA->getOffset();
24228 } else if (Op.getOpcode() == ISD::ADD) {
24229 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24230 Offset += C->getZExtValue();
24231 Op = Op.getOperand(0);
24234 } else if (Op.getOpcode() == ISD::SUB) {
24235 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24236 Offset += -C->getZExtValue();
24237 Op = Op.getOperand(0);
24242 // Otherwise, this isn't something we can handle, reject it.
24246 const GlobalValue *GV = GA->getGlobal();
24247 // If we require an extra load to get this address, as in PIC mode, we
24248 // can't accept it.
24249 if (isGlobalStubReference(
24250 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24253 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24254 GA->getValueType(0), Offset);
24259 if (Result.getNode()) {
24260 Ops.push_back(Result);
24263 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24266 std::pair<unsigned, const TargetRegisterClass *>
24267 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24268 const std::string &Constraint,
24270 // First, see if this is a constraint that directly corresponds to an LLVM
24272 if (Constraint.size() == 1) {
24273 // GCC Constraint Letters
24274 switch (Constraint[0]) {
24276 // TODO: Slight differences here in allocation order and leaving
24277 // RIP in the class. Do they matter any more here than they do
24278 // in the normal allocation?
24279 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24280 if (Subtarget->is64Bit()) {
24281 if (VT == MVT::i32 || VT == MVT::f32)
24282 return std::make_pair(0U, &X86::GR32RegClass);
24283 if (VT == MVT::i16)
24284 return std::make_pair(0U, &X86::GR16RegClass);
24285 if (VT == MVT::i8 || VT == MVT::i1)
24286 return std::make_pair(0U, &X86::GR8RegClass);
24287 if (VT == MVT::i64 || VT == MVT::f64)
24288 return std::make_pair(0U, &X86::GR64RegClass);
24291 // 32-bit fallthrough
24292 case 'Q': // Q_REGS
24293 if (VT == MVT::i32 || VT == MVT::f32)
24294 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24295 if (VT == MVT::i16)
24296 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24297 if (VT == MVT::i8 || VT == MVT::i1)
24298 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24299 if (VT == MVT::i64)
24300 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24302 case 'r': // GENERAL_REGS
24303 case 'l': // INDEX_REGS
24304 if (VT == MVT::i8 || VT == MVT::i1)
24305 return std::make_pair(0U, &X86::GR8RegClass);
24306 if (VT == MVT::i16)
24307 return std::make_pair(0U, &X86::GR16RegClass);
24308 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24309 return std::make_pair(0U, &X86::GR32RegClass);
24310 return std::make_pair(0U, &X86::GR64RegClass);
24311 case 'R': // LEGACY_REGS
24312 if (VT == MVT::i8 || VT == MVT::i1)
24313 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24314 if (VT == MVT::i16)
24315 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24316 if (VT == MVT::i32 || !Subtarget->is64Bit())
24317 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24318 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24319 case 'f': // FP Stack registers.
24320 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24321 // value to the correct fpstack register class.
24322 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24323 return std::make_pair(0U, &X86::RFP32RegClass);
24324 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24325 return std::make_pair(0U, &X86::RFP64RegClass);
24326 return std::make_pair(0U, &X86::RFP80RegClass);
24327 case 'y': // MMX_REGS if MMX allowed.
24328 if (!Subtarget->hasMMX()) break;
24329 return std::make_pair(0U, &X86::VR64RegClass);
24330 case 'Y': // SSE_REGS if SSE2 allowed
24331 if (!Subtarget->hasSSE2()) break;
24333 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24334 if (!Subtarget->hasSSE1()) break;
24336 switch (VT.SimpleTy) {
24338 // Scalar SSE types.
24341 return std::make_pair(0U, &X86::FR32RegClass);
24344 return std::make_pair(0U, &X86::FR64RegClass);
24352 return std::make_pair(0U, &X86::VR128RegClass);
24360 return std::make_pair(0U, &X86::VR256RegClass);
24365 return std::make_pair(0U, &X86::VR512RegClass);
24371 // Use the default implementation in TargetLowering to convert the register
24372 // constraint into a member of a register class.
24373 std::pair<unsigned, const TargetRegisterClass*> Res;
24374 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24376 // Not found as a standard register?
24378 // Map st(0) -> st(7) -> ST0
24379 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24380 tolower(Constraint[1]) == 's' &&
24381 tolower(Constraint[2]) == 't' &&
24382 Constraint[3] == '(' &&
24383 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24384 Constraint[5] == ')' &&
24385 Constraint[6] == '}') {
24387 Res.first = X86::FP0+Constraint[4]-'0';
24388 Res.second = &X86::RFP80RegClass;
24392 // GCC allows "st(0)" to be called just plain "st".
24393 if (StringRef("{st}").equals_lower(Constraint)) {
24394 Res.first = X86::FP0;
24395 Res.second = &X86::RFP80RegClass;
24400 if (StringRef("{flags}").equals_lower(Constraint)) {
24401 Res.first = X86::EFLAGS;
24402 Res.second = &X86::CCRRegClass;
24406 // 'A' means EAX + EDX.
24407 if (Constraint == "A") {
24408 Res.first = X86::EAX;
24409 Res.second = &X86::GR32_ADRegClass;
24415 // Otherwise, check to see if this is a register class of the wrong value
24416 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24417 // turn into {ax},{dx}.
24418 if (Res.second->hasType(VT))
24419 return Res; // Correct type already, nothing to do.
24421 // All of the single-register GCC register classes map their values onto
24422 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24423 // really want an 8-bit or 32-bit register, map to the appropriate register
24424 // class and return the appropriate register.
24425 if (Res.second == &X86::GR16RegClass) {
24426 if (VT == MVT::i8 || VT == MVT::i1) {
24427 unsigned DestReg = 0;
24428 switch (Res.first) {
24430 case X86::AX: DestReg = X86::AL; break;
24431 case X86::DX: DestReg = X86::DL; break;
24432 case X86::CX: DestReg = X86::CL; break;
24433 case X86::BX: DestReg = X86::BL; break;
24436 Res.first = DestReg;
24437 Res.second = &X86::GR8RegClass;
24439 } else if (VT == MVT::i32 || VT == MVT::f32) {
24440 unsigned DestReg = 0;
24441 switch (Res.first) {
24443 case X86::AX: DestReg = X86::EAX; break;
24444 case X86::DX: DestReg = X86::EDX; break;
24445 case X86::CX: DestReg = X86::ECX; break;
24446 case X86::BX: DestReg = X86::EBX; break;
24447 case X86::SI: DestReg = X86::ESI; break;
24448 case X86::DI: DestReg = X86::EDI; break;
24449 case X86::BP: DestReg = X86::EBP; break;
24450 case X86::SP: DestReg = X86::ESP; break;
24453 Res.first = DestReg;
24454 Res.second = &X86::GR32RegClass;
24456 } else if (VT == MVT::i64 || VT == MVT::f64) {
24457 unsigned DestReg = 0;
24458 switch (Res.first) {
24460 case X86::AX: DestReg = X86::RAX; break;
24461 case X86::DX: DestReg = X86::RDX; break;
24462 case X86::CX: DestReg = X86::RCX; break;
24463 case X86::BX: DestReg = X86::RBX; break;
24464 case X86::SI: DestReg = X86::RSI; break;
24465 case X86::DI: DestReg = X86::RDI; break;
24466 case X86::BP: DestReg = X86::RBP; break;
24467 case X86::SP: DestReg = X86::RSP; break;
24470 Res.first = DestReg;
24471 Res.second = &X86::GR64RegClass;
24474 } else if (Res.second == &X86::FR32RegClass ||
24475 Res.second == &X86::FR64RegClass ||
24476 Res.second == &X86::VR128RegClass ||
24477 Res.second == &X86::VR256RegClass ||
24478 Res.second == &X86::FR32XRegClass ||
24479 Res.second == &X86::FR64XRegClass ||
24480 Res.second == &X86::VR128XRegClass ||
24481 Res.second == &X86::VR256XRegClass ||
24482 Res.second == &X86::VR512RegClass) {
24483 // Handle references to XMM physical registers that got mapped into the
24484 // wrong class. This can happen with constraints like {xmm0} where the
24485 // target independent register mapper will just pick the first match it can
24486 // find, ignoring the required type.
24488 if (VT == MVT::f32 || VT == MVT::i32)
24489 Res.second = &X86::FR32RegClass;
24490 else if (VT == MVT::f64 || VT == MVT::i64)
24491 Res.second = &X86::FR64RegClass;
24492 else if (X86::VR128RegClass.hasType(VT))
24493 Res.second = &X86::VR128RegClass;
24494 else if (X86::VR256RegClass.hasType(VT))
24495 Res.second = &X86::VR256RegClass;
24496 else if (X86::VR512RegClass.hasType(VT))
24497 Res.second = &X86::VR512RegClass;
24503 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24505 // Scaling factors are not free at all.
24506 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24507 // will take 2 allocations in the out of order engine instead of 1
24508 // for plain addressing mode, i.e. inst (reg1).
24510 // vaddps (%rsi,%drx), %ymm0, %ymm1
24511 // Requires two allocations (one for the load, one for the computation)
24513 // vaddps (%rsi), %ymm0, %ymm1
24514 // Requires just 1 allocation, i.e., freeing allocations for other operations
24515 // and having less micro operations to execute.
24517 // For some X86 architectures, this is even worse because for instance for
24518 // stores, the complex addressing mode forces the instruction to use the
24519 // "load" ports instead of the dedicated "store" port.
24520 // E.g., on Haswell:
24521 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24522 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24523 if (isLegalAddressingMode(AM, Ty))
24524 // Scale represents reg2 * scale, thus account for 1
24525 // as soon as we use a second register.
24526 return AM.Scale != 0;
24530 bool X86TargetLowering::isTargetFTOL() const {
24531 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();