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 "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62 "x86-experimental-vector-widening-legalization", cl::init(false),
63 cl::desc("Enable an experimental vector type legalization through widening "
64 "rather than promotion."),
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68 "x86-experimental-vector-shuffle-lowering", cl::init(false),
69 cl::desc("Enable an experimental vector shuffle lowering code path."),
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77 SelectionDAG &DAG, SDLoc dl,
78 unsigned vectorWidth) {
79 assert((vectorWidth == 128 || vectorWidth == 256) &&
80 "Unsupported vector width");
81 EVT VT = Vec.getValueType();
82 EVT ElVT = VT.getVectorElementType();
83 unsigned Factor = VT.getSizeInBits()/vectorWidth;
84 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85 VT.getVectorNumElements()/Factor);
87 // Extract from UNDEF is UNDEF.
88 if (Vec.getOpcode() == ISD::UNDEF)
89 return DAG.getUNDEF(ResultVT);
91 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
92 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94 // This is the index of the first element of the vectorWidth-bit chunk
96 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99 // If the input is a buildvector just emit a smaller one.
100 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
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 bounday. 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,
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 bounday. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163 unsigned IdxVal, SelectionDAG &DAG,
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170 unsigned IdxVal, SelectionDAG &DAG,
172 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181 unsigned NumElems, SelectionDAG &DAG,
183 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188 unsigned NumElems, SelectionDAG &DAG,
190 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195 if (TT.isOSBinFormatMachO()) {
196 if (TT.getArch() == Triple::x86_64)
197 return new X86_64MachoTargetObjectFile();
198 return new TargetLoweringObjectFileMachO();
202 return new X86LinuxTargetObjectFile();
203 if (TT.isOSBinFormatELF())
204 return new TargetLoweringObjectFileELF();
205 if (TT.isKnownWindowsMSVCEnvironment())
206 return new X86WindowsTargetObjectFile();
207 if (TT.isOSBinFormatCOFF())
208 return new TargetLoweringObjectFileCOFF();
209 llvm_unreachable("unknown subtarget type");
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216 Subtarget = &TM.getSubtarget<X86Subtarget>();
217 X86ScalarSSEf64 = Subtarget->hasSSE2();
218 X86ScalarSSEf32 = Subtarget->hasSSE1();
219 TD = getDataLayout();
221 resetOperationActions();
224 void X86TargetLowering::resetOperationActions() {
225 const TargetMachine &TM = getTargetMachine();
226 static bool FirstTimeThrough = true;
228 // If none of the target options have changed, then we don't need to reset the
229 // operation actions.
230 if (!FirstTimeThrough && TO == TM.Options) return;
232 if (!FirstTimeThrough) {
233 // Reinitialize the actions.
235 FirstTimeThrough = false;
240 // Set up the TargetLowering object.
241 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243 // X86 is weird, it always uses i8 for shift amounts and setcc results.
244 setBooleanContents(ZeroOrOneBooleanContent);
245 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 // For 64-bit since we have so many registers use the ILP scheduler, for
249 // 32-bit code use the register pressure specific scheduling.
250 // For Atom, always use ILP scheduling.
251 if (Subtarget->isAtom())
252 setSchedulingPreference(Sched::ILP);
253 else if (Subtarget->is64Bit())
254 setSchedulingPreference(Sched::ILP);
256 setSchedulingPreference(Sched::RegPressure);
257 const X86RegisterInfo *RegInfo =
258 TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261 // Bypass expensive divides on Atom when compiling with O2
262 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263 addBypassSlowDiv(32, 8);
264 if (Subtarget->is64Bit())
265 addBypassSlowDiv(64, 16);
268 if (Subtarget->isTargetKnownWindowsMSVC()) {
269 // Setup Windows compiler runtime calls.
270 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272 setLibcallName(RTLIB::SREM_I64, "_allrem");
273 setLibcallName(RTLIB::UREM_I64, "_aullrem");
274 setLibcallName(RTLIB::MUL_I64, "_allmul");
275 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281 // The _ftol2 runtime function has an unusual calling conv, which
282 // is modeled by a special pseudo-instruction.
283 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289 if (Subtarget->isTargetDarwin()) {
290 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291 setUseUnderscoreSetJmp(false);
292 setUseUnderscoreLongJmp(false);
293 } else if (Subtarget->isTargetWindowsGNU()) {
294 // MS runtime is weird: it exports _setjmp, but longjmp!
295 setUseUnderscoreSetJmp(true);
296 setUseUnderscoreLongJmp(false);
298 setUseUnderscoreSetJmp(true);
299 setUseUnderscoreLongJmp(true);
302 // Set up the register classes.
303 addRegisterClass(MVT::i8, &X86::GR8RegClass);
304 addRegisterClass(MVT::i16, &X86::GR16RegClass);
305 addRegisterClass(MVT::i32, &X86::GR32RegClass);
306 if (Subtarget->is64Bit())
307 addRegisterClass(MVT::i64, &X86::GR64RegClass);
309 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311 // We don't accept any truncstore of integer registers.
312 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
319 // SETOEQ and SETUNE require checking two conditions.
320 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
330 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
336 } else if (!TM.Options.UseSoftFloat) {
337 // We have an algorithm for SSE2->double, and we turn this into a
338 // 64-bit FILD followed by conditional FADD for other targets.
339 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
340 // We have an algorithm for SSE2, and we turn this into a 64-bit
341 // FILD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
345 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
350 if (!TM.Options.UseSoftFloat) {
351 // SSE has no i16 to fp conversion, only i32
352 if (X86ScalarSSEf32) {
353 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
354 // f32 and f64 cases are Legal, f80 case is not
355 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
357 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
365 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
366 // are Legal, f80 is custom lowered.
367 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
368 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
370 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
375 if (X86ScalarSSEf32) {
376 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
377 // f32 and f64 cases are Legal, f80 case is not
378 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
380 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
384 // Handle FP_TO_UINT by promoting the destination to a larger signed
386 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
387 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
390 if (Subtarget->is64Bit()) {
391 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
393 } else if (!TM.Options.UseSoftFloat) {
394 // Since AVX is a superset of SSE3, only check for SSE here.
395 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396 // Expand FP_TO_UINT into a select.
397 // FIXME: We would like to use a Custom expander here eventually to do
398 // the optimal thing for SSE vs. the default expansion in the legalizer.
399 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
401 // With SSE3 we can use fisttpll to convert to a signed i64; without
402 // SSE, we're stuck with a fistpll.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
406 if (isTargetFTOL()) {
407 // Use the _ftol2 runtime function, which has a pseudo-instruction
408 // to handle its weird calling convention.
409 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
412 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413 if (!X86ScalarSSEf64) {
414 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
415 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
418 // Without SSE, i64->f64 goes through memory.
419 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
423 // Scalar integer divide and remainder are lowered to use operations that
424 // produce two results, to match the available instructions. This exposes
425 // the two-result form to trivial CSE, which is able to combine x/y and x%y
426 // into a single instruction.
428 // Scalar integer multiply-high is also lowered to use two-result
429 // operations, to match the available instructions. However, plain multiply
430 // (low) operations are left as Legal, as there are single-result
431 // instructions for this in x86. Using the two-result multiply instructions
432 // when both high and low results are needed must be arranged by dagcombine.
433 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435 setOperationAction(ISD::MULHS, VT, Expand);
436 setOperationAction(ISD::MULHU, VT, Expand);
437 setOperationAction(ISD::SDIV, VT, Expand);
438 setOperationAction(ISD::UDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UREM, VT, Expand);
442 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443 setOperationAction(ISD::ADDC, VT, Custom);
444 setOperationAction(ISD::ADDE, VT, Custom);
445 setOperationAction(ISD::SUBC, VT, Custom);
446 setOperationAction(ISD::SUBE, VT, Custom);
449 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
450 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
451 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
452 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
454 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
470 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
471 setOperationAction(ISD::FREM , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f64 , Expand);
473 setOperationAction(ISD::FREM , MVT::f80 , Expand);
474 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
476 // Promote the i8 variants and force them on up to i32 which has a shorter
478 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
482 if (Subtarget->hasBMI()) {
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
494 if (Subtarget->hasLZCNT()) {
495 // When promoting the i8 variants, force them to i32 for a shorter
497 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
498 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
500 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
507 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
512 if (Subtarget->is64Bit()) {
513 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518 // Special handling for half-precision floating point conversions.
519 // If we don't have F16C support, then lower half float conversions
520 // into library calls.
521 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
526 // There's never any support for operations beyond MVT::f32.
527 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537 if (Subtarget->hasPOPCNT()) {
538 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
540 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
541 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
542 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
543 if (Subtarget->is64Bit())
544 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
547 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
549 if (!Subtarget->hasMOVBE())
550 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
552 // These should be promoted to a larger select which is supported.
553 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
554 // X86 wants to expand cmov itself.
555 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
556 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
557 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
558 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
559 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
560 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
561 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
562 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
563 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
564 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
565 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
566 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
569 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
571 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
572 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574 // support continuation, user-level threading, and etc.. As a result, no
575 // other SjLj exception interfaces are implemented and please don't build
576 // your own exception handling based on them.
577 // LLVM/Clang supports zero-cost DWARF exception handling.
578 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
582 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
583 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
584 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
585 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
586 if (Subtarget->is64Bit())
587 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
589 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
590 if (Subtarget->is64Bit()) {
591 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
592 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
593 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
594 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
595 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
597 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
599 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
600 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
601 if (Subtarget->is64Bit()) {
602 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
603 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
604 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
607 if (Subtarget->hasSSE1())
608 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
610 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
612 // Expand certain atomics
613 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
620 if (Subtarget->hasCmpxchg16b()) {
621 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
624 // FIXME - use subtarget debug flags
625 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
630 if (Subtarget->is64Bit()) {
631 setExceptionPointerRegister(X86::RAX);
632 setExceptionSelectorRegister(X86::RDX);
634 setExceptionPointerRegister(X86::EAX);
635 setExceptionSelectorRegister(X86::EDX);
637 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643 setOperationAction(ISD::TRAP, MVT::Other, Legal);
644 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647 setOperationAction(ISD::VASTART , MVT::Other, Custom);
648 setOperationAction(ISD::VAEND , MVT::Other, Expand);
649 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650 // TargetInfo::X86_64ABIBuiltinVaList
651 setOperationAction(ISD::VAARG , MVT::Other, Custom);
652 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
654 // TargetInfo::CharPtrBuiltinVaList
655 setOperationAction(ISD::VAARG , MVT::Other, Expand);
656 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
659 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
660 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
662 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663 MVT::i64 : MVT::i32, Custom);
665 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666 // f32 and f64 use SSE.
667 // Set up the FP register classes.
668 addRegisterClass(MVT::f32, &X86::FR32RegClass);
669 addRegisterClass(MVT::f64, &X86::FR64RegClass);
671 // Use ANDPD to simulate FABS.
672 setOperationAction(ISD::FABS , MVT::f64, Custom);
673 setOperationAction(ISD::FABS , MVT::f32, Custom);
675 // Use XORP to simulate FNEG.
676 setOperationAction(ISD::FNEG , MVT::f64, Custom);
677 setOperationAction(ISD::FNEG , MVT::f32, Custom);
679 // Use ANDPD and ORPD to simulate FCOPYSIGN.
680 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
683 // Lower this to FGETSIGNx86 plus an AND.
684 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
687 // We don't support sin/cos/fmod
688 setOperationAction(ISD::FSIN , MVT::f64, Expand);
689 setOperationAction(ISD::FCOS , MVT::f64, Expand);
690 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691 setOperationAction(ISD::FSIN , MVT::f32, Expand);
692 setOperationAction(ISD::FCOS , MVT::f32, Expand);
693 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
695 // Expand FP immediates into loads from the stack, except for the special
697 addLegalFPImmediate(APFloat(+0.0)); // xorpd
698 addLegalFPImmediate(APFloat(+0.0f)); // xorps
699 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700 // Use SSE for f32, x87 for f64.
701 // Set up the FP register classes.
702 addRegisterClass(MVT::f32, &X86::FR32RegClass);
703 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
705 // Use ANDPS to simulate FABS.
706 setOperationAction(ISD::FABS , MVT::f32, Custom);
708 // Use XORP to simulate FNEG.
709 setOperationAction(ISD::FNEG , MVT::f32, Custom);
711 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
713 // Use ANDPS and ORPS to simulate FCOPYSIGN.
714 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
717 // We don't support sin/cos/fmod
718 setOperationAction(ISD::FSIN , MVT::f32, Expand);
719 setOperationAction(ISD::FCOS , MVT::f32, Expand);
720 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
722 // Special cases we handle for FP constants.
723 addLegalFPImmediate(APFloat(+0.0f)); // xorps
724 addLegalFPImmediate(APFloat(+0.0)); // FLD0
725 addLegalFPImmediate(APFloat(+1.0)); // FLD1
726 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 } else if (!TM.Options.UseSoftFloat) {
735 // f32 and f64 in x87.
736 // Set up the FP register classes.
737 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
740 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
741 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
742 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
745 if (!TM.Options.UnsafeFPMath) {
746 setOperationAction(ISD::FSIN , MVT::f64, Expand);
747 setOperationAction(ISD::FSIN , MVT::f32, Expand);
748 setOperationAction(ISD::FCOS , MVT::f64, Expand);
749 setOperationAction(ISD::FCOS , MVT::f32, Expand);
750 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
753 addLegalFPImmediate(APFloat(+0.0)); // FLD0
754 addLegalFPImmediate(APFloat(+1.0)); // FLD1
755 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
763 // We don't support FMA.
764 setOperationAction(ISD::FMA, MVT::f64, Expand);
765 setOperationAction(ISD::FMA, MVT::f32, Expand);
767 // Long double always uses X87.
768 if (!TM.Options.UseSoftFloat) {
769 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
771 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
773 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774 addLegalFPImmediate(TmpFlt); // FLD0
776 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
779 APFloat TmpFlt2(+1.0);
780 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
782 addLegalFPImmediate(TmpFlt2); // FLD1
783 TmpFlt2.changeSign();
784 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
787 if (!TM.Options.UnsafeFPMath) {
788 setOperationAction(ISD::FSIN , MVT::f80, Expand);
789 setOperationAction(ISD::FCOS , MVT::f80, Expand);
790 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
793 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
795 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796 setOperationAction(ISD::FRINT, MVT::f80, Expand);
797 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798 setOperationAction(ISD::FMA, MVT::f80, Expand);
801 // Always use a library call for pow.
802 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
803 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
804 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
806 setOperationAction(ISD::FLOG, MVT::f80, Expand);
807 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809 setOperationAction(ISD::FEXP, MVT::f80, Expand);
810 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
812 // First set operation action for all vector types to either promote
813 // (for widening) or expand (for scalarization). Then we will selectively
814 // turn on ones that can be effectively codegen'd.
815 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817 MVT VT = (MVT::SimpleValueType)i;
818 setOperationAction(ISD::ADD , VT, Expand);
819 setOperationAction(ISD::SUB , VT, Expand);
820 setOperationAction(ISD::FADD, VT, Expand);
821 setOperationAction(ISD::FNEG, VT, Expand);
822 setOperationAction(ISD::FSUB, VT, Expand);
823 setOperationAction(ISD::MUL , VT, Expand);
824 setOperationAction(ISD::FMUL, VT, Expand);
825 setOperationAction(ISD::SDIV, VT, Expand);
826 setOperationAction(ISD::UDIV, VT, Expand);
827 setOperationAction(ISD::FDIV, VT, Expand);
828 setOperationAction(ISD::SREM, VT, Expand);
829 setOperationAction(ISD::UREM, VT, Expand);
830 setOperationAction(ISD::LOAD, VT, Expand);
831 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836 setOperationAction(ISD::FABS, VT, Expand);
837 setOperationAction(ISD::FSIN, VT, Expand);
838 setOperationAction(ISD::FSINCOS, VT, Expand);
839 setOperationAction(ISD::FCOS, VT, Expand);
840 setOperationAction(ISD::FSINCOS, VT, Expand);
841 setOperationAction(ISD::FREM, VT, Expand);
842 setOperationAction(ISD::FMA, VT, Expand);
843 setOperationAction(ISD::FPOWI, VT, Expand);
844 setOperationAction(ISD::FSQRT, VT, Expand);
845 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846 setOperationAction(ISD::FFLOOR, VT, Expand);
847 setOperationAction(ISD::FCEIL, VT, Expand);
848 setOperationAction(ISD::FTRUNC, VT, Expand);
849 setOperationAction(ISD::FRINT, VT, Expand);
850 setOperationAction(ISD::FNEARBYINT, VT, Expand);
851 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852 setOperationAction(ISD::MULHS, VT, Expand);
853 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854 setOperationAction(ISD::MULHU, VT, Expand);
855 setOperationAction(ISD::SDIVREM, VT, Expand);
856 setOperationAction(ISD::UDIVREM, VT, Expand);
857 setOperationAction(ISD::FPOW, VT, Expand);
858 setOperationAction(ISD::CTPOP, VT, Expand);
859 setOperationAction(ISD::CTTZ, VT, Expand);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861 setOperationAction(ISD::CTLZ, VT, Expand);
862 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863 setOperationAction(ISD::SHL, VT, Expand);
864 setOperationAction(ISD::SRA, VT, Expand);
865 setOperationAction(ISD::SRL, VT, Expand);
866 setOperationAction(ISD::ROTL, VT, Expand);
867 setOperationAction(ISD::ROTR, VT, Expand);
868 setOperationAction(ISD::BSWAP, VT, Expand);
869 setOperationAction(ISD::SETCC, VT, Expand);
870 setOperationAction(ISD::FLOG, VT, Expand);
871 setOperationAction(ISD::FLOG2, VT, Expand);
872 setOperationAction(ISD::FLOG10, VT, Expand);
873 setOperationAction(ISD::FEXP, VT, Expand);
874 setOperationAction(ISD::FEXP2, VT, Expand);
875 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880 setOperationAction(ISD::TRUNCATE, VT, Expand);
881 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884 setOperationAction(ISD::VSELECT, VT, Expand);
885 setOperationAction(ISD::SELECT_CC, VT, Expand);
886 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888 setTruncStoreAction(VT,
889 (MVT::SimpleValueType)InnerVT, Expand);
890 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
893 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894 // we have to deal with them whether we ask for Expansion or not. Setting
895 // Expand causes its own optimisation problems though, so leave them legal.
896 if (VT.getVectorElementType() == MVT::i1)
897 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
900 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901 // with -msoft-float, disable use of MMX as well.
902 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904 // No operations on x86mmx supported, everything uses intrinsics.
907 // MMX-sized vectors (other than x86mmx) are expected to be expanded
908 // into smaller operations.
909 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
910 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
911 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
912 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
913 setOperationAction(ISD::AND, MVT::v8i8, Expand);
914 setOperationAction(ISD::AND, MVT::v4i16, Expand);
915 setOperationAction(ISD::AND, MVT::v2i32, Expand);
916 setOperationAction(ISD::AND, MVT::v1i64, Expand);
917 setOperationAction(ISD::OR, MVT::v8i8, Expand);
918 setOperationAction(ISD::OR, MVT::v4i16, Expand);
919 setOperationAction(ISD::OR, MVT::v2i32, Expand);
920 setOperationAction(ISD::OR, MVT::v1i64, Expand);
921 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
922 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
923 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
924 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
930 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
931 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
932 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
933 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
934 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
936 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
937 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
939 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
942 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
943 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
944 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
945 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
946 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
947 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
948 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
949 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
950 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
951 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
956 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
959 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960 // registers cannot be used even for integer operations.
961 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
966 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
967 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
968 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
969 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
970 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
971 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
972 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
973 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
974 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
975 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
976 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
977 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
978 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
979 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
980 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
981 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
982 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
983 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
984 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
985 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
986 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
987 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
990 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
991 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
992 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
995 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to custom lower non-power-of-2 vectors
1004 if (!isPowerOf2_32(VT.getVectorNumElements()))
1006 // Do not attempt to custom lower non-128-bit vectors
1007 if (!VT.is128BitVector())
1009 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1010 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1014 // We support custom legalizing of sext and anyext loads for specific
1015 // memory vector types which we can load as a scalar (or sequence of
1016 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017 // loads these must work with a single scalar load.
1018 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019 if (Subtarget->is64Bit()) {
1020 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1033 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1034 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1035 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1037 if (Subtarget->is64Bit()) {
1038 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1039 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1042 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044 MVT VT = (MVT::SimpleValueType)i;
1046 // Do not attempt to promote non-128-bit vectors
1047 if (!VT.is128BitVector())
1050 setOperationAction(ISD::AND, VT, Promote);
1051 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1052 setOperationAction(ISD::OR, VT, Promote);
1053 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1054 setOperationAction(ISD::XOR, VT, Promote);
1055 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1056 setOperationAction(ISD::LOAD, VT, Promote);
1057 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1058 setOperationAction(ISD::SELECT, VT, Promote);
1059 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1062 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1064 // Custom lower v2i64 and v2f64 selects.
1065 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1066 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1067 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1068 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1070 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1073 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1074 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1075 // As there is no 64-bit GPR available, we need build a special custom
1076 // sequence to convert from v2i32 to v2f32.
1077 if (!Subtarget->is64Bit())
1078 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1080 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1081 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1083 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1085 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1086 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1087 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1090 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1092 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1093 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1094 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1095 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1096 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1097 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1098 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1099 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1100 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1102 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1103 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1104 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1105 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1106 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1107 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1108 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1109 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1110 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1111 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1113 // FIXME: Do we need to handle scalar-to-vector here?
1114 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1116 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1117 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1118 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1119 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1120 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1121 // There is no BLENDI for byte vectors. We don't need to custom lower
1122 // some vselects for now.
1123 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1125 // SSE41 brings specific instructions for doing vector sign extend even in
1126 // cases where we don't have SRA.
1127 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1131 // i8 and i16 vectors are custom , because the source register and source
1132 // source memory operand types are not the same width. f32 vectors are
1133 // custom since the immediate controlling the insert encodes additional
1135 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1137 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1138 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1140 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1145 // FIXME: these should be Legal but thats only for the case where
1146 // the index is constant. For now custom expand to deal with that.
1147 if (Subtarget->is64Bit()) {
1148 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1149 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1153 if (Subtarget->hasSSE2()) {
1154 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1155 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1157 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1158 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1160 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1161 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1163 // In the customized shift lowering, the legal cases in AVX2 will be
1165 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1166 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1168 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1169 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1171 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1174 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1176 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1178 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1179 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1180 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1182 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1183 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1184 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1186 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1187 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1188 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1189 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1190 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1192 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1193 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1194 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1195 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1196 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1197 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1199 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1200 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1201 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1202 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1203 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1205 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1206 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1208 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1209 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1210 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1212 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213 // even though v8i16 is a legal type.
1214 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1215 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1216 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1218 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1219 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1220 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1222 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1223 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1225 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1227 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1228 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1231 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1233 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1234 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1237 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1238 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1239 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1241 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1242 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1243 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1245 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1246 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1247 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1248 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1250 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1251 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1252 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1253 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1254 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1255 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1256 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1257 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1258 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1259 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1260 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1261 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1263 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1265 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1266 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1267 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1268 setOperationAction(ISD::FMA, MVT::f32, Legal);
1269 setOperationAction(ISD::FMA, MVT::f64, Legal);
1272 if (Subtarget->hasInt256()) {
1273 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1274 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1275 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1276 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1278 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1279 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1280 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1281 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1283 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1284 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1285 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1286 // Don't lower v32i8 because there is no 128-bit byte mul
1288 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1289 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1290 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1291 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1293 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1294 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1296 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1297 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1298 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1299 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1301 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1302 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1303 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1304 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1306 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1307 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1308 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1309 // Don't lower v32i8 because there is no 128-bit byte mul
1312 // In the customized shift lowering, the legal cases in AVX2 will be
1314 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1315 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1317 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1318 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1320 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1322 // Custom lower several nodes for 256-bit types.
1323 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325 MVT VT = (MVT::SimpleValueType)i;
1327 // Extract subvector is special because the value type
1328 // (result) is 128-bit but the source is 256-bit wide.
1329 if (VT.is128BitVector())
1330 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1332 // Do not attempt to custom lower other non-256-bit vectors
1333 if (!VT.is256BitVector())
1336 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1337 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1338 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1341 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1342 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1345 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347 MVT VT = (MVT::SimpleValueType)i;
1349 // Do not attempt to promote non-256-bit vectors
1350 if (!VT.is256BitVector())
1353 setOperationAction(ISD::AND, VT, Promote);
1354 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1355 setOperationAction(ISD::OR, VT, Promote);
1356 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1357 setOperationAction(ISD::XOR, VT, Promote);
1358 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1359 setOperationAction(ISD::LOAD, VT, Promote);
1360 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1361 setOperationAction(ISD::SELECT, VT, Promote);
1362 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1366 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1370 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1372 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1373 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1374 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1376 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1377 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1378 setOperationAction(ISD::XOR, MVT::i1, Legal);
1379 setOperationAction(ISD::OR, MVT::i1, Legal);
1380 setOperationAction(ISD::AND, MVT::i1, Legal);
1381 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1382 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1383 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1384 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1385 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1386 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1388 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1390 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1391 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1392 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1393 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1395 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1396 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1397 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1398 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1399 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1400 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1401 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1402 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1404 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1405 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1406 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1407 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1408 if (Subtarget->is64Bit()) {
1409 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1410 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1411 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1412 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1414 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1416 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1417 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1418 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1419 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1421 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1422 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1423 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1425 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1426 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1427 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1428 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1429 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1430 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1431 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1432 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1434 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1437 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
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::v8i1, Custom);
1444 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1446 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1447 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1449 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1454 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1456 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1459 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1461 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1462 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1465 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1467 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1469 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1470 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1472 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1473 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1475 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1476 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1478 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1479 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1481 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1482 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1483 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1485 if (Subtarget->hasCDI()) {
1486 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1487 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1490 // Custom lower several nodes.
1491 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493 MVT VT = (MVT::SimpleValueType)i;
1495 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496 // Extract subvector is special because the value type
1497 // (result) is 256/128-bit but the source is 512-bit wide.
1498 if (VT.is128BitVector() || VT.is256BitVector())
1499 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1501 if (VT.getVectorElementType() == MVT::i1)
1502 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1504 // Do not attempt to custom lower other non-512-bit vectors
1505 if (!VT.is512BitVector())
1508 if ( EltSize >= 32) {
1509 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1510 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1511 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1512 setOperationAction(ISD::VSELECT, VT, Legal);
1513 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1514 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1515 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1518 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519 MVT VT = (MVT::SimpleValueType)i;
1521 // Do not attempt to promote non-256-bit vectors
1522 if (!VT.is512BitVector())
1525 setOperationAction(ISD::SELECT, VT, Promote);
1526 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1530 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1532 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536 // of this type with custom code.
1537 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1543 // We want to custom lower some of our intrinsics.
1544 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547 if (!Subtarget->is64Bit())
1548 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1550 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551 // handle type legalization for these operations here.
1553 // FIXME: We really should do custom legalization for addition and
1554 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1555 // than generic legalization for 64-bit multiplication-with-overflow, though.
1556 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557 // Add/Sub/Mul with overflow operations are custom lowered.
1559 setOperationAction(ISD::SADDO, VT, Custom);
1560 setOperationAction(ISD::UADDO, VT, Custom);
1561 setOperationAction(ISD::SSUBO, VT, Custom);
1562 setOperationAction(ISD::USUBO, VT, Custom);
1563 setOperationAction(ISD::SMULO, VT, Custom);
1564 setOperationAction(ISD::UMULO, VT, Custom);
1567 // There are no 8-bit 3-address imul/mul instructions
1568 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1571 if (!Subtarget->is64Bit()) {
1572 // These libcalls are not available in 32-bit.
1573 setLibcallName(RTLIB::SHL_I128, nullptr);
1574 setLibcallName(RTLIB::SRL_I128, nullptr);
1575 setLibcallName(RTLIB::SRA_I128, nullptr);
1578 // Combine sin / cos into one node or libcall if possible.
1579 if (Subtarget->hasSinCos()) {
1580 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582 if (Subtarget->isTargetDarwin()) {
1583 // For MacOSX, we don't want to the normal expansion of a libcall to
1584 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1586 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1591 if (Subtarget->isTargetWin64()) {
1592 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594 setOperationAction(ISD::SREM, MVT::i128, Custom);
1595 setOperationAction(ISD::UREM, MVT::i128, Custom);
1596 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1600 // We have target-specific dag combine patterns for the following nodes:
1601 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603 setTargetDAGCombine(ISD::VSELECT);
1604 setTargetDAGCombine(ISD::SELECT);
1605 setTargetDAGCombine(ISD::SHL);
1606 setTargetDAGCombine(ISD::SRA);
1607 setTargetDAGCombine(ISD::SRL);
1608 setTargetDAGCombine(ISD::OR);
1609 setTargetDAGCombine(ISD::AND);
1610 setTargetDAGCombine(ISD::ADD);
1611 setTargetDAGCombine(ISD::FADD);
1612 setTargetDAGCombine(ISD::FSUB);
1613 setTargetDAGCombine(ISD::FMA);
1614 setTargetDAGCombine(ISD::SUB);
1615 setTargetDAGCombine(ISD::LOAD);
1616 setTargetDAGCombine(ISD::STORE);
1617 setTargetDAGCombine(ISD::ZERO_EXTEND);
1618 setTargetDAGCombine(ISD::ANY_EXTEND);
1619 setTargetDAGCombine(ISD::SIGN_EXTEND);
1620 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621 setTargetDAGCombine(ISD::TRUNCATE);
1622 setTargetDAGCombine(ISD::SINT_TO_FP);
1623 setTargetDAGCombine(ISD::SETCC);
1624 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625 setTargetDAGCombine(ISD::BUILD_VECTOR);
1626 if (Subtarget->is64Bit())
1627 setTargetDAGCombine(ISD::MUL);
1628 setTargetDAGCombine(ISD::XOR);
1630 computeRegisterProperties();
1632 // On Darwin, -Os means optimize for size without hurting performance,
1633 // do not reduce the limit.
1634 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640 setPrefLoopAlignment(4); // 2^4 bytes.
1642 // Predictable cmov don't hurt on atom because it's in-order.
1643 PredictableSelectIsExpensive = !Subtarget->isAtom();
1645 setPrefFunctionAlignment(4); // 2^4 bytes.
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651 Subtarget->is64Bit();
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656 if (ExperimentalVectorWideningLegalization &&
1657 VT.getVectorNumElements() != 1 &&
1658 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659 return TypeWidenVector;
1661 return TargetLoweringBase::getPreferredVectorAction(VT);
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1666 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1668 if (Subtarget->hasAVX512())
1669 switch(VT.getVectorNumElements()) {
1670 case 8: return MVT::v8i1;
1671 case 16: return MVT::v16i1;
1674 return VT.changeVectorElementTypeToInteger();
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1682 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683 if (VTy->getBitWidth() == 128)
1685 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686 unsigned EltAlign = 0;
1687 getMaxByValAlign(ATy->getElementType(), EltAlign);
1688 if (EltAlign > MaxAlign)
1689 MaxAlign = EltAlign;
1690 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692 unsigned EltAlign = 0;
1693 getMaxByValAlign(STy->getElementType(i), EltAlign);
1694 if (EltAlign > MaxAlign)
1695 MaxAlign = EltAlign;
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707 if (Subtarget->is64Bit()) {
1708 // Max of 8 and alignment of type.
1709 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1716 if (Subtarget->hasSSE1())
1717 getMaxByValAlign(Ty, Align);
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734 unsigned DstAlign, unsigned SrcAlign,
1735 bool IsMemset, bool ZeroMemset,
1737 MachineFunction &MF) const {
1738 const Function *F = MF.getFunction();
1739 if ((!IsMemset || ZeroMemset) &&
1740 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741 Attribute::NoImplicitFloat)) {
1743 (Subtarget->isUnalignedMemAccessFast() ||
1744 ((DstAlign == 0 || DstAlign >= 16) &&
1745 (SrcAlign == 0 || SrcAlign >= 16)))) {
1747 if (Subtarget->hasInt256())
1749 if (Subtarget->hasFp256())
1752 if (Subtarget->hasSSE2())
1754 if (Subtarget->hasSSE1())
1756 } else if (!MemcpyStrSrc && Size >= 8 &&
1757 !Subtarget->is64Bit() &&
1758 Subtarget->hasSSE2()) {
1759 // Do not use f64 to lower memcpy if source is string constant. It's
1760 // better to use i32 to avoid the loads.
1764 if (Subtarget->is64Bit() && Size >= 8)
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1771 return X86ScalarSSEf32;
1772 else if (VT == MVT::f64)
1773 return X86ScalarSSEf64;
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1783 *Fast = Subtarget->isUnalignedMemAccessFast();
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function. The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1793 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794 Subtarget->isPICStyleGOT())
1795 return MachineJumpTableInfo::EK_Custom32;
1797 // Otherwise, use the normal jump table encoding heuristics.
1798 return TargetLowering::getJumpTableEncoding();
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803 const MachineBasicBlock *MBB,
1804 unsigned uid,MCContext &Ctx) const{
1805 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806 Subtarget->isPICStyleGOT());
1807 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1809 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816 SelectionDAG &DAG) const {
1817 if (!Subtarget->is64Bit())
1818 // This doesn't have SDLoc associated with it, but is not really the
1819 // same as a Register.
1820 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829 MCContext &Ctx) const {
1830 // X86-64 uses RIP relative addressing based on the jump table label.
1831 if (Subtarget->isPICStyleRIPRel())
1832 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1834 // Otherwise, the reference is relative to the PIC base.
1835 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841 const TargetRegisterClass *RRC = nullptr;
1843 switch (VT.SimpleTy) {
1845 return TargetLowering::findRepresentativeClass(VT);
1846 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847 RRC = Subtarget->is64Bit() ?
1848 (const TargetRegisterClass*)&X86::GR64RegClass :
1849 (const TargetRegisterClass*)&X86::GR32RegClass;
1852 RRC = &X86::VR64RegClass;
1854 case MVT::f32: case MVT::f64:
1855 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856 case MVT::v4f32: case MVT::v2f64:
1857 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1859 RRC = &X86::VR128RegClass;
1862 return std::make_pair(RRC, Cost);
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866 unsigned &Offset) const {
1867 if (!Subtarget->isTargetLinux())
1870 if (Subtarget->is64Bit()) {
1871 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1873 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886 unsigned DestAS) const {
1887 assert(SrcAS != DestAS && "Expected different address spaces!");
1889 return SrcAS < 256 && DestAS < 256;
1892 //===----------------------------------------------------------------------===//
1893 // Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1896 #include "X86GenCallingConv.inc"
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900 MachineFunction &MF, bool isVarArg,
1901 const SmallVectorImpl<ISD::OutputArg> &Outs,
1902 LLVMContext &Context) const {
1903 SmallVector<CCValAssign, 16> RVLocs;
1904 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1906 return CCInfo.CheckReturn(Outs, RetCC_X86);
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916 CallingConv::ID CallConv, bool isVarArg,
1917 const SmallVectorImpl<ISD::OutputArg> &Outs,
1918 const SmallVectorImpl<SDValue> &OutVals,
1919 SDLoc dl, SelectionDAG &DAG) const {
1920 MachineFunction &MF = DAG.getMachineFunction();
1921 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1923 SmallVector<CCValAssign, 16> RVLocs;
1924 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925 RVLocs, *DAG.getContext());
1926 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1929 SmallVector<SDValue, 6> RetOps;
1930 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931 // Operand #1 = Bytes To Pop
1932 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1935 // Copy the result values into the output registers.
1936 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937 CCValAssign &VA = RVLocs[i];
1938 assert(VA.isRegLoc() && "Can only return in registers!");
1939 SDValue ValToCopy = OutVals[i];
1940 EVT ValVT = ValToCopy.getValueType();
1942 // Promote values to the appropriate types
1943 if (VA.getLocInfo() == CCValAssign::SExt)
1944 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945 else if (VA.getLocInfo() == CCValAssign::ZExt)
1946 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947 else if (VA.getLocInfo() == CCValAssign::AExt)
1948 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949 else if (VA.getLocInfo() == CCValAssign::BCvt)
1950 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1952 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953 "Unexpected FP-extend for return value.");
1955 // If this is x86-64, and we disabled SSE, we can't return FP values,
1956 // or SSE or MMX vectors.
1957 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960 report_fatal_error("SSE register return with SSE disabled");
1962 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1963 // llvm-gcc has never done it right and no one has noticed, so this
1964 // should be OK for now.
1965 if (ValVT == MVT::f64 &&
1966 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967 report_fatal_error("SSE2 register return with SSE2 disabled");
1969 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970 // the RET instruction and handled by the FP Stackifier.
1971 if (VA.getLocReg() == X86::FP0 ||
1972 VA.getLocReg() == X86::FP1) {
1973 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974 // change the value to the FP stack register class.
1975 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977 RetOps.push_back(ValToCopy);
1978 // Don't emit a copytoreg.
1982 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983 // which is returned in RAX / RDX.
1984 if (Subtarget->is64Bit()) {
1985 if (ValVT == MVT::x86mmx) {
1986 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1990 // If we don't have SSE2 available, convert to v4f32 so the generated
1991 // register is legal.
1992 if (!Subtarget->hasSSE2())
1993 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1998 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999 Flag = Chain.getValue(1);
2000 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2003 // The x86-64 ABIs require that for returning structs by value we copy
2004 // the sret argument into %rax/%eax (depending on ABI) for the return.
2005 // Win32 requires us to put the sret argument to %eax as well.
2006 // We saved the argument into a virtual register in the entry block,
2007 // so now we copy the value out and into %rax/%eax.
2008 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010 MachineFunction &MF = DAG.getMachineFunction();
2011 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012 unsigned Reg = FuncInfo->getSRetReturnReg();
2014 "SRetReturnReg should have been set in LowerFormalArguments().");
2015 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2018 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019 X86::RAX : X86::EAX;
2020 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021 Flag = Chain.getValue(1);
2023 // RAX/EAX now acts like a return value.
2024 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2027 RetOps[0] = Chain; // Update chain.
2029 // Add the flag if we have it.
2031 RetOps.push_back(Flag);
2033 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037 if (N->getNumValues() != 1)
2039 if (!N->hasNUsesOfValue(1, 0))
2042 SDValue TCChain = Chain;
2043 SDNode *Copy = *N->use_begin();
2044 if (Copy->getOpcode() == ISD::CopyToReg) {
2045 // If the copy has a glue operand, we conservatively assume it isn't safe to
2046 // perform a tail call.
2047 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2049 TCChain = Copy->getOperand(0);
2050 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2053 bool HasRet = false;
2054 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2056 if (UI->getOpcode() != X86ISD::RET_FLAG)
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070 ISD::NodeType ExtendKind) const {
2072 // TODO: Is this also valid on 32-bit?
2073 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074 ReturnMVT = MVT::i8;
2076 ReturnMVT = MVT::i32;
2078 MVT MinVT = getRegisterType(ReturnMVT);
2079 return VT.bitsLT(MinVT) ? MinVT : VT;
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087 CallingConv::ID CallConv, bool isVarArg,
2088 const SmallVectorImpl<ISD::InputArg> &Ins,
2089 SDLoc dl, SelectionDAG &DAG,
2090 SmallVectorImpl<SDValue> &InVals) const {
2092 // Assign locations to each value returned by this call.
2093 SmallVector<CCValAssign, 16> RVLocs;
2094 bool Is64Bit = Subtarget->is64Bit();
2095 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096 DAG.getTarget(), RVLocs, *DAG.getContext());
2097 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2099 // Copy all of the result registers out of their specified physreg.
2100 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101 CCValAssign &VA = RVLocs[i];
2102 EVT CopyVT = VA.getValVT();
2104 // If this is x86-64, and we disabled SSE, we can't return FP values
2105 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107 report_fatal_error("SSE register return with SSE disabled");
2110 // If we prefer to use the value in xmm registers, copy it out as f80 and
2111 // use a truncate to move it from fp stack reg to xmm reg.
2112 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2113 isScalarFPTypeInSSEReg(VA.getValVT()))
2116 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2117 CopyVT, InFlag).getValue(1);
2118 SDValue Val = Chain.getValue(0);
2120 if (CopyVT != VA.getValVT())
2121 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2122 // This truncation won't change the value.
2123 DAG.getIntPtrConstant(1));
2125 InFlag = Chain.getValue(2);
2126 InVals.push_back(Val);
2132 //===----------------------------------------------------------------------===//
2133 // C & StdCall & Fast Calling Convention implementation
2134 //===----------------------------------------------------------------------===//
2135 // StdCall calling convention seems to be standard for many Windows' API
2136 // routines and around. It differs from C calling convention just a little:
2137 // callee should clean up the stack, not caller. Symbols should be also
2138 // decorated in some fancy way :) It doesn't support any vector arguments.
2139 // For info on fast calling convention see Fast Calling Convention (tail call)
2140 // implementation LowerX86_32FastCCCallTo.
2142 /// CallIsStructReturn - Determines whether a call uses struct return
2144 enum StructReturnType {
2149 static StructReturnType
2150 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2152 return NotStructReturn;
2154 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2155 if (!Flags.isSRet())
2156 return NotStructReturn;
2157 if (Flags.isInReg())
2158 return RegStructReturn;
2159 return StackStructReturn;
2162 /// ArgsAreStructReturn - Determines whether a function uses struct
2163 /// return semantics.
2164 static StructReturnType
2165 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2167 return NotStructReturn;
2169 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2170 if (!Flags.isSRet())
2171 return NotStructReturn;
2172 if (Flags.isInReg())
2173 return RegStructReturn;
2174 return StackStructReturn;
2177 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2178 /// by "Src" to address "Dst" with size and alignment information specified by
2179 /// the specific parameter attribute. The copy will be passed as a byval
2180 /// function parameter.
2182 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2183 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2185 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2187 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2188 /*isVolatile*/false, /*AlwaysInline=*/true,
2189 MachinePointerInfo(), MachinePointerInfo());
2192 /// IsTailCallConvention - Return true if the calling convention is one that
2193 /// supports tail call optimization.
2194 static bool IsTailCallConvention(CallingConv::ID CC) {
2195 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2196 CC == CallingConv::HiPE);
2199 /// \brief Return true if the calling convention is a C calling convention.
2200 static bool IsCCallConvention(CallingConv::ID CC) {
2201 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2202 CC == CallingConv::X86_64_SysV);
2205 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2206 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2210 CallingConv::ID CalleeCC = CS.getCallingConv();
2211 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2217 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2218 /// a tailcall target by changing its ABI.
2219 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2220 bool GuaranteedTailCallOpt) {
2221 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2225 X86TargetLowering::LowerMemArgument(SDValue Chain,
2226 CallingConv::ID CallConv,
2227 const SmallVectorImpl<ISD::InputArg> &Ins,
2228 SDLoc dl, SelectionDAG &DAG,
2229 const CCValAssign &VA,
2230 MachineFrameInfo *MFI,
2232 // Create the nodes corresponding to a load from this parameter slot.
2233 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2234 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2235 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2236 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2239 // If value is passed by pointer we have address passed instead of the value
2241 if (VA.getLocInfo() == CCValAssign::Indirect)
2242 ValVT = VA.getLocVT();
2244 ValVT = VA.getValVT();
2246 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2247 // changed with more analysis.
2248 // In case of tail call optimization mark all arguments mutable. Since they
2249 // could be overwritten by lowering of arguments in case of a tail call.
2250 if (Flags.isByVal()) {
2251 unsigned Bytes = Flags.getByValSize();
2252 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2253 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2254 return DAG.getFrameIndex(FI, getPointerTy());
2256 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2257 VA.getLocMemOffset(), isImmutable);
2258 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2259 return DAG.getLoad(ValVT, dl, Chain, FIN,
2260 MachinePointerInfo::getFixedStack(FI),
2261 false, false, false, 0);
2266 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2267 CallingConv::ID CallConv,
2269 const SmallVectorImpl<ISD::InputArg> &Ins,
2272 SmallVectorImpl<SDValue> &InVals)
2274 MachineFunction &MF = DAG.getMachineFunction();
2275 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2277 const Function* Fn = MF.getFunction();
2278 if (Fn->hasExternalLinkage() &&
2279 Subtarget->isTargetCygMing() &&
2280 Fn->getName() == "main")
2281 FuncInfo->setForceFramePointer(true);
2283 MachineFrameInfo *MFI = MF.getFrameInfo();
2284 bool Is64Bit = Subtarget->is64Bit();
2285 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2287 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2288 "Var args not supported with calling convention fastcc, ghc or hipe");
2290 // Assign locations to all of the incoming arguments.
2291 SmallVector<CCValAssign, 16> ArgLocs;
2292 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2293 ArgLocs, *DAG.getContext());
2295 // Allocate shadow area for Win64
2297 CCInfo.AllocateStack(32, 8);
2299 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2301 unsigned LastVal = ~0U;
2303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2304 CCValAssign &VA = ArgLocs[i];
2305 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2307 assert(VA.getValNo() != LastVal &&
2308 "Don't support value assigned to multiple locs yet");
2310 LastVal = VA.getValNo();
2312 if (VA.isRegLoc()) {
2313 EVT RegVT = VA.getLocVT();
2314 const TargetRegisterClass *RC;
2315 if (RegVT == MVT::i32)
2316 RC = &X86::GR32RegClass;
2317 else if (Is64Bit && RegVT == MVT::i64)
2318 RC = &X86::GR64RegClass;
2319 else if (RegVT == MVT::f32)
2320 RC = &X86::FR32RegClass;
2321 else if (RegVT == MVT::f64)
2322 RC = &X86::FR64RegClass;
2323 else if (RegVT.is512BitVector())
2324 RC = &X86::VR512RegClass;
2325 else if (RegVT.is256BitVector())
2326 RC = &X86::VR256RegClass;
2327 else if (RegVT.is128BitVector())
2328 RC = &X86::VR128RegClass;
2329 else if (RegVT == MVT::x86mmx)
2330 RC = &X86::VR64RegClass;
2331 else if (RegVT == MVT::i1)
2332 RC = &X86::VK1RegClass;
2333 else if (RegVT == MVT::v8i1)
2334 RC = &X86::VK8RegClass;
2335 else if (RegVT == MVT::v16i1)
2336 RC = &X86::VK16RegClass;
2337 else if (RegVT == MVT::v32i1)
2338 RC = &X86::VK32RegClass;
2339 else if (RegVT == MVT::v64i1)
2340 RC = &X86::VK64RegClass;
2342 llvm_unreachable("Unknown argument type!");
2344 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2345 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2347 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2348 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2350 if (VA.getLocInfo() == CCValAssign::SExt)
2351 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2352 DAG.getValueType(VA.getValVT()));
2353 else if (VA.getLocInfo() == CCValAssign::ZExt)
2354 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2355 DAG.getValueType(VA.getValVT()));
2356 else if (VA.getLocInfo() == CCValAssign::BCvt)
2357 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2359 if (VA.isExtInLoc()) {
2360 // Handle MMX values passed in XMM regs.
2361 if (RegVT.isVector())
2362 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2364 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2367 assert(VA.isMemLoc());
2368 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2371 // If value is passed via pointer - do a load.
2372 if (VA.getLocInfo() == CCValAssign::Indirect)
2373 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2374 MachinePointerInfo(), false, false, false, 0);
2376 InVals.push_back(ArgValue);
2379 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2380 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381 // The x86-64 ABIs require that for returning structs by value we copy
2382 // the sret argument into %rax/%eax (depending on ABI) for the return.
2383 // Win32 requires us to put the sret argument to %eax as well.
2384 // Save the argument into a virtual register so that we can access it
2385 // from the return points.
2386 if (Ins[i].Flags.isSRet()) {
2387 unsigned Reg = FuncInfo->getSRetReturnReg();
2389 MVT PtrTy = getPointerTy();
2390 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2391 FuncInfo->setSRetReturnReg(Reg);
2393 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2394 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2400 unsigned StackSize = CCInfo.getNextStackOffset();
2401 // Align stack specially for tail calls.
2402 if (FuncIsMadeTailCallSafe(CallConv,
2403 MF.getTarget().Options.GuaranteedTailCallOpt))
2404 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2406 // If the function takes variable number of arguments, make a frame index for
2407 // the start of the first vararg value... for expansion of llvm.va_start.
2409 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2410 CallConv != CallingConv::X86_ThisCall)) {
2411 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2414 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2416 // FIXME: We should really autogenerate these arrays
2417 static const MCPhysReg GPR64ArgRegsWin64[] = {
2418 X86::RCX, X86::RDX, X86::R8, X86::R9
2420 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2421 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2423 static const MCPhysReg XMMArgRegs64Bit[] = {
2424 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2425 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2427 const MCPhysReg *GPR64ArgRegs;
2428 unsigned NumXMMRegs = 0;
2431 // The XMM registers which might contain var arg parameters are shadowed
2432 // in their paired GPR. So we only need to save the GPR to their home
2434 TotalNumIntRegs = 4;
2435 GPR64ArgRegs = GPR64ArgRegsWin64;
2437 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2438 GPR64ArgRegs = GPR64ArgRegs64Bit;
2440 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2443 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2446 bool NoImplicitFloatOps = Fn->getAttributes().
2447 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2448 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2449 "SSE register cannot be used when SSE is disabled!");
2450 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2451 NoImplicitFloatOps) &&
2452 "SSE register cannot be used when SSE is disabled!");
2453 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2454 !Subtarget->hasSSE1())
2455 // Kernel mode asks for SSE to be disabled, so don't push them
2457 TotalNumXMMRegs = 0;
2460 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2461 // Get to the caller-allocated home save location. Add 8 to account
2462 // for the return address.
2463 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2464 FuncInfo->setRegSaveFrameIndex(
2465 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2466 // Fixup to set vararg frame on shadow area (4 x i64).
2468 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2470 // For X86-64, if there are vararg parameters that are passed via
2471 // registers, then we must store them to their spots on the stack so
2472 // they may be loaded by deferencing the result of va_next.
2473 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2474 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2475 FuncInfo->setRegSaveFrameIndex(
2476 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2480 // Store the integer parameter registers.
2481 SmallVector<SDValue, 8> MemOps;
2482 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2484 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2485 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2486 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2487 DAG.getIntPtrConstant(Offset));
2488 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2489 &X86::GR64RegClass);
2490 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2492 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2493 MachinePointerInfo::getFixedStack(
2494 FuncInfo->getRegSaveFrameIndex(), Offset),
2496 MemOps.push_back(Store);
2500 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2501 // Now store the XMM (fp + vector) parameter registers.
2502 SmallVector<SDValue, 11> SaveXMMOps;
2503 SaveXMMOps.push_back(Chain);
2505 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2506 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2507 SaveXMMOps.push_back(ALVal);
2509 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2510 FuncInfo->getRegSaveFrameIndex()));
2511 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2512 FuncInfo->getVarArgsFPOffset()));
2514 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2515 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2516 &X86::VR128RegClass);
2517 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2518 SaveXMMOps.push_back(Val);
2520 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2521 MVT::Other, SaveXMMOps));
2524 if (!MemOps.empty())
2525 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2529 // Some CCs need callee pop.
2530 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2531 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2532 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2534 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2535 // If this is an sret function, the return should pop the hidden pointer.
2536 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2537 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2538 argsAreStructReturn(Ins) == StackStructReturn)
2539 FuncInfo->setBytesToPopOnReturn(4);
2543 // RegSaveFrameIndex is X86-64 only.
2544 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2545 if (CallConv == CallingConv::X86_FastCall ||
2546 CallConv == CallingConv::X86_ThisCall)
2547 // fastcc functions can't have varargs.
2548 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2551 FuncInfo->setArgumentStackSize(StackSize);
2557 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2558 SDValue StackPtr, SDValue Arg,
2559 SDLoc dl, SelectionDAG &DAG,
2560 const CCValAssign &VA,
2561 ISD::ArgFlagsTy Flags) const {
2562 unsigned LocMemOffset = VA.getLocMemOffset();
2563 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2564 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2565 if (Flags.isByVal())
2566 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2568 return DAG.getStore(Chain, dl, Arg, PtrOff,
2569 MachinePointerInfo::getStack(LocMemOffset),
2573 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2574 /// optimization is performed and it is required.
2576 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2577 SDValue &OutRetAddr, SDValue Chain,
2578 bool IsTailCall, bool Is64Bit,
2579 int FPDiff, SDLoc dl) const {
2580 // Adjust the Return address stack slot.
2581 EVT VT = getPointerTy();
2582 OutRetAddr = getReturnAddressFrameIndex(DAG);
2584 // Load the "old" Return address.
2585 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2586 false, false, false, 0);
2587 return SDValue(OutRetAddr.getNode(), 1);
2590 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2591 /// optimization is performed and it is required (FPDiff!=0).
2592 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2593 SDValue Chain, SDValue RetAddrFrIdx,
2594 EVT PtrVT, unsigned SlotSize,
2595 int FPDiff, SDLoc dl) {
2596 // Store the return address to the appropriate stack slot.
2597 if (!FPDiff) return Chain;
2598 // Calculate the new stack slot for the return address.
2599 int NewReturnAddrFI =
2600 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2602 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2603 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2604 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2610 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2611 SmallVectorImpl<SDValue> &InVals) const {
2612 SelectionDAG &DAG = CLI.DAG;
2614 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2615 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2616 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2617 SDValue Chain = CLI.Chain;
2618 SDValue Callee = CLI.Callee;
2619 CallingConv::ID CallConv = CLI.CallConv;
2620 bool &isTailCall = CLI.IsTailCall;
2621 bool isVarArg = CLI.IsVarArg;
2623 MachineFunction &MF = DAG.getMachineFunction();
2624 bool Is64Bit = Subtarget->is64Bit();
2625 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2626 StructReturnType SR = callIsStructReturn(Outs);
2627 bool IsSibcall = false;
2629 if (MF.getTarget().Options.DisableTailCalls)
2632 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2634 // Force this to be a tail call. The verifier rules are enough to ensure
2635 // that we can lower this successfully without moving the return address
2638 } else if (isTailCall) {
2639 // Check if it's really possible to do a tail call.
2640 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2641 isVarArg, SR != NotStructReturn,
2642 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2643 Outs, OutVals, Ins, DAG);
2645 // Sibcalls are automatically detected tailcalls which do not require
2647 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2654 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2655 "Var args not supported with calling convention fastcc, ghc or hipe");
2657 // Analyze operands of the call, assigning locations to each operand.
2658 SmallVector<CCValAssign, 16> ArgLocs;
2659 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2660 ArgLocs, *DAG.getContext());
2662 // Allocate shadow area for Win64
2664 CCInfo.AllocateStack(32, 8);
2666 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2668 // Get a count of how many bytes are to be pushed on the stack.
2669 unsigned NumBytes = CCInfo.getNextStackOffset();
2671 // This is a sibcall. The memory operands are available in caller's
2672 // own caller's stack.
2674 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2675 IsTailCallConvention(CallConv))
2676 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2679 if (isTailCall && !IsSibcall && !IsMustTail) {
2680 // Lower arguments at fp - stackoffset + fpdiff.
2681 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2682 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2684 FPDiff = NumBytesCallerPushed - NumBytes;
2686 // Set the delta of movement of the returnaddr stackslot.
2687 // But only set if delta is greater than previous delta.
2688 if (FPDiff < X86Info->getTCReturnAddrDelta())
2689 X86Info->setTCReturnAddrDelta(FPDiff);
2692 unsigned NumBytesToPush = NumBytes;
2693 unsigned NumBytesToPop = NumBytes;
2695 // If we have an inalloca argument, all stack space has already been allocated
2696 // for us and be right at the top of the stack. We don't support multiple
2697 // arguments passed in memory when using inalloca.
2698 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2700 if (!ArgLocs.back().isMemLoc())
2701 report_fatal_error("cannot use inalloca attribute on a register "
2703 if (ArgLocs.back().getLocMemOffset() != 0)
2704 report_fatal_error("any parameter with the inalloca attribute must be "
2705 "the only memory argument");
2709 Chain = DAG.getCALLSEQ_START(
2710 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2712 SDValue RetAddrFrIdx;
2713 // Load return address for tail calls.
2714 if (isTailCall && FPDiff)
2715 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2716 Is64Bit, FPDiff, dl);
2718 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2719 SmallVector<SDValue, 8> MemOpChains;
2722 // Walk the register/memloc assignments, inserting copies/loads. In the case
2723 // of tail call optimization arguments are handle later.
2724 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2725 DAG.getSubtarget().getRegisterInfo());
2726 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2727 // Skip inalloca arguments, they have already been written.
2728 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2729 if (Flags.isInAlloca())
2732 CCValAssign &VA = ArgLocs[i];
2733 EVT RegVT = VA.getLocVT();
2734 SDValue Arg = OutVals[i];
2735 bool isByVal = Flags.isByVal();
2737 // Promote the value if needed.
2738 switch (VA.getLocInfo()) {
2739 default: llvm_unreachable("Unknown loc info!");
2740 case CCValAssign::Full: break;
2741 case CCValAssign::SExt:
2742 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2744 case CCValAssign::ZExt:
2745 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2747 case CCValAssign::AExt:
2748 if (RegVT.is128BitVector()) {
2749 // Special case: passing MMX values in XMM registers.
2750 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2751 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2752 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2754 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2756 case CCValAssign::BCvt:
2757 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2759 case CCValAssign::Indirect: {
2760 // Store the argument.
2761 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2762 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2763 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2764 MachinePointerInfo::getFixedStack(FI),
2771 if (VA.isRegLoc()) {
2772 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2773 if (isVarArg && IsWin64) {
2774 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2775 // shadow reg if callee is a varargs function.
2776 unsigned ShadowReg = 0;
2777 switch (VA.getLocReg()) {
2778 case X86::XMM0: ShadowReg = X86::RCX; break;
2779 case X86::XMM1: ShadowReg = X86::RDX; break;
2780 case X86::XMM2: ShadowReg = X86::R8; break;
2781 case X86::XMM3: ShadowReg = X86::R9; break;
2784 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2786 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2787 assert(VA.isMemLoc());
2788 if (!StackPtr.getNode())
2789 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2791 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2792 dl, DAG, VA, Flags));
2796 if (!MemOpChains.empty())
2797 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2799 if (Subtarget->isPICStyleGOT()) {
2800 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2803 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2804 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2806 // If we are tail calling and generating PIC/GOT style code load the
2807 // address of the callee into ECX. The value in ecx is used as target of
2808 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2809 // for tail calls on PIC/GOT architectures. Normally we would just put the
2810 // address of GOT into ebx and then call target@PLT. But for tail calls
2811 // ebx would be restored (since ebx is callee saved) before jumping to the
2814 // Note: The actual moving to ECX is done further down.
2815 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2816 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2817 !G->getGlobal()->hasProtectedVisibility())
2818 Callee = LowerGlobalAddress(Callee, DAG);
2819 else if (isa<ExternalSymbolSDNode>(Callee))
2820 Callee = LowerExternalSymbol(Callee, DAG);
2824 if (Is64Bit && isVarArg && !IsWin64) {
2825 // From AMD64 ABI document:
2826 // For calls that may call functions that use varargs or stdargs
2827 // (prototype-less calls or calls to functions containing ellipsis (...) in
2828 // the declaration) %al is used as hidden argument to specify the number
2829 // of SSE registers used. The contents of %al do not need to match exactly
2830 // the number of registers, but must be an ubound on the number of SSE
2831 // registers used and is in the range 0 - 8 inclusive.
2833 // Count the number of XMM registers allocated.
2834 static const MCPhysReg XMMArgRegs[] = {
2835 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2836 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2838 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2839 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2840 && "SSE registers cannot be used when SSE is disabled");
2842 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2843 DAG.getConstant(NumXMMRegs, MVT::i8)));
2846 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2847 // don't need this because the eligibility check rejects calls that require
2848 // shuffling arguments passed in memory.
2849 if (!IsSibcall && isTailCall) {
2850 // Force all the incoming stack arguments to be loaded from the stack
2851 // before any new outgoing arguments are stored to the stack, because the
2852 // outgoing stack slots may alias the incoming argument stack slots, and
2853 // the alias isn't otherwise explicit. This is slightly more conservative
2854 // than necessary, because it means that each store effectively depends
2855 // on every argument instead of just those arguments it would clobber.
2856 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2858 SmallVector<SDValue, 8> MemOpChains2;
2861 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2862 CCValAssign &VA = ArgLocs[i];
2865 assert(VA.isMemLoc());
2866 SDValue Arg = OutVals[i];
2867 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2868 // Skip inalloca arguments. They don't require any work.
2869 if (Flags.isInAlloca())
2871 // Create frame index.
2872 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2873 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2874 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2875 FIN = DAG.getFrameIndex(FI, getPointerTy());
2877 if (Flags.isByVal()) {
2878 // Copy relative to framepointer.
2879 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2880 if (!StackPtr.getNode())
2881 StackPtr = DAG.getCopyFromReg(Chain, dl,
2882 RegInfo->getStackRegister(),
2884 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2886 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2890 // Store relative to framepointer.
2891 MemOpChains2.push_back(
2892 DAG.getStore(ArgChain, dl, Arg, FIN,
2893 MachinePointerInfo::getFixedStack(FI),
2898 if (!MemOpChains2.empty())
2899 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2901 // Store the return address to the appropriate stack slot.
2902 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2903 getPointerTy(), RegInfo->getSlotSize(),
2907 // Build a sequence of copy-to-reg nodes chained together with token chain
2908 // and flag operands which copy the outgoing args into registers.
2910 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2911 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2912 RegsToPass[i].second, InFlag);
2913 InFlag = Chain.getValue(1);
2916 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2917 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2918 // In the 64-bit large code model, we have to make all calls
2919 // through a register, since the call instruction's 32-bit
2920 // pc-relative offset may not be large enough to hold the whole
2922 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2923 // If the callee is a GlobalAddress node (quite common, every direct call
2924 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2927 // We should use extra load for direct calls to dllimported functions in
2929 const GlobalValue *GV = G->getGlobal();
2930 if (!GV->hasDLLImportStorageClass()) {
2931 unsigned char OpFlags = 0;
2932 bool ExtraLoad = false;
2933 unsigned WrapperKind = ISD::DELETED_NODE;
2935 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2936 // external symbols most go through the PLT in PIC mode. If the symbol
2937 // has hidden or protected visibility, or if it is static or local, then
2938 // we don't need to use the PLT - we can directly call it.
2939 if (Subtarget->isTargetELF() &&
2940 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2941 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2942 OpFlags = X86II::MO_PLT;
2943 } else if (Subtarget->isPICStyleStubAny() &&
2944 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2945 (!Subtarget->getTargetTriple().isMacOSX() ||
2946 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2947 // PC-relative references to external symbols should go through $stub,
2948 // unless we're building with the leopard linker or later, which
2949 // automatically synthesizes these stubs.
2950 OpFlags = X86II::MO_DARWIN_STUB;
2951 } else if (Subtarget->isPICStyleRIPRel() &&
2952 isa<Function>(GV) &&
2953 cast<Function>(GV)->getAttributes().
2954 hasAttribute(AttributeSet::FunctionIndex,
2955 Attribute::NonLazyBind)) {
2956 // If the function is marked as non-lazy, generate an indirect call
2957 // which loads from the GOT directly. This avoids runtime overhead
2958 // at the cost of eager binding (and one extra byte of encoding).
2959 OpFlags = X86II::MO_GOTPCREL;
2960 WrapperKind = X86ISD::WrapperRIP;
2964 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2965 G->getOffset(), OpFlags);
2967 // Add a wrapper if needed.
2968 if (WrapperKind != ISD::DELETED_NODE)
2969 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2970 // Add extra indirection if needed.
2972 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2973 MachinePointerInfo::getGOT(),
2974 false, false, false, 0);
2976 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2977 unsigned char OpFlags = 0;
2979 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2980 // external symbols should go through the PLT.
2981 if (Subtarget->isTargetELF() &&
2982 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2983 OpFlags = X86II::MO_PLT;
2984 } else if (Subtarget->isPICStyleStubAny() &&
2985 (!Subtarget->getTargetTriple().isMacOSX() ||
2986 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2987 // PC-relative references to external symbols should go through $stub,
2988 // unless we're building with the leopard linker or later, which
2989 // automatically synthesizes these stubs.
2990 OpFlags = X86II::MO_DARWIN_STUB;
2993 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2997 // Returns a chain & a flag for retval copy to use.
2998 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2999 SmallVector<SDValue, 8> Ops;
3001 if (!IsSibcall && isTailCall) {
3002 Chain = DAG.getCALLSEQ_END(Chain,
3003 DAG.getIntPtrConstant(NumBytesToPop, true),
3004 DAG.getIntPtrConstant(0, true), InFlag, dl);
3005 InFlag = Chain.getValue(1);
3008 Ops.push_back(Chain);
3009 Ops.push_back(Callee);
3012 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3014 // Add argument registers to the end of the list so that they are known live
3016 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3017 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3018 RegsToPass[i].second.getValueType()));
3020 // Add a register mask operand representing the call-preserved registers.
3021 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3022 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3023 assert(Mask && "Missing call preserved mask for calling convention");
3024 Ops.push_back(DAG.getRegisterMask(Mask));
3026 if (InFlag.getNode())
3027 Ops.push_back(InFlag);
3031 //// If this is the first return lowered for this function, add the regs
3032 //// to the liveout set for the function.
3033 // This isn't right, although it's probably harmless on x86; liveouts
3034 // should be computed from returns not tail calls. Consider a void
3035 // function making a tail call to a function returning int.
3036 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3039 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3040 InFlag = Chain.getValue(1);
3042 // Create the CALLSEQ_END node.
3043 unsigned NumBytesForCalleeToPop;
3044 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3045 DAG.getTarget().Options.GuaranteedTailCallOpt))
3046 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3047 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3048 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3049 SR == StackStructReturn)
3050 // If this is a call to a struct-return function, the callee
3051 // pops the hidden struct pointer, so we have to push it back.
3052 // This is common for Darwin/X86, Linux & Mingw32 targets.
3053 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3054 NumBytesForCalleeToPop = 4;
3056 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3058 // Returns a flag for retval copy to use.
3060 Chain = DAG.getCALLSEQ_END(Chain,
3061 DAG.getIntPtrConstant(NumBytesToPop, true),
3062 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3065 InFlag = Chain.getValue(1);
3068 // Handle result values, copying them out of physregs into vregs that we
3070 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3071 Ins, dl, DAG, InVals);
3074 //===----------------------------------------------------------------------===//
3075 // Fast Calling Convention (tail call) implementation
3076 //===----------------------------------------------------------------------===//
3078 // Like std call, callee cleans arguments, convention except that ECX is
3079 // reserved for storing the tail called function address. Only 2 registers are
3080 // free for argument passing (inreg). Tail call optimization is performed
3082 // * tailcallopt is enabled
3083 // * caller/callee are fastcc
3084 // On X86_64 architecture with GOT-style position independent code only local
3085 // (within module) calls are supported at the moment.
3086 // To keep the stack aligned according to platform abi the function
3087 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3088 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3089 // If a tail called function callee has more arguments than the caller the
3090 // caller needs to make sure that there is room to move the RETADDR to. This is
3091 // achieved by reserving an area the size of the argument delta right after the
3092 // original RETADDR, but before the saved framepointer or the spilled registers
3093 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3105 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3106 /// for a 16 byte align requirement.
3108 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3109 SelectionDAG& DAG) const {
3110 MachineFunction &MF = DAG.getMachineFunction();
3111 const TargetMachine &TM = MF.getTarget();
3112 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3113 TM.getSubtargetImpl()->getRegisterInfo());
3114 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3115 unsigned StackAlignment = TFI.getStackAlignment();
3116 uint64_t AlignMask = StackAlignment - 1;
3117 int64_t Offset = StackSize;
3118 unsigned SlotSize = RegInfo->getSlotSize();
3119 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3120 // Number smaller than 12 so just add the difference.
3121 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3123 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3124 Offset = ((~AlignMask) & Offset) + StackAlignment +
3125 (StackAlignment-SlotSize);
3130 /// MatchingStackOffset - Return true if the given stack call argument is
3131 /// already available in the same position (relatively) of the caller's
3132 /// incoming argument stack.
3134 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3135 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3136 const X86InstrInfo *TII) {
3137 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3139 if (Arg.getOpcode() == ISD::CopyFromReg) {
3140 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3141 if (!TargetRegisterInfo::isVirtualRegister(VR))
3143 MachineInstr *Def = MRI->getVRegDef(VR);
3146 if (!Flags.isByVal()) {
3147 if (!TII->isLoadFromStackSlot(Def, FI))
3150 unsigned Opcode = Def->getOpcode();
3151 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3152 Def->getOperand(1).isFI()) {
3153 FI = Def->getOperand(1).getIndex();
3154 Bytes = Flags.getByValSize();
3158 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3159 if (Flags.isByVal())
3160 // ByVal argument is passed in as a pointer but it's now being
3161 // dereferenced. e.g.
3162 // define @foo(%struct.X* %A) {
3163 // tail call @bar(%struct.X* byval %A)
3166 SDValue Ptr = Ld->getBasePtr();
3167 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3170 FI = FINode->getIndex();
3171 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3172 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3173 FI = FINode->getIndex();
3174 Bytes = Flags.getByValSize();
3178 assert(FI != INT_MAX);
3179 if (!MFI->isFixedObjectIndex(FI))
3181 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3184 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3185 /// for tail call optimization. Targets which want to do tail call
3186 /// optimization should implement this function.
3188 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3189 CallingConv::ID CalleeCC,
3191 bool isCalleeStructRet,
3192 bool isCallerStructRet,
3194 const SmallVectorImpl<ISD::OutputArg> &Outs,
3195 const SmallVectorImpl<SDValue> &OutVals,
3196 const SmallVectorImpl<ISD::InputArg> &Ins,
3197 SelectionDAG &DAG) const {
3198 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3201 // If -tailcallopt is specified, make fastcc functions tail-callable.
3202 const MachineFunction &MF = DAG.getMachineFunction();
3203 const Function *CallerF = MF.getFunction();
3205 // If the function return type is x86_fp80 and the callee return type is not,
3206 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3207 // perform a tailcall optimization here.
3208 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3211 CallingConv::ID CallerCC = CallerF->getCallingConv();
3212 bool CCMatch = CallerCC == CalleeCC;
3213 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3214 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3216 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3217 if (IsTailCallConvention(CalleeCC) && CCMatch)
3222 // Look for obvious safe cases to perform tail call optimization that do not
3223 // require ABI changes. This is what gcc calls sibcall.
3225 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3226 // emit a special epilogue.
3227 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3228 DAG.getSubtarget().getRegisterInfo());
3229 if (RegInfo->needsStackRealignment(MF))
3232 // Also avoid sibcall optimization if either caller or callee uses struct
3233 // return semantics.
3234 if (isCalleeStructRet || isCallerStructRet)
3237 // An stdcall/thiscall caller is expected to clean up its arguments; the
3238 // callee isn't going to do that.
3239 // FIXME: this is more restrictive than needed. We could produce a tailcall
3240 // when the stack adjustment matches. For example, with a thiscall that takes
3241 // only one argument.
3242 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3243 CallerCC == CallingConv::X86_ThisCall))
3246 // Do not sibcall optimize vararg calls unless all arguments are passed via
3248 if (isVarArg && !Outs.empty()) {
3250 // Optimizing for varargs on Win64 is unlikely to be safe without
3251 // additional testing.
3252 if (IsCalleeWin64 || IsCallerWin64)
3255 SmallVector<CCValAssign, 16> ArgLocs;
3256 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3257 DAG.getTarget(), ArgLocs, *DAG.getContext());
3259 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3260 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3261 if (!ArgLocs[i].isRegLoc())
3265 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3266 // stack. Therefore, if it's not used by the call it is not safe to optimize
3267 // this into a sibcall.
3268 bool Unused = false;
3269 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3276 SmallVector<CCValAssign, 16> RVLocs;
3277 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3278 DAG.getTarget(), RVLocs, *DAG.getContext());
3279 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3280 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3281 CCValAssign &VA = RVLocs[i];
3282 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3287 // If the calling conventions do not match, then we'd better make sure the
3288 // results are returned in the same way as what the caller expects.
3290 SmallVector<CCValAssign, 16> RVLocs1;
3291 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3292 DAG.getTarget(), RVLocs1, *DAG.getContext());
3293 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3295 SmallVector<CCValAssign, 16> RVLocs2;
3296 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3297 DAG.getTarget(), RVLocs2, *DAG.getContext());
3298 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3300 if (RVLocs1.size() != RVLocs2.size())
3302 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3303 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3305 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3307 if (RVLocs1[i].isRegLoc()) {
3308 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3311 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3317 // If the callee takes no arguments then go on to check the results of the
3319 if (!Outs.empty()) {
3320 // Check if stack adjustment is needed. For now, do not do this if any
3321 // argument is passed on the stack.
3322 SmallVector<CCValAssign, 16> ArgLocs;
3323 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3324 DAG.getTarget(), ArgLocs, *DAG.getContext());
3326 // Allocate shadow area for Win64
3328 CCInfo.AllocateStack(32, 8);
3330 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3331 if (CCInfo.getNextStackOffset()) {
3332 MachineFunction &MF = DAG.getMachineFunction();
3333 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3336 // Check if the arguments are already laid out in the right way as
3337 // the caller's fixed stack objects.
3338 MachineFrameInfo *MFI = MF.getFrameInfo();
3339 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3340 const X86InstrInfo *TII =
3341 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3342 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3343 CCValAssign &VA = ArgLocs[i];
3344 SDValue Arg = OutVals[i];
3345 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3346 if (VA.getLocInfo() == CCValAssign::Indirect)
3348 if (!VA.isRegLoc()) {
3349 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3356 // If the tailcall address may be in a register, then make sure it's
3357 // possible to register allocate for it. In 32-bit, the call address can
3358 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3359 // callee-saved registers are restored. These happen to be the same
3360 // registers used to pass 'inreg' arguments so watch out for those.
3361 if (!Subtarget->is64Bit() &&
3362 ((!isa<GlobalAddressSDNode>(Callee) &&
3363 !isa<ExternalSymbolSDNode>(Callee)) ||
3364 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3365 unsigned NumInRegs = 0;
3366 // In PIC we need an extra register to formulate the address computation
3368 unsigned MaxInRegs =
3369 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3371 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3372 CCValAssign &VA = ArgLocs[i];
3375 unsigned Reg = VA.getLocReg();
3378 case X86::EAX: case X86::EDX: case X86::ECX:
3379 if (++NumInRegs == MaxInRegs)
3391 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3392 const TargetLibraryInfo *libInfo) const {
3393 return X86::createFastISel(funcInfo, libInfo);
3396 //===----------------------------------------------------------------------===//
3397 // Other Lowering Hooks
3398 //===----------------------------------------------------------------------===//
3400 static bool MayFoldLoad(SDValue Op) {
3401 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3404 static bool MayFoldIntoStore(SDValue Op) {
3405 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3408 static bool isTargetShuffle(unsigned Opcode) {
3410 default: return false;
3411 case X86ISD::PSHUFB:
3412 case X86ISD::PSHUFD:
3413 case X86ISD::PSHUFHW:
3414 case X86ISD::PSHUFLW:
3416 case X86ISD::PALIGNR:
3417 case X86ISD::MOVLHPS:
3418 case X86ISD::MOVLHPD:
3419 case X86ISD::MOVHLPS:
3420 case X86ISD::MOVLPS:
3421 case X86ISD::MOVLPD:
3422 case X86ISD::MOVSHDUP:
3423 case X86ISD::MOVSLDUP:
3424 case X86ISD::MOVDDUP:
3427 case X86ISD::UNPCKL:
3428 case X86ISD::UNPCKH:
3429 case X86ISD::VPERMILP:
3430 case X86ISD::VPERM2X128:
3431 case X86ISD::VPERMI:
3436 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3437 SDValue V1, SelectionDAG &DAG) {
3439 default: llvm_unreachable("Unknown x86 shuffle node");
3440 case X86ISD::MOVSHDUP:
3441 case X86ISD::MOVSLDUP:
3442 case X86ISD::MOVDDUP:
3443 return DAG.getNode(Opc, dl, VT, V1);
3447 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3448 SDValue V1, unsigned TargetMask,
3449 SelectionDAG &DAG) {
3451 default: llvm_unreachable("Unknown x86 shuffle node");
3452 case X86ISD::PSHUFD:
3453 case X86ISD::PSHUFHW:
3454 case X86ISD::PSHUFLW:
3455 case X86ISD::VPERMILP:
3456 case X86ISD::VPERMI:
3457 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3461 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3462 SDValue V1, SDValue V2, unsigned TargetMask,
3463 SelectionDAG &DAG) {
3465 default: llvm_unreachable("Unknown x86 shuffle node");
3466 case X86ISD::PALIGNR:
3467 case X86ISD::VALIGN:
3469 case X86ISD::VPERM2X128:
3470 return DAG.getNode(Opc, dl, VT, V1, V2,
3471 DAG.getConstant(TargetMask, MVT::i8));
3475 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3476 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3478 default: llvm_unreachable("Unknown x86 shuffle node");
3479 case X86ISD::MOVLHPS:
3480 case X86ISD::MOVLHPD:
3481 case X86ISD::MOVHLPS:
3482 case X86ISD::MOVLPS:
3483 case X86ISD::MOVLPD:
3486 case X86ISD::UNPCKL:
3487 case X86ISD::UNPCKH:
3488 return DAG.getNode(Opc, dl, VT, V1, V2);
3492 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3493 MachineFunction &MF = DAG.getMachineFunction();
3494 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3495 DAG.getSubtarget().getRegisterInfo());
3496 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3497 int ReturnAddrIndex = FuncInfo->getRAIndex();
3499 if (ReturnAddrIndex == 0) {
3500 // Set up a frame object for the return address.
3501 unsigned SlotSize = RegInfo->getSlotSize();
3502 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3505 FuncInfo->setRAIndex(ReturnAddrIndex);
3508 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3511 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3512 bool hasSymbolicDisplacement) {
3513 // Offset should fit into 32 bit immediate field.
3514 if (!isInt<32>(Offset))
3517 // If we don't have a symbolic displacement - we don't have any extra
3519 if (!hasSymbolicDisplacement)
3522 // FIXME: Some tweaks might be needed for medium code model.
3523 if (M != CodeModel::Small && M != CodeModel::Kernel)
3526 // For small code model we assume that latest object is 16MB before end of 31
3527 // bits boundary. We may also accept pretty large negative constants knowing
3528 // that all objects are in the positive half of address space.
3529 if (M == CodeModel::Small && Offset < 16*1024*1024)
3532 // For kernel code model we know that all object resist in the negative half
3533 // of 32bits address space. We may not accept negative offsets, since they may
3534 // be just off and we may accept pretty large positive ones.
3535 if (M == CodeModel::Kernel && Offset > 0)
3541 /// isCalleePop - Determines whether the callee is required to pop its
3542 /// own arguments. Callee pop is necessary to support tail calls.
3543 bool X86::isCalleePop(CallingConv::ID CallingConv,
3544 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3548 switch (CallingConv) {
3551 case CallingConv::X86_StdCall:
3553 case CallingConv::X86_FastCall:
3555 case CallingConv::X86_ThisCall:
3557 case CallingConv::Fast:
3559 case CallingConv::GHC:
3561 case CallingConv::HiPE:
3566 /// \brief Return true if the condition is an unsigned comparison operation.
3567 static bool isX86CCUnsigned(unsigned X86CC) {
3569 default: llvm_unreachable("Invalid integer condition!");
3570 case X86::COND_E: return true;
3571 case X86::COND_G: return false;
3572 case X86::COND_GE: return false;
3573 case X86::COND_L: return false;
3574 case X86::COND_LE: return false;
3575 case X86::COND_NE: return true;
3576 case X86::COND_B: return true;
3577 case X86::COND_A: return true;
3578 case X86::COND_BE: return true;
3579 case X86::COND_AE: return true;
3581 llvm_unreachable("covered switch fell through?!");
3584 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3585 /// specific condition code, returning the condition code and the LHS/RHS of the
3586 /// comparison to make.
3587 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3588 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3590 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3591 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3592 // X > -1 -> X == 0, jump !sign.
3593 RHS = DAG.getConstant(0, RHS.getValueType());
3594 return X86::COND_NS;
3596 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3597 // X < 0 -> X == 0, jump on sign.
3600 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3602 RHS = DAG.getConstant(0, RHS.getValueType());
3603 return X86::COND_LE;
3607 switch (SetCCOpcode) {
3608 default: llvm_unreachable("Invalid integer condition!");
3609 case ISD::SETEQ: return X86::COND_E;
3610 case ISD::SETGT: return X86::COND_G;
3611 case ISD::SETGE: return X86::COND_GE;
3612 case ISD::SETLT: return X86::COND_L;
3613 case ISD::SETLE: return X86::COND_LE;
3614 case ISD::SETNE: return X86::COND_NE;
3615 case ISD::SETULT: return X86::COND_B;
3616 case ISD::SETUGT: return X86::COND_A;
3617 case ISD::SETULE: return X86::COND_BE;
3618 case ISD::SETUGE: return X86::COND_AE;
3622 // First determine if it is required or is profitable to flip the operands.
3624 // If LHS is a foldable load, but RHS is not, flip the condition.
3625 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3626 !ISD::isNON_EXTLoad(RHS.getNode())) {
3627 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3628 std::swap(LHS, RHS);
3631 switch (SetCCOpcode) {
3637 std::swap(LHS, RHS);
3641 // On a floating point condition, the flags are set as follows:
3643 // 0 | 0 | 0 | X > Y
3644 // 0 | 0 | 1 | X < Y
3645 // 1 | 0 | 0 | X == Y
3646 // 1 | 1 | 1 | unordered
3647 switch (SetCCOpcode) {
3648 default: llvm_unreachable("Condcode should be pre-legalized away");
3650 case ISD::SETEQ: return X86::COND_E;
3651 case ISD::SETOLT: // flipped
3653 case ISD::SETGT: return X86::COND_A;
3654 case ISD::SETOLE: // flipped
3656 case ISD::SETGE: return X86::COND_AE;
3657 case ISD::SETUGT: // flipped
3659 case ISD::SETLT: return X86::COND_B;
3660 case ISD::SETUGE: // flipped
3662 case ISD::SETLE: return X86::COND_BE;
3664 case ISD::SETNE: return X86::COND_NE;
3665 case ISD::SETUO: return X86::COND_P;
3666 case ISD::SETO: return X86::COND_NP;
3668 case ISD::SETUNE: return X86::COND_INVALID;
3672 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3673 /// code. Current x86 isa includes the following FP cmov instructions:
3674 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3675 static bool hasFPCMov(unsigned X86CC) {
3691 /// isFPImmLegal - Returns true if the target can instruction select the
3692 /// specified FP immediate natively. If false, the legalizer will
3693 /// materialize the FP immediate as a load from a constant pool.
3694 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3695 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3696 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3702 /// \brief Returns true if it is beneficial to convert a load of a constant
3703 /// to just the constant itself.
3704 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3706 assert(Ty->isIntegerTy());
3708 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3709 if (BitSize == 0 || BitSize > 64)
3714 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3715 /// the specified range (L, H].
3716 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3717 return (Val < 0) || (Val >= Low && Val < Hi);
3720 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3721 /// specified value.
3722 static bool isUndefOrEqual(int Val, int CmpVal) {
3723 return (Val < 0 || Val == CmpVal);
3726 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3727 /// from position Pos and ending in Pos+Size, falls within the specified
3728 /// sequential range (L, L+Pos]. or is undef.
3729 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3730 unsigned Pos, unsigned Size, int Low) {
3731 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3732 if (!isUndefOrEqual(Mask[i], Low))
3737 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3738 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3739 /// the second operand.
3740 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3741 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3742 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3743 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3744 return (Mask[0] < 2 && Mask[1] < 2);
3748 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3749 /// is suitable for input to PSHUFHW.
3750 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3751 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3754 // Lower quadword copied in order or undef.
3755 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3758 // Upper quadword shuffled.
3759 for (unsigned i = 4; i != 8; ++i)
3760 if (!isUndefOrInRange(Mask[i], 4, 8))
3763 if (VT == MVT::v16i16) {
3764 // Lower quadword copied in order or undef.
3765 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3768 // Upper quadword shuffled.
3769 for (unsigned i = 12; i != 16; ++i)
3770 if (!isUndefOrInRange(Mask[i], 12, 16))
3777 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3778 /// is suitable for input to PSHUFLW.
3779 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3780 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3783 // Upper quadword copied in order.
3784 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3787 // Lower quadword shuffled.
3788 for (unsigned i = 0; i != 4; ++i)
3789 if (!isUndefOrInRange(Mask[i], 0, 4))
3792 if (VT == MVT::v16i16) {
3793 // Upper quadword copied in order.
3794 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3797 // Lower quadword shuffled.
3798 for (unsigned i = 8; i != 12; ++i)
3799 if (!isUndefOrInRange(Mask[i], 8, 12))
3806 /// \brief Return true if the mask specifies a shuffle of elements that is
3807 /// suitable for input to intralane (palignr) or interlane (valign) vector
3809 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3810 unsigned NumElts = VT.getVectorNumElements();
3811 unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3812 unsigned NumLaneElts = NumElts/NumLanes;
3814 // Do not handle 64-bit element shuffles with palignr.
3815 if (NumLaneElts == 2)
3818 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3820 for (i = 0; i != NumLaneElts; ++i) {
3825 // Lane is all undef, go to next lane
3826 if (i == NumLaneElts)
3829 int Start = Mask[i+l];
3831 // Make sure its in this lane in one of the sources
3832 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3833 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3836 // If not lane 0, then we must match lane 0
3837 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3840 // Correct second source to be contiguous with first source
3841 if (Start >= (int)NumElts)
3842 Start -= NumElts - NumLaneElts;
3844 // Make sure we're shifting in the right direction.
3845 if (Start <= (int)(i+l))
3850 // Check the rest of the elements to see if they are consecutive.
3851 for (++i; i != NumLaneElts; ++i) {
3852 int Idx = Mask[i+l];
3854 // Make sure its in this lane
3855 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3856 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3859 // If not lane 0, then we must match lane 0
3860 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3863 if (Idx >= (int)NumElts)
3864 Idx -= NumElts - NumLaneElts;
3866 if (!isUndefOrEqual(Idx, Start+i))
3875 /// \brief Return true if the node specifies a shuffle of elements that is
3876 /// suitable for input to PALIGNR.
3877 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3878 const X86Subtarget *Subtarget) {
3879 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3880 (VT.is256BitVector() && !Subtarget->hasInt256()))
3881 // FIXME: Add AVX512BW.
3884 return isAlignrMask(Mask, VT, false);
3887 /// \brief Return true if the node specifies a shuffle of elements that is
3888 /// suitable for input to VALIGN.
3889 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3890 const X86Subtarget *Subtarget) {
3891 // FIXME: Add AVX512VL.
3892 if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3894 return isAlignrMask(Mask, VT, true);
3897 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3898 /// the two vector operands have swapped position.
3899 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3900 unsigned NumElems) {
3901 for (unsigned i = 0; i != NumElems; ++i) {
3905 else if (idx < (int)NumElems)
3906 Mask[i] = idx + NumElems;
3908 Mask[i] = idx - NumElems;
3912 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3914 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3915 /// reverse of what x86 shuffles want.
3916 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3918 unsigned NumElems = VT.getVectorNumElements();
3919 unsigned NumLanes = VT.getSizeInBits()/128;
3920 unsigned NumLaneElems = NumElems/NumLanes;
3922 if (NumLaneElems != 2 && NumLaneElems != 4)
3925 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3926 bool symetricMaskRequired =
3927 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3929 // VSHUFPSY divides the resulting vector into 4 chunks.
3930 // The sources are also splitted into 4 chunks, and each destination
3931 // chunk must come from a different source chunk.
3933 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3934 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3936 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3937 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3939 // VSHUFPDY divides the resulting vector into 4 chunks.
3940 // The sources are also splitted into 4 chunks, and each destination
3941 // chunk must come from a different source chunk.
3943 // SRC1 => X3 X2 X1 X0
3944 // SRC2 => Y3 Y2 Y1 Y0
3946 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3948 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3949 unsigned HalfLaneElems = NumLaneElems/2;
3950 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3951 for (unsigned i = 0; i != NumLaneElems; ++i) {
3952 int Idx = Mask[i+l];
3953 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3954 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3956 // For VSHUFPSY, the mask of the second half must be the same as the
3957 // first but with the appropriate offsets. This works in the same way as
3958 // VPERMILPS works with masks.
3959 if (!symetricMaskRequired || Idx < 0)
3961 if (MaskVal[i] < 0) {
3962 MaskVal[i] = Idx - l;
3965 if ((signed)(Idx - l) != MaskVal[i])
3973 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3974 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3975 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3976 if (!VT.is128BitVector())
3979 unsigned NumElems = VT.getVectorNumElements();
3984 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3985 return isUndefOrEqual(Mask[0], 6) &&
3986 isUndefOrEqual(Mask[1], 7) &&
3987 isUndefOrEqual(Mask[2], 2) &&
3988 isUndefOrEqual(Mask[3], 3);
3991 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3992 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3994 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3995 if (!VT.is128BitVector())
3998 unsigned NumElems = VT.getVectorNumElements();
4003 return isUndefOrEqual(Mask[0], 2) &&
4004 isUndefOrEqual(Mask[1], 3) &&
4005 isUndefOrEqual(Mask[2], 2) &&
4006 isUndefOrEqual(Mask[3], 3);
4009 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4010 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4011 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4012 if (!VT.is128BitVector())
4015 unsigned NumElems = VT.getVectorNumElements();
4017 if (NumElems != 2 && NumElems != 4)
4020 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4021 if (!isUndefOrEqual(Mask[i], i + NumElems))
4024 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4025 if (!isUndefOrEqual(Mask[i], i))
4031 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4032 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4033 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4034 if (!VT.is128BitVector())
4037 unsigned NumElems = VT.getVectorNumElements();
4039 if (NumElems != 2 && NumElems != 4)
4042 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4043 if (!isUndefOrEqual(Mask[i], i))
4046 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4047 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4053 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4054 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4055 /// i. e: If all but one element come from the same vector.
4056 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4057 // TODO: Deal with AVX's VINSERTPS
4058 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4061 unsigned CorrectPosV1 = 0;
4062 unsigned CorrectPosV2 = 0;
4063 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4064 if (Mask[i] == -1) {
4072 else if (Mask[i] == i + 4)
4076 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4077 // We have 3 elements (undefs count as elements from any vector) from one
4078 // vector, and one from another.
4085 // Some special combinations that can be optimized.
4088 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4089 SelectionDAG &DAG) {
4090 MVT VT = SVOp->getSimpleValueType(0);
4093 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4096 ArrayRef<int> Mask = SVOp->getMask();
4098 // These are the special masks that may be optimized.
4099 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4100 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4101 bool MatchEvenMask = true;
4102 bool MatchOddMask = true;
4103 for (int i=0; i<8; ++i) {
4104 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4105 MatchEvenMask = false;
4106 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4107 MatchOddMask = false;
4110 if (!MatchEvenMask && !MatchOddMask)
4113 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4115 SDValue Op0 = SVOp->getOperand(0);
4116 SDValue Op1 = SVOp->getOperand(1);
4118 if (MatchEvenMask) {
4119 // Shift the second operand right to 32 bits.
4120 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4121 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4123 // Shift the first operand left to 32 bits.
4124 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4125 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4127 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4128 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4131 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4132 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4133 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4134 bool HasInt256, bool V2IsSplat = false) {
4136 assert(VT.getSizeInBits() >= 128 &&
4137 "Unsupported vector type for unpckl");
4139 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4141 unsigned NumOf256BitLanes;
4142 unsigned NumElts = VT.getVectorNumElements();
4143 if (VT.is256BitVector()) {
4144 if (NumElts != 4 && NumElts != 8 &&
4145 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4148 NumOf256BitLanes = 1;
4149 } else if (VT.is512BitVector()) {
4150 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4151 "Unsupported vector type for unpckh");
4153 NumOf256BitLanes = 2;
4156 NumOf256BitLanes = 1;
4159 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4160 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4162 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4163 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4164 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4165 int BitI = Mask[l256*NumEltsInStride+l+i];
4166 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4167 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4169 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4171 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4179 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4180 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4181 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4182 bool HasInt256, bool V2IsSplat = false) {
4183 assert(VT.getSizeInBits() >= 128 &&
4184 "Unsupported vector type for unpckh");
4186 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4188 unsigned NumOf256BitLanes;
4189 unsigned NumElts = VT.getVectorNumElements();
4190 if (VT.is256BitVector()) {
4191 if (NumElts != 4 && NumElts != 8 &&
4192 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4195 NumOf256BitLanes = 1;
4196 } else if (VT.is512BitVector()) {
4197 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4198 "Unsupported vector type for unpckh");
4200 NumOf256BitLanes = 2;
4203 NumOf256BitLanes = 1;
4206 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4207 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4209 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4210 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4211 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4212 int BitI = Mask[l256*NumEltsInStride+l+i];
4213 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4214 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4216 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4218 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4226 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4227 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4229 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4230 unsigned NumElts = VT.getVectorNumElements();
4231 bool Is256BitVec = VT.is256BitVector();
4233 if (VT.is512BitVector())
4235 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4236 "Unsupported vector type for unpckh");
4238 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4239 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4242 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4243 // FIXME: Need a better way to get rid of this, there's no latency difference
4244 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4245 // the former later. We should also remove the "_undef" special mask.
4246 if (NumElts == 4 && Is256BitVec)
4249 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4250 // independently on 128-bit lanes.
4251 unsigned NumLanes = VT.getSizeInBits()/128;
4252 unsigned NumLaneElts = NumElts/NumLanes;
4254 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4255 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4256 int BitI = Mask[l+i];
4257 int BitI1 = Mask[l+i+1];
4259 if (!isUndefOrEqual(BitI, j))
4261 if (!isUndefOrEqual(BitI1, j))
4269 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4270 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4272 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4273 unsigned NumElts = VT.getVectorNumElements();
4275 if (VT.is512BitVector())
4278 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4279 "Unsupported vector type for unpckh");
4281 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4282 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4285 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4286 // independently on 128-bit lanes.
4287 unsigned NumLanes = VT.getSizeInBits()/128;
4288 unsigned NumLaneElts = NumElts/NumLanes;
4290 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4291 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4292 int BitI = Mask[l+i];
4293 int BitI1 = Mask[l+i+1];
4294 if (!isUndefOrEqual(BitI, j))
4296 if (!isUndefOrEqual(BitI1, j))
4303 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4304 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4305 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4306 if (!VT.is512BitVector())
4309 unsigned NumElts = VT.getVectorNumElements();
4310 unsigned HalfSize = NumElts/2;
4311 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4312 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4317 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4318 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4326 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4327 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4328 /// MOVSD, and MOVD, i.e. setting the lowest element.
4329 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4330 if (VT.getVectorElementType().getSizeInBits() < 32)
4332 if (!VT.is128BitVector())
4335 unsigned NumElts = VT.getVectorNumElements();
4337 if (!isUndefOrEqual(Mask[0], NumElts))
4340 for (unsigned i = 1; i != NumElts; ++i)
4341 if (!isUndefOrEqual(Mask[i], i))
4347 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4348 /// as permutations between 128-bit chunks or halves. As an example: this
4350 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4351 /// The first half comes from the second half of V1 and the second half from the
4352 /// the second half of V2.
4353 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4354 if (!HasFp256 || !VT.is256BitVector())
4357 // The shuffle result is divided into half A and half B. In total the two
4358 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4359 // B must come from C, D, E or F.
4360 unsigned HalfSize = VT.getVectorNumElements()/2;
4361 bool MatchA = false, MatchB = false;
4363 // Check if A comes from one of C, D, E, F.
4364 for (unsigned Half = 0; Half != 4; ++Half) {
4365 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4371 // Check if B comes from one of C, D, E, F.
4372 for (unsigned Half = 0; Half != 4; ++Half) {
4373 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4379 return MatchA && MatchB;
4382 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4383 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4384 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4385 MVT VT = SVOp->getSimpleValueType(0);
4387 unsigned HalfSize = VT.getVectorNumElements()/2;
4389 unsigned FstHalf = 0, SndHalf = 0;
4390 for (unsigned i = 0; i < HalfSize; ++i) {
4391 if (SVOp->getMaskElt(i) > 0) {
4392 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4396 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4397 if (SVOp->getMaskElt(i) > 0) {
4398 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4403 return (FstHalf | (SndHalf << 4));
4406 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4407 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4408 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4412 unsigned NumElts = VT.getVectorNumElements();
4414 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4415 for (unsigned i = 0; i != NumElts; ++i) {
4418 Imm8 |= Mask[i] << (i*2);
4423 unsigned LaneSize = 4;
4424 SmallVector<int, 4> MaskVal(LaneSize, -1);
4426 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4427 for (unsigned i = 0; i != LaneSize; ++i) {
4428 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4432 if (MaskVal[i] < 0) {
4433 MaskVal[i] = Mask[i+l] - l;
4434 Imm8 |= MaskVal[i] << (i*2);
4437 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4444 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4445 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4446 /// Note that VPERMIL mask matching is different depending whether theunderlying
4447 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4448 /// to the same elements of the low, but to the higher half of the source.
4449 /// In VPERMILPD the two lanes could be shuffled independently of each other
4450 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4451 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4452 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4453 if (VT.getSizeInBits() < 256 || EltSize < 32)
4455 bool symetricMaskRequired = (EltSize == 32);
4456 unsigned NumElts = VT.getVectorNumElements();
4458 unsigned NumLanes = VT.getSizeInBits()/128;
4459 unsigned LaneSize = NumElts/NumLanes;
4460 // 2 or 4 elements in one lane
4462 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4463 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4464 for (unsigned i = 0; i != LaneSize; ++i) {
4465 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4467 if (symetricMaskRequired) {
4468 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4469 ExpectedMaskVal[i] = Mask[i+l] - l;
4472 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4480 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4481 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4482 /// element of vector 2 and the other elements to come from vector 1 in order.
4483 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4484 bool V2IsSplat = false, bool V2IsUndef = false) {
4485 if (!VT.is128BitVector())
4488 unsigned NumOps = VT.getVectorNumElements();
4489 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4492 if (!isUndefOrEqual(Mask[0], 0))
4495 for (unsigned i = 1; i != NumOps; ++i)
4496 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4497 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4498 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4504 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4505 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4506 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4507 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4508 const X86Subtarget *Subtarget) {
4509 if (!Subtarget->hasSSE3())
4512 unsigned NumElems = VT.getVectorNumElements();
4514 if ((VT.is128BitVector() && NumElems != 4) ||
4515 (VT.is256BitVector() && NumElems != 8) ||
4516 (VT.is512BitVector() && NumElems != 16))
4519 // "i+1" is the value the indexed mask element must have
4520 for (unsigned i = 0; i != NumElems; i += 2)
4521 if (!isUndefOrEqual(Mask[i], i+1) ||
4522 !isUndefOrEqual(Mask[i+1], i+1))
4528 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4529 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4530 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4531 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4532 const X86Subtarget *Subtarget) {
4533 if (!Subtarget->hasSSE3())
4536 unsigned NumElems = VT.getVectorNumElements();
4538 if ((VT.is128BitVector() && NumElems != 4) ||
4539 (VT.is256BitVector() && NumElems != 8) ||
4540 (VT.is512BitVector() && NumElems != 16))
4543 // "i" is the value the indexed mask element must have
4544 for (unsigned i = 0; i != NumElems; i += 2)
4545 if (!isUndefOrEqual(Mask[i], i) ||
4546 !isUndefOrEqual(Mask[i+1], i))
4552 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4553 /// specifies a shuffle of elements that is suitable for input to 256-bit
4554 /// version of MOVDDUP.
4555 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4556 if (!HasFp256 || !VT.is256BitVector())
4559 unsigned NumElts = VT.getVectorNumElements();
4563 for (unsigned i = 0; i != NumElts/2; ++i)
4564 if (!isUndefOrEqual(Mask[i], 0))
4566 for (unsigned i = NumElts/2; i != NumElts; ++i)
4567 if (!isUndefOrEqual(Mask[i], NumElts/2))
4572 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4573 /// specifies a shuffle of elements that is suitable for input to 128-bit
4574 /// version of MOVDDUP.
4575 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4576 if (!VT.is128BitVector())
4579 unsigned e = VT.getVectorNumElements() / 2;
4580 for (unsigned i = 0; i != e; ++i)
4581 if (!isUndefOrEqual(Mask[i], i))
4583 for (unsigned i = 0; i != e; ++i)
4584 if (!isUndefOrEqual(Mask[e+i], i))
4589 /// isVEXTRACTIndex - Return true if the specified
4590 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4591 /// suitable for instruction that extract 128 or 256 bit vectors
4592 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4593 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4594 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4597 // The index should be aligned on a vecWidth-bit boundary.
4599 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4601 MVT VT = N->getSimpleValueType(0);
4602 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4603 bool Result = (Index * ElSize) % vecWidth == 0;
4608 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4609 /// operand specifies a subvector insert that is suitable for input to
4610 /// insertion of 128 or 256-bit subvectors
4611 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4612 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4613 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4615 // The index should be aligned on a vecWidth-bit boundary.
4617 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4619 MVT VT = N->getSimpleValueType(0);
4620 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4621 bool Result = (Index * ElSize) % vecWidth == 0;
4626 bool X86::isVINSERT128Index(SDNode *N) {
4627 return isVINSERTIndex(N, 128);
4630 bool X86::isVINSERT256Index(SDNode *N) {
4631 return isVINSERTIndex(N, 256);
4634 bool X86::isVEXTRACT128Index(SDNode *N) {
4635 return isVEXTRACTIndex(N, 128);
4638 bool X86::isVEXTRACT256Index(SDNode *N) {
4639 return isVEXTRACTIndex(N, 256);
4642 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4643 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4644 /// Handles 128-bit and 256-bit.
4645 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4646 MVT VT = N->getSimpleValueType(0);
4648 assert((VT.getSizeInBits() >= 128) &&
4649 "Unsupported vector type for PSHUF/SHUFP");
4651 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4652 // independently on 128-bit lanes.
4653 unsigned NumElts = VT.getVectorNumElements();
4654 unsigned NumLanes = VT.getSizeInBits()/128;
4655 unsigned NumLaneElts = NumElts/NumLanes;
4657 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4658 "Only supports 2, 4 or 8 elements per lane");
4660 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4662 for (unsigned i = 0; i != NumElts; ++i) {
4663 int Elt = N->getMaskElt(i);
4664 if (Elt < 0) continue;
4665 Elt &= NumLaneElts - 1;
4666 unsigned ShAmt = (i << Shift) % 8;
4667 Mask |= Elt << ShAmt;
4673 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4674 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4675 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4676 MVT VT = N->getSimpleValueType(0);
4678 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4679 "Unsupported vector type for PSHUFHW");
4681 unsigned NumElts = VT.getVectorNumElements();
4684 for (unsigned l = 0; l != NumElts; l += 8) {
4685 // 8 nodes per lane, but we only care about the last 4.
4686 for (unsigned i = 0; i < 4; ++i) {
4687 int Elt = N->getMaskElt(l+i+4);
4688 if (Elt < 0) continue;
4689 Elt &= 0x3; // only 2-bits.
4690 Mask |= Elt << (i * 2);
4697 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4698 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4699 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4700 MVT VT = N->getSimpleValueType(0);
4702 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4703 "Unsupported vector type for PSHUFHW");
4705 unsigned NumElts = VT.getVectorNumElements();
4708 for (unsigned l = 0; l != NumElts; l += 8) {
4709 // 8 nodes per lane, but we only care about the first 4.
4710 for (unsigned i = 0; i < 4; ++i) {
4711 int Elt = N->getMaskElt(l+i);
4712 if (Elt < 0) continue;
4713 Elt &= 0x3; // only 2-bits
4714 Mask |= Elt << (i * 2);
4721 /// \brief Return the appropriate immediate to shuffle the specified
4722 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4723 /// VALIGN (if Interlane is true) instructions.
4724 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4726 MVT VT = SVOp->getSimpleValueType(0);
4727 unsigned EltSize = InterLane ? 1 :
4728 VT.getVectorElementType().getSizeInBits() >> 3;
4730 unsigned NumElts = VT.getVectorNumElements();
4731 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4732 unsigned NumLaneElts = NumElts/NumLanes;
4736 for (i = 0; i != NumElts; ++i) {
4737 Val = SVOp->getMaskElt(i);
4741 if (Val >= (int)NumElts)
4742 Val -= NumElts - NumLaneElts;
4744 assert(Val - i > 0 && "PALIGNR imm should be positive");
4745 return (Val - i) * EltSize;
4748 /// \brief Return the appropriate immediate to shuffle the specified
4749 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4750 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4751 return getShuffleAlignrImmediate(SVOp, false);
4754 /// \brief Return the appropriate immediate to shuffle the specified
4755 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4756 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4757 return getShuffleAlignrImmediate(SVOp, true);
4761 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4762 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4763 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4764 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4767 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4769 MVT VecVT = N->getOperand(0).getSimpleValueType();
4770 MVT ElVT = VecVT.getVectorElementType();
4772 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4773 return Index / NumElemsPerChunk;
4776 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4777 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4778 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4779 llvm_unreachable("Illegal insert subvector for VINSERT");
4782 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4784 MVT VecVT = N->getSimpleValueType(0);
4785 MVT ElVT = VecVT.getVectorElementType();
4787 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4788 return Index / NumElemsPerChunk;
4791 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4792 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4793 /// and VINSERTI128 instructions.
4794 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4795 return getExtractVEXTRACTImmediate(N, 128);
4798 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4799 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4800 /// and VINSERTI64x4 instructions.
4801 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4802 return getExtractVEXTRACTImmediate(N, 256);
4805 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4806 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4807 /// and VINSERTI128 instructions.
4808 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4809 return getInsertVINSERTImmediate(N, 128);
4812 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4813 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4814 /// and VINSERTI64x4 instructions.
4815 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4816 return getInsertVINSERTImmediate(N, 256);
4819 /// isZero - Returns true if Elt is a constant integer zero
4820 static bool isZero(SDValue V) {
4821 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4822 return C && C->isNullValue();
4825 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4827 bool X86::isZeroNode(SDValue Elt) {
4830 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4831 return CFP->getValueAPF().isPosZero();
4835 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4836 /// match movhlps. The lower half elements should come from upper half of
4837 /// V1 (and in order), and the upper half elements should come from the upper
4838 /// half of V2 (and in order).
4839 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4840 if (!VT.is128BitVector())
4842 if (VT.getVectorNumElements() != 4)
4844 for (unsigned i = 0, e = 2; i != e; ++i)
4845 if (!isUndefOrEqual(Mask[i], i+2))
4847 for (unsigned i = 2; i != 4; ++i)
4848 if (!isUndefOrEqual(Mask[i], i+4))
4853 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4854 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4856 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4857 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4859 N = N->getOperand(0).getNode();
4860 if (!ISD::isNON_EXTLoad(N))
4863 *LD = cast<LoadSDNode>(N);
4867 // Test whether the given value is a vector value which will be legalized
4869 static bool WillBeConstantPoolLoad(SDNode *N) {
4870 if (N->getOpcode() != ISD::BUILD_VECTOR)
4873 // Check for any non-constant elements.
4874 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4875 switch (N->getOperand(i).getNode()->getOpcode()) {
4877 case ISD::ConstantFP:
4884 // Vectors of all-zeros and all-ones are materialized with special
4885 // instructions rather than being loaded.
4886 return !ISD::isBuildVectorAllZeros(N) &&
4887 !ISD::isBuildVectorAllOnes(N);
4890 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4891 /// match movlp{s|d}. The lower half elements should come from lower half of
4892 /// V1 (and in order), and the upper half elements should come from the upper
4893 /// half of V2 (and in order). And since V1 will become the source of the
4894 /// MOVLP, it must be either a vector load or a scalar load to vector.
4895 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4896 ArrayRef<int> Mask, MVT VT) {
4897 if (!VT.is128BitVector())
4900 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4902 // Is V2 is a vector load, don't do this transformation. We will try to use
4903 // load folding shufps op.
4904 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4907 unsigned NumElems = VT.getVectorNumElements();
4909 if (NumElems != 2 && NumElems != 4)
4911 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4912 if (!isUndefOrEqual(Mask[i], i))
4914 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4915 if (!isUndefOrEqual(Mask[i], i+NumElems))
4920 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4921 /// to an zero vector.
4922 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4923 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4924 SDValue V1 = N->getOperand(0);
4925 SDValue V2 = N->getOperand(1);
4926 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4927 for (unsigned i = 0; i != NumElems; ++i) {
4928 int Idx = N->getMaskElt(i);
4929 if (Idx >= (int)NumElems) {
4930 unsigned Opc = V2.getOpcode();
4931 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4933 if (Opc != ISD::BUILD_VECTOR ||
4934 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4936 } else if (Idx >= 0) {
4937 unsigned Opc = V1.getOpcode();
4938 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4940 if (Opc != ISD::BUILD_VECTOR ||
4941 !X86::isZeroNode(V1.getOperand(Idx)))
4948 /// getZeroVector - Returns a vector of specified type with all zero elements.
4950 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4951 SelectionDAG &DAG, SDLoc dl) {
4952 assert(VT.isVector() && "Expected a vector type");
4954 // Always build SSE zero vectors as <4 x i32> bitcasted
4955 // to their dest type. This ensures they get CSE'd.
4957 if (VT.is128BitVector()) { // SSE
4958 if (Subtarget->hasSSE2()) { // SSE2
4959 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4960 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4962 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4963 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4965 } else if (VT.is256BitVector()) { // AVX
4966 if (Subtarget->hasInt256()) { // AVX2
4967 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4968 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4969 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4971 // 256-bit logic and arithmetic instructions in AVX are all
4972 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4973 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4974 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4975 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4977 } else if (VT.is512BitVector()) { // AVX-512
4978 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4979 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4980 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4981 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4982 } else if (VT.getScalarType() == MVT::i1) {
4983 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4984 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4985 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4986 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4988 llvm_unreachable("Unexpected vector type");
4990 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4993 /// getOnesVector - Returns a vector of specified type with all bits set.
4994 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4995 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4996 /// Then bitcast to their original type, ensuring they get CSE'd.
4997 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4999 assert(VT.isVector() && "Expected a vector type");
5001 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5003 if (VT.is256BitVector()) {
5004 if (HasInt256) { // AVX2
5005 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5006 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5008 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5009 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5011 } else if (VT.is128BitVector()) {
5012 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5014 llvm_unreachable("Unexpected vector type");
5016 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5019 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5020 /// that point to V2 points to its first element.
5021 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5022 for (unsigned i = 0; i != NumElems; ++i) {
5023 if (Mask[i] > (int)NumElems) {
5029 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5030 /// operation of specified width.
5031 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5033 unsigned NumElems = VT.getVectorNumElements();
5034 SmallVector<int, 8> Mask;
5035 Mask.push_back(NumElems);
5036 for (unsigned i = 1; i != NumElems; ++i)
5038 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5041 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5042 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5044 unsigned NumElems = VT.getVectorNumElements();
5045 SmallVector<int, 8> Mask;
5046 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5048 Mask.push_back(i + NumElems);
5050 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5053 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5054 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5056 unsigned NumElems = VT.getVectorNumElements();
5057 SmallVector<int, 8> Mask;
5058 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5059 Mask.push_back(i + Half);
5060 Mask.push_back(i + NumElems + Half);
5062 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5065 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5066 // a generic shuffle instruction because the target has no such instructions.
5067 // Generate shuffles which repeat i16 and i8 several times until they can be
5068 // represented by v4f32 and then be manipulated by target suported shuffles.
5069 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5070 MVT VT = V.getSimpleValueType();
5071 int NumElems = VT.getVectorNumElements();
5074 while (NumElems > 4) {
5075 if (EltNo < NumElems/2) {
5076 V = getUnpackl(DAG, dl, VT, V, V);
5078 V = getUnpackh(DAG, dl, VT, V, V);
5079 EltNo -= NumElems/2;
5086 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5087 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5088 MVT VT = V.getSimpleValueType();
5091 if (VT.is128BitVector()) {
5092 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5093 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5094 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5096 } else if (VT.is256BitVector()) {
5097 // To use VPERMILPS to splat scalars, the second half of indicies must
5098 // refer to the higher part, which is a duplication of the lower one,
5099 // because VPERMILPS can only handle in-lane permutations.
5100 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5101 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5103 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5104 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5107 llvm_unreachable("Vector size not supported");
5109 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5112 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5113 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5114 MVT SrcVT = SV->getSimpleValueType(0);
5115 SDValue V1 = SV->getOperand(0);
5118 int EltNo = SV->getSplatIndex();
5119 int NumElems = SrcVT.getVectorNumElements();
5120 bool Is256BitVec = SrcVT.is256BitVector();
5122 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5123 "Unknown how to promote splat for type");
5125 // Extract the 128-bit part containing the splat element and update
5126 // the splat element index when it refers to the higher register.
5128 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5129 if (EltNo >= NumElems/2)
5130 EltNo -= NumElems/2;
5133 // All i16 and i8 vector types can't be used directly by a generic shuffle
5134 // instruction because the target has no such instruction. Generate shuffles
5135 // which repeat i16 and i8 several times until they fit in i32, and then can
5136 // be manipulated by target suported shuffles.
5137 MVT EltVT = SrcVT.getVectorElementType();
5138 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5139 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5141 // Recreate the 256-bit vector and place the same 128-bit vector
5142 // into the low and high part. This is necessary because we want
5143 // to use VPERM* to shuffle the vectors
5145 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5148 return getLegalSplat(DAG, V1, EltNo);
5151 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5152 /// vector of zero or undef vector. This produces a shuffle where the low
5153 /// element of V2 is swizzled into the zero/undef vector, landing at element
5154 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5155 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5157 const X86Subtarget *Subtarget,
5158 SelectionDAG &DAG) {
5159 MVT VT = V2.getSimpleValueType();
5161 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5162 unsigned NumElems = VT.getVectorNumElements();
5163 SmallVector<int, 16> MaskVec;
5164 for (unsigned i = 0; i != NumElems; ++i)
5165 // If this is the insertion idx, put the low elt of V2 here.
5166 MaskVec.push_back(i == Idx ? NumElems : i);
5167 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5170 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5171 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5172 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5173 /// shuffles which use a single input multiple times, and in those cases it will
5174 /// adjust the mask to only have indices within that single input.
5175 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5176 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5177 unsigned NumElems = VT.getVectorNumElements();
5181 bool IsFakeUnary = false;
5182 switch(N->getOpcode()) {
5184 ImmN = N->getOperand(N->getNumOperands()-1);
5185 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5186 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5188 case X86ISD::UNPCKH:
5189 DecodeUNPCKHMask(VT, Mask);
5190 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5192 case X86ISD::UNPCKL:
5193 DecodeUNPCKLMask(VT, Mask);
5194 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5196 case X86ISD::MOVHLPS:
5197 DecodeMOVHLPSMask(NumElems, Mask);
5198 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5200 case X86ISD::MOVLHPS:
5201 DecodeMOVLHPSMask(NumElems, Mask);
5202 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5204 case X86ISD::PALIGNR:
5205 ImmN = N->getOperand(N->getNumOperands()-1);
5206 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5208 case X86ISD::PSHUFD:
5209 case X86ISD::VPERMILP:
5210 ImmN = N->getOperand(N->getNumOperands()-1);
5211 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5214 case X86ISD::PSHUFHW:
5215 ImmN = N->getOperand(N->getNumOperands()-1);
5216 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5219 case X86ISD::PSHUFLW:
5220 ImmN = N->getOperand(N->getNumOperands()-1);
5221 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5224 case X86ISD::PSHUFB: {
5226 SDValue MaskNode = N->getOperand(1);
5227 while (MaskNode->getOpcode() == ISD::BITCAST)
5228 MaskNode = MaskNode->getOperand(0);
5230 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5231 // If we have a build-vector, then things are easy.
5232 EVT VT = MaskNode.getValueType();
5233 assert(VT.isVector() &&
5234 "Can't produce a non-vector with a build_vector!");
5235 if (!VT.isInteger())
5238 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5240 SmallVector<uint64_t, 32> RawMask;
5241 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5242 auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5245 APInt MaskElement = CN->getAPIntValue();
5247 // We now have to decode the element which could be any integer size and
5248 // extract each byte of it.
5249 for (int j = 0; j < NumBytesPerElement; ++j) {
5250 // Note that this is x86 and so always little endian: the low byte is
5251 // the first byte of the mask.
5252 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5253 MaskElement = MaskElement.lshr(8);
5256 DecodePSHUFBMask(RawMask, Mask);
5260 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5264 SDValue Ptr = MaskLoad->getBasePtr();
5265 if (Ptr->getOpcode() == X86ISD::Wrapper)
5266 Ptr = Ptr->getOperand(0);
5268 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5269 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5272 if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5273 // FIXME: Support AVX-512 here.
5274 if (!C->getType()->isVectorTy() ||
5275 (C->getNumElements() != 16 && C->getNumElements() != 32))
5278 assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5279 DecodePSHUFBMask(C, Mask);
5285 case X86ISD::VPERMI:
5286 ImmN = N->getOperand(N->getNumOperands()-1);
5287 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5291 case X86ISD::MOVSD: {
5292 // The index 0 always comes from the first element of the second source,
5293 // this is why MOVSS and MOVSD are used in the first place. The other
5294 // elements come from the other positions of the first source vector
5295 Mask.push_back(NumElems);
5296 for (unsigned i = 1; i != NumElems; ++i) {
5301 case X86ISD::VPERM2X128:
5302 ImmN = N->getOperand(N->getNumOperands()-1);
5303 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5304 if (Mask.empty()) return false;
5306 case X86ISD::MOVDDUP:
5307 case X86ISD::MOVLHPD:
5308 case X86ISD::MOVLPD:
5309 case X86ISD::MOVLPS:
5310 case X86ISD::MOVSHDUP:
5311 case X86ISD::MOVSLDUP:
5312 // Not yet implemented
5314 default: llvm_unreachable("unknown target shuffle node");
5317 // If we have a fake unary shuffle, the shuffle mask is spread across two
5318 // inputs that are actually the same node. Re-map the mask to always point
5319 // into the first input.
5322 if (M >= (int)Mask.size())
5328 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5329 /// element of the result of the vector shuffle.
5330 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5333 return SDValue(); // Limit search depth.
5335 SDValue V = SDValue(N, 0);
5336 EVT VT = V.getValueType();
5337 unsigned Opcode = V.getOpcode();
5339 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5340 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5341 int Elt = SV->getMaskElt(Index);
5344 return DAG.getUNDEF(VT.getVectorElementType());
5346 unsigned NumElems = VT.getVectorNumElements();
5347 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5348 : SV->getOperand(1);
5349 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5352 // Recurse into target specific vector shuffles to find scalars.
5353 if (isTargetShuffle(Opcode)) {
5354 MVT ShufVT = V.getSimpleValueType();
5355 unsigned NumElems = ShufVT.getVectorNumElements();
5356 SmallVector<int, 16> ShuffleMask;
5359 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5362 int Elt = ShuffleMask[Index];
5364 return DAG.getUNDEF(ShufVT.getVectorElementType());
5366 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5368 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5372 // Actual nodes that may contain scalar elements
5373 if (Opcode == ISD::BITCAST) {
5374 V = V.getOperand(0);
5375 EVT SrcVT = V.getValueType();
5376 unsigned NumElems = VT.getVectorNumElements();
5378 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5382 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5383 return (Index == 0) ? V.getOperand(0)
5384 : DAG.getUNDEF(VT.getVectorElementType());
5386 if (V.getOpcode() == ISD::BUILD_VECTOR)
5387 return V.getOperand(Index);
5392 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5393 /// shuffle operation which come from a consecutively from a zero. The
5394 /// search can start in two different directions, from left or right.
5395 /// We count undefs as zeros until PreferredNum is reached.
5396 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5397 unsigned NumElems, bool ZerosFromLeft,
5399 unsigned PreferredNum = -1U) {
5400 unsigned NumZeros = 0;
5401 for (unsigned i = 0; i != NumElems; ++i) {
5402 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5403 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5407 if (X86::isZeroNode(Elt))
5409 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5410 NumZeros = std::min(NumZeros + 1, PreferredNum);
5418 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5419 /// correspond consecutively to elements from one of the vector operands,
5420 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5422 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5423 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5424 unsigned NumElems, unsigned &OpNum) {
5425 bool SeenV1 = false;
5426 bool SeenV2 = false;
5428 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5429 int Idx = SVOp->getMaskElt(i);
5430 // Ignore undef indicies
5434 if (Idx < (int)NumElems)
5439 // Only accept consecutive elements from the same vector
5440 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5444 OpNum = SeenV1 ? 0 : 1;
5448 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5449 /// logical left shift of a vector.
5450 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5451 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5453 SVOp->getSimpleValueType(0).getVectorNumElements();
5454 unsigned NumZeros = getNumOfConsecutiveZeros(
5455 SVOp, NumElems, false /* check zeros from right */, DAG,
5456 SVOp->getMaskElt(0));
5462 // Considering the elements in the mask that are not consecutive zeros,
5463 // check if they consecutively come from only one of the source vectors.
5465 // V1 = {X, A, B, C} 0
5467 // vector_shuffle V1, V2 <1, 2, 3, X>
5469 if (!isShuffleMaskConsecutive(SVOp,
5470 0, // Mask Start Index
5471 NumElems-NumZeros, // Mask End Index(exclusive)
5472 NumZeros, // Where to start looking in the src vector
5473 NumElems, // Number of elements in vector
5474 OpSrc)) // Which source operand ?
5479 ShVal = SVOp->getOperand(OpSrc);
5483 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5484 /// logical left shift of a vector.
5485 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5486 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5488 SVOp->getSimpleValueType(0).getVectorNumElements();
5489 unsigned NumZeros = getNumOfConsecutiveZeros(
5490 SVOp, NumElems, true /* check zeros from left */, DAG,
5491 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5497 // Considering the elements in the mask that are not consecutive zeros,
5498 // check if they consecutively come from only one of the source vectors.
5500 // 0 { A, B, X, X } = V2
5502 // vector_shuffle V1, V2 <X, X, 4, 5>
5504 if (!isShuffleMaskConsecutive(SVOp,
5505 NumZeros, // Mask Start Index
5506 NumElems, // Mask End Index(exclusive)
5507 0, // Where to start looking in the src vector
5508 NumElems, // Number of elements in vector
5509 OpSrc)) // Which source operand ?
5514 ShVal = SVOp->getOperand(OpSrc);
5518 /// isVectorShift - Returns true if the shuffle can be implemented as a
5519 /// logical left or right shift of a vector.
5520 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5521 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5522 // Although the logic below support any bitwidth size, there are no
5523 // shift instructions which handle more than 128-bit vectors.
5524 if (!SVOp->getSimpleValueType(0).is128BitVector())
5527 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5528 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5534 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5536 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5537 unsigned NumNonZero, unsigned NumZero,
5539 const X86Subtarget* Subtarget,
5540 const TargetLowering &TLI) {
5547 for (unsigned i = 0; i < 16; ++i) {
5548 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5549 if (ThisIsNonZero && First) {
5551 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5553 V = DAG.getUNDEF(MVT::v8i16);
5558 SDValue ThisElt, LastElt;
5559 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5560 if (LastIsNonZero) {
5561 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5562 MVT::i16, Op.getOperand(i-1));
5564 if (ThisIsNonZero) {
5565 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5566 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5567 ThisElt, DAG.getConstant(8, MVT::i8));
5569 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5573 if (ThisElt.getNode())
5574 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5575 DAG.getIntPtrConstant(i/2));
5579 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5582 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5584 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5585 unsigned NumNonZero, unsigned NumZero,
5587 const X86Subtarget* Subtarget,
5588 const TargetLowering &TLI) {
5595 for (unsigned i = 0; i < 8; ++i) {
5596 bool isNonZero = (NonZeros & (1 << i)) != 0;
5600 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5602 V = DAG.getUNDEF(MVT::v8i16);
5605 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5606 MVT::v8i16, V, Op.getOperand(i),
5607 DAG.getIntPtrConstant(i));
5614 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5615 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5616 unsigned NonZeros, unsigned NumNonZero,
5617 unsigned NumZero, SelectionDAG &DAG,
5618 const X86Subtarget *Subtarget,
5619 const TargetLowering &TLI) {
5620 // We know there's at least one non-zero element
5621 unsigned FirstNonZeroIdx = 0;
5622 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5623 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5624 X86::isZeroNode(FirstNonZero)) {
5626 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5629 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5630 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5633 SDValue V = FirstNonZero.getOperand(0);
5634 MVT VVT = V.getSimpleValueType();
5635 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5638 unsigned FirstNonZeroDst =
5639 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5640 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5641 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5642 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5644 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5645 SDValue Elem = Op.getOperand(Idx);
5646 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5649 // TODO: What else can be here? Deal with it.
5650 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5653 // TODO: Some optimizations are still possible here
5654 // ex: Getting one element from a vector, and the rest from another.
5655 if (Elem.getOperand(0) != V)
5658 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5661 else if (IncorrectIdx == -1U) {
5665 // There was already one element with an incorrect index.
5666 // We can't optimize this case to an insertps.
5670 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5672 EVT VT = Op.getSimpleValueType();
5673 unsigned ElementMoveMask = 0;
5674 if (IncorrectIdx == -1U)
5675 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5677 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5679 SDValue InsertpsMask =
5680 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5681 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5687 /// getVShift - Return a vector logical shift node.
5689 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5690 unsigned NumBits, SelectionDAG &DAG,
5691 const TargetLowering &TLI, SDLoc dl) {
5692 assert(VT.is128BitVector() && "Unknown type for VShift");
5693 EVT ShVT = MVT::v2i64;
5694 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5695 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5696 return DAG.getNode(ISD::BITCAST, dl, VT,
5697 DAG.getNode(Opc, dl, ShVT, SrcOp,
5698 DAG.getConstant(NumBits,
5699 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5703 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5705 // Check if the scalar load can be widened into a vector load. And if
5706 // the address is "base + cst" see if the cst can be "absorbed" into
5707 // the shuffle mask.
5708 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5709 SDValue Ptr = LD->getBasePtr();
5710 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5712 EVT PVT = LD->getValueType(0);
5713 if (PVT != MVT::i32 && PVT != MVT::f32)
5718 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5719 FI = FINode->getIndex();
5721 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5722 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5723 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5724 Offset = Ptr.getConstantOperandVal(1);
5725 Ptr = Ptr.getOperand(0);
5730 // FIXME: 256-bit vector instructions don't require a strict alignment,
5731 // improve this code to support it better.
5732 unsigned RequiredAlign = VT.getSizeInBits()/8;
5733 SDValue Chain = LD->getChain();
5734 // Make sure the stack object alignment is at least 16 or 32.
5735 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5736 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5737 if (MFI->isFixedObjectIndex(FI)) {
5738 // Can't change the alignment. FIXME: It's possible to compute
5739 // the exact stack offset and reference FI + adjust offset instead.
5740 // If someone *really* cares about this. That's the way to implement it.
5743 MFI->setObjectAlignment(FI, RequiredAlign);
5747 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5748 // Ptr + (Offset & ~15).
5751 if ((Offset % RequiredAlign) & 3)
5753 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5755 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5756 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5758 int EltNo = (Offset - StartOffset) >> 2;
5759 unsigned NumElems = VT.getVectorNumElements();
5761 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5762 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5763 LD->getPointerInfo().getWithOffset(StartOffset),
5764 false, false, false, 0);
5766 SmallVector<int, 8> Mask;
5767 for (unsigned i = 0; i != NumElems; ++i)
5768 Mask.push_back(EltNo);
5770 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5776 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5777 /// vector of type 'VT', see if the elements can be replaced by a single large
5778 /// load which has the same value as a build_vector whose operands are 'elts'.
5780 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5782 /// FIXME: we'd also like to handle the case where the last elements are zero
5783 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5784 /// There's even a handy isZeroNode for that purpose.
5785 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5786 SDLoc &DL, SelectionDAG &DAG,
5787 bool isAfterLegalize) {
5788 EVT EltVT = VT.getVectorElementType();
5789 unsigned NumElems = Elts.size();
5791 LoadSDNode *LDBase = nullptr;
5792 unsigned LastLoadedElt = -1U;
5794 // For each element in the initializer, see if we've found a load or an undef.
5795 // If we don't find an initial load element, or later load elements are
5796 // non-consecutive, bail out.
5797 for (unsigned i = 0; i < NumElems; ++i) {
5798 SDValue Elt = Elts[i];
5800 if (!Elt.getNode() ||
5801 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5804 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5806 LDBase = cast<LoadSDNode>(Elt.getNode());
5810 if (Elt.getOpcode() == ISD::UNDEF)
5813 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5814 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5819 // If we have found an entire vector of loads and undefs, then return a large
5820 // load of the entire vector width starting at the base pointer. If we found
5821 // consecutive loads for the low half, generate a vzext_load node.
5822 if (LastLoadedElt == NumElems - 1) {
5824 if (isAfterLegalize &&
5825 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5828 SDValue NewLd = SDValue();
5830 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5831 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5832 LDBase->getPointerInfo(),
5833 LDBase->isVolatile(), LDBase->isNonTemporal(),
5834 LDBase->isInvariant(), 0);
5835 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5836 LDBase->getPointerInfo(),
5837 LDBase->isVolatile(), LDBase->isNonTemporal(),
5838 LDBase->isInvariant(), LDBase->getAlignment());
5840 if (LDBase->hasAnyUseOfValue(1)) {
5841 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5843 SDValue(NewLd.getNode(), 1));
5844 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5845 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5846 SDValue(NewLd.getNode(), 1));
5851 if (NumElems == 4 && LastLoadedElt == 1 &&
5852 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5853 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5854 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5856 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5857 LDBase->getPointerInfo(),
5858 LDBase->getAlignment(),
5859 false/*isVolatile*/, true/*ReadMem*/,
5862 // Make sure the newly-created LOAD is in the same position as LDBase in
5863 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5864 // update uses of LDBase's output chain to use the TokenFactor.
5865 if (LDBase->hasAnyUseOfValue(1)) {
5866 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5867 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5868 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5869 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5870 SDValue(ResNode.getNode(), 1));
5873 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5878 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5879 /// to generate a splat value for the following cases:
5880 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5881 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5882 /// a scalar load, or a constant.
5883 /// The VBROADCAST node is returned when a pattern is found,
5884 /// or SDValue() otherwise.
5885 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5886 SelectionDAG &DAG) {
5887 if (!Subtarget->hasFp256())
5890 MVT VT = Op.getSimpleValueType();
5893 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5894 "Unsupported vector type for broadcast.");
5899 switch (Op.getOpcode()) {
5901 // Unknown pattern found.
5904 case ISD::BUILD_VECTOR: {
5905 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5906 BitVector UndefElements;
5907 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5909 // We need a splat of a single value to use broadcast, and it doesn't
5910 // make any sense if the value is only in one element of the vector.
5911 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5915 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5916 Ld.getOpcode() == ISD::ConstantFP);
5918 // Make sure that all of the users of a non-constant load are from the
5919 // BUILD_VECTOR node.
5920 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5925 case ISD::VECTOR_SHUFFLE: {
5926 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5928 // Shuffles must have a splat mask where the first element is
5930 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5933 SDValue Sc = Op.getOperand(0);
5934 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5935 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5937 if (!Subtarget->hasInt256())
5940 // Use the register form of the broadcast instruction available on AVX2.
5941 if (VT.getSizeInBits() >= 256)
5942 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5943 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5946 Ld = Sc.getOperand(0);
5947 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5948 Ld.getOpcode() == ISD::ConstantFP);
5950 // The scalar_to_vector node and the suspected
5951 // load node must have exactly one user.
5952 // Constants may have multiple users.
5954 // AVX-512 has register version of the broadcast
5955 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5956 Ld.getValueType().getSizeInBits() >= 32;
5957 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5964 bool IsGE256 = (VT.getSizeInBits() >= 256);
5966 // Handle the broadcasting a single constant scalar from the constant pool
5967 // into a vector. On Sandybridge it is still better to load a constant vector
5968 // from the constant pool and not to broadcast it from a scalar.
5969 if (ConstSplatVal && Subtarget->hasInt256()) {
5970 EVT CVT = Ld.getValueType();
5971 assert(!CVT.isVector() && "Must not broadcast a vector type");
5972 unsigned ScalarSize = CVT.getSizeInBits();
5974 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5975 const Constant *C = nullptr;
5976 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5977 C = CI->getConstantIntValue();
5978 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5979 C = CF->getConstantFPValue();
5981 assert(C && "Invalid constant type");
5983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5984 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5985 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5986 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5987 MachinePointerInfo::getConstantPool(),
5988 false, false, false, Alignment);
5990 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5994 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5995 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5997 // Handle AVX2 in-register broadcasts.
5998 if (!IsLoad && Subtarget->hasInt256() &&
5999 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6000 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6002 // The scalar source must be a normal load.
6006 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6007 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6009 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6010 // double since there is no vbroadcastsd xmm
6011 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6012 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6013 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6016 // Unsupported broadcast.
6020 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6021 /// underlying vector and index.
6023 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6025 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6027 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6028 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6031 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6033 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6035 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6036 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6039 // In this case the vector is the extract_subvector expression and the index
6040 // is 2, as specified by the shuffle.
6041 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6042 SDValue ShuffleVec = SVOp->getOperand(0);
6043 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6044 assert(ShuffleVecVT.getVectorElementType() ==
6045 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6047 int ShuffleIdx = SVOp->getMaskElt(Idx);
6048 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6049 ExtractedFromVec = ShuffleVec;
6055 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6056 MVT VT = Op.getSimpleValueType();
6058 // Skip if insert_vec_elt is not supported.
6059 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6060 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6064 unsigned NumElems = Op.getNumOperands();
6068 SmallVector<unsigned, 4> InsertIndices;
6069 SmallVector<int, 8> Mask(NumElems, -1);
6071 for (unsigned i = 0; i != NumElems; ++i) {
6072 unsigned Opc = Op.getOperand(i).getOpcode();
6074 if (Opc == ISD::UNDEF)
6077 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6078 // Quit if more than 1 elements need inserting.
6079 if (InsertIndices.size() > 1)
6082 InsertIndices.push_back(i);
6086 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6087 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6088 // Quit if non-constant index.
6089 if (!isa<ConstantSDNode>(ExtIdx))
6091 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6093 // Quit if extracted from vector of different type.
6094 if (ExtractedFromVec.getValueType() != VT)
6097 if (!VecIn1.getNode())
6098 VecIn1 = ExtractedFromVec;
6099 else if (VecIn1 != ExtractedFromVec) {
6100 if (!VecIn2.getNode())
6101 VecIn2 = ExtractedFromVec;
6102 else if (VecIn2 != ExtractedFromVec)
6103 // Quit if more than 2 vectors to shuffle
6107 if (ExtractedFromVec == VecIn1)
6109 else if (ExtractedFromVec == VecIn2)
6110 Mask[i] = Idx + NumElems;
6113 if (!VecIn1.getNode())
6116 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6117 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6118 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6119 unsigned Idx = InsertIndices[i];
6120 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6121 DAG.getIntPtrConstant(Idx));
6127 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6129 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6131 MVT VT = Op.getSimpleValueType();
6132 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6133 "Unexpected type in LowerBUILD_VECTORvXi1!");
6136 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6137 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6138 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6139 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6142 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6143 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6144 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6145 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6148 bool AllContants = true;
6149 uint64_t Immediate = 0;
6150 int NonConstIdx = -1;
6151 bool IsSplat = true;
6152 unsigned NumNonConsts = 0;
6153 unsigned NumConsts = 0;
6154 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6155 SDValue In = Op.getOperand(idx);
6156 if (In.getOpcode() == ISD::UNDEF)
6158 if (!isa<ConstantSDNode>(In)) {
6159 AllContants = false;
6165 if (cast<ConstantSDNode>(In)->getZExtValue())
6166 Immediate |= (1ULL << idx);
6168 if (In != Op.getOperand(0))
6173 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6174 DAG.getConstant(Immediate, MVT::i16));
6175 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6176 DAG.getIntPtrConstant(0));
6179 if (NumNonConsts == 1 && NonConstIdx != 0) {
6182 SDValue VecAsImm = DAG.getConstant(Immediate,
6183 MVT::getIntegerVT(VT.getSizeInBits()));
6184 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6187 DstVec = DAG.getUNDEF(VT);
6188 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6189 Op.getOperand(NonConstIdx),
6190 DAG.getIntPtrConstant(NonConstIdx));
6192 if (!IsSplat && (NonConstIdx != 0))
6193 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6194 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6197 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6198 DAG.getConstant(-1, SelectVT),
6199 DAG.getConstant(0, SelectVT));
6201 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6202 DAG.getConstant((Immediate | 1), SelectVT),
6203 DAG.getConstant(Immediate, SelectVT));
6204 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6207 /// \brief Return true if \p N implements a horizontal binop and return the
6208 /// operands for the horizontal binop into V0 and V1.
6210 /// This is a helper function of PerformBUILD_VECTORCombine.
6211 /// This function checks that the build_vector \p N in input implements a
6212 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6213 /// operation to match.
6214 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6215 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6216 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6219 /// This function only analyzes elements of \p N whose indices are
6220 /// in range [BaseIdx, LastIdx).
6221 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6223 unsigned BaseIdx, unsigned LastIdx,
6224 SDValue &V0, SDValue &V1) {
6225 EVT VT = N->getValueType(0);
6227 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6228 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6229 "Invalid Vector in input!");
6231 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6232 bool CanFold = true;
6233 unsigned ExpectedVExtractIdx = BaseIdx;
6234 unsigned NumElts = LastIdx - BaseIdx;
6235 V0 = DAG.getUNDEF(VT);
6236 V1 = DAG.getUNDEF(VT);
6238 // Check if N implements a horizontal binop.
6239 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6240 SDValue Op = N->getOperand(i + BaseIdx);
6243 if (Op->getOpcode() == ISD::UNDEF) {
6244 // Update the expected vector extract index.
6245 if (i * 2 == NumElts)
6246 ExpectedVExtractIdx = BaseIdx;
6247 ExpectedVExtractIdx += 2;
6251 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6256 SDValue Op0 = Op.getOperand(0);
6257 SDValue Op1 = Op.getOperand(1);
6259 // Try to match the following pattern:
6260 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6261 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6262 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6263 Op0.getOperand(0) == Op1.getOperand(0) &&
6264 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6265 isa<ConstantSDNode>(Op1.getOperand(1)));
6269 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6270 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6272 if (i * 2 < NumElts) {
6273 if (V0.getOpcode() == ISD::UNDEF)
6274 V0 = Op0.getOperand(0);
6276 if (V1.getOpcode() == ISD::UNDEF)
6277 V1 = Op0.getOperand(0);
6278 if (i * 2 == NumElts)
6279 ExpectedVExtractIdx = BaseIdx;
6282 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6283 if (I0 == ExpectedVExtractIdx)
6284 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6285 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6286 // Try to match the following dag sequence:
6287 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6288 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6292 ExpectedVExtractIdx += 2;
6298 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6299 /// a concat_vector.
6301 /// This is a helper function of PerformBUILD_VECTORCombine.
6302 /// This function expects two 256-bit vectors called V0 and V1.
6303 /// At first, each vector is split into two separate 128-bit vectors.
6304 /// Then, the resulting 128-bit vectors are used to implement two
6305 /// horizontal binary operations.
6307 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6309 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6310 /// the two new horizontal binop.
6311 /// When Mode is set, the first horizontal binop dag node would take as input
6312 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6313 /// horizontal binop dag node would take as input the lower 128-bit of V1
6314 /// and the upper 128-bit of V1.
6316 /// HADD V0_LO, V0_HI
6317 /// HADD V1_LO, V1_HI
6319 /// Otherwise, the first horizontal binop dag node takes as input the lower
6320 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6321 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6323 /// HADD V0_LO, V1_LO
6324 /// HADD V0_HI, V1_HI
6326 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6327 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6328 /// the upper 128-bits of the result.
6329 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6330 SDLoc DL, SelectionDAG &DAG,
6331 unsigned X86Opcode, bool Mode,
6332 bool isUndefLO, bool isUndefHI) {
6333 EVT VT = V0.getValueType();
6334 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6335 "Invalid nodes in input!");
6337 unsigned NumElts = VT.getVectorNumElements();
6338 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6339 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6340 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6341 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6342 EVT NewVT = V0_LO.getValueType();
6344 SDValue LO = DAG.getUNDEF(NewVT);
6345 SDValue HI = DAG.getUNDEF(NewVT);
6348 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6349 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6350 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6351 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6352 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6354 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6355 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6356 V1_LO->getOpcode() != ISD::UNDEF))
6357 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6359 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6360 V1_HI->getOpcode() != ISD::UNDEF))
6361 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6364 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6367 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6368 /// sequence of 'vadd + vsub + blendi'.
6369 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6370 const X86Subtarget *Subtarget) {
6372 EVT VT = BV->getValueType(0);
6373 unsigned NumElts = VT.getVectorNumElements();
6374 SDValue InVec0 = DAG.getUNDEF(VT);
6375 SDValue InVec1 = DAG.getUNDEF(VT);
6377 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6378 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6380 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6381 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6382 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6385 // Odd-numbered elements in the input build vector are obtained from
6386 // adding two integer/float elements.
6387 // Even-numbered elements in the input build vector are obtained from
6388 // subtracting two integer/float elements.
6389 unsigned ExpectedOpcode = ISD::FSUB;
6390 unsigned NextExpectedOpcode = ISD::FADD;
6391 bool AddFound = false;
6392 bool SubFound = false;
6394 for (unsigned i = 0, e = NumElts; i != e; i++) {
6395 SDValue Op = BV->getOperand(i);
6397 // Skip 'undef' values.
6398 unsigned Opcode = Op.getOpcode();
6399 if (Opcode == ISD::UNDEF) {
6400 std::swap(ExpectedOpcode, NextExpectedOpcode);
6404 // Early exit if we found an unexpected opcode.
6405 if (Opcode != ExpectedOpcode)
6408 SDValue Op0 = Op.getOperand(0);
6409 SDValue Op1 = Op.getOperand(1);
6411 // Try to match the following pattern:
6412 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6413 // Early exit if we cannot match that sequence.
6414 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6415 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6416 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6417 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6418 Op0.getOperand(1) != Op1.getOperand(1))
6421 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6425 // We found a valid add/sub node. Update the information accordingly.
6431 // Update InVec0 and InVec1.
6432 if (InVec0.getOpcode() == ISD::UNDEF)
6433 InVec0 = Op0.getOperand(0);
6434 if (InVec1.getOpcode() == ISD::UNDEF)
6435 InVec1 = Op1.getOperand(0);
6437 // Make sure that operands in input to each add/sub node always
6438 // come from a same pair of vectors.
6439 if (InVec0 != Op0.getOperand(0)) {
6440 if (ExpectedOpcode == ISD::FSUB)
6443 // FADD is commutable. Try to commute the operands
6444 // and then test again.
6445 std::swap(Op0, Op1);
6446 if (InVec0 != Op0.getOperand(0))
6450 if (InVec1 != Op1.getOperand(0))
6453 // Update the pair of expected opcodes.
6454 std::swap(ExpectedOpcode, NextExpectedOpcode);
6457 // Don't try to fold this build_vector into a VSELECT if it has
6458 // too many UNDEF operands.
6459 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6460 InVec1.getOpcode() != ISD::UNDEF) {
6461 // Emit a sequence of vector add and sub followed by a VSELECT.
6462 // The new VSELECT will be lowered into a BLENDI.
6463 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6464 // and emit a single ADDSUB instruction.
6465 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6466 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6468 // Construct the VSELECT mask.
6469 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6470 EVT SVT = MaskVT.getVectorElementType();
6471 unsigned SVTBits = SVT.getSizeInBits();
6472 SmallVector<SDValue, 8> Ops;
6474 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6475 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6476 APInt::getAllOnesValue(SVTBits);
6477 SDValue Constant = DAG.getConstant(Value, SVT);
6478 Ops.push_back(Constant);
6481 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6482 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6488 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6489 const X86Subtarget *Subtarget) {
6491 EVT VT = N->getValueType(0);
6492 unsigned NumElts = VT.getVectorNumElements();
6493 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6494 SDValue InVec0, InVec1;
6496 // Try to match an ADDSUB.
6497 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6498 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6499 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6500 if (Value.getNode())
6504 // Try to match horizontal ADD/SUB.
6505 unsigned NumUndefsLO = 0;
6506 unsigned NumUndefsHI = 0;
6507 unsigned Half = NumElts/2;
6509 // Count the number of UNDEF operands in the build_vector in input.
6510 for (unsigned i = 0, e = Half; i != e; ++i)
6511 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6514 for (unsigned i = Half, e = NumElts; i != e; ++i)
6515 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6518 // Early exit if this is either a build_vector of all UNDEFs or all the
6519 // operands but one are UNDEF.
6520 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6523 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6524 // Try to match an SSE3 float HADD/HSUB.
6525 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6526 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6528 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6529 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6530 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6531 // Try to match an SSSE3 integer HADD/HSUB.
6532 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6533 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6535 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6536 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6539 if (!Subtarget->hasAVX())
6542 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6543 // Try to match an AVX horizontal add/sub of packed single/double
6544 // precision floating point values from 256-bit vectors.
6545 SDValue InVec2, InVec3;
6546 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6547 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6548 ((InVec0.getOpcode() == ISD::UNDEF ||
6549 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6550 ((InVec1.getOpcode() == ISD::UNDEF ||
6551 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6552 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6554 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6555 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6556 ((InVec0.getOpcode() == ISD::UNDEF ||
6557 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6558 ((InVec1.getOpcode() == ISD::UNDEF ||
6559 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6560 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6561 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6562 // Try to match an AVX2 horizontal add/sub of signed integers.
6563 SDValue InVec2, InVec3;
6565 bool CanFold = true;
6567 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6568 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6569 ((InVec0.getOpcode() == ISD::UNDEF ||
6570 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6571 ((InVec1.getOpcode() == ISD::UNDEF ||
6572 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6573 X86Opcode = X86ISD::HADD;
6574 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6575 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6576 ((InVec0.getOpcode() == ISD::UNDEF ||
6577 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6578 ((InVec1.getOpcode() == ISD::UNDEF ||
6579 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6580 X86Opcode = X86ISD::HSUB;
6585 // Fold this build_vector into a single horizontal add/sub.
6586 // Do this only if the target has AVX2.
6587 if (Subtarget->hasAVX2())
6588 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6590 // Do not try to expand this build_vector into a pair of horizontal
6591 // add/sub if we can emit a pair of scalar add/sub.
6592 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6595 // Convert this build_vector into a pair of horizontal binop followed by
6597 bool isUndefLO = NumUndefsLO == Half;
6598 bool isUndefHI = NumUndefsHI == Half;
6599 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6600 isUndefLO, isUndefHI);
6604 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6605 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6607 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6608 X86Opcode = X86ISD::HADD;
6609 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6610 X86Opcode = X86ISD::HSUB;
6611 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6612 X86Opcode = X86ISD::FHADD;
6613 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6614 X86Opcode = X86ISD::FHSUB;
6618 // Don't try to expand this build_vector into a pair of horizontal add/sub
6619 // if we can simply emit a pair of scalar add/sub.
6620 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6623 // Convert this build_vector into two horizontal add/sub followed by
6625 bool isUndefLO = NumUndefsLO == Half;
6626 bool isUndefHI = NumUndefsHI == Half;
6627 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6628 isUndefLO, isUndefHI);
6635 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6638 MVT VT = Op.getSimpleValueType();
6639 MVT ExtVT = VT.getVectorElementType();
6640 unsigned NumElems = Op.getNumOperands();
6642 // Generate vectors for predicate vectors.
6643 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6644 return LowerBUILD_VECTORvXi1(Op, DAG);
6646 // Vectors containing all zeros can be matched by pxor and xorps later
6647 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6648 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6649 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6650 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6653 return getZeroVector(VT, Subtarget, DAG, dl);
6656 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6657 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6658 // vpcmpeqd on 256-bit vectors.
6659 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6660 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6663 if (!VT.is512BitVector())
6664 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6667 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6668 if (Broadcast.getNode())
6671 unsigned EVTBits = ExtVT.getSizeInBits();
6673 unsigned NumZero = 0;
6674 unsigned NumNonZero = 0;
6675 unsigned NonZeros = 0;
6676 bool IsAllConstants = true;
6677 SmallSet<SDValue, 8> Values;
6678 for (unsigned i = 0; i < NumElems; ++i) {
6679 SDValue Elt = Op.getOperand(i);
6680 if (Elt.getOpcode() == ISD::UNDEF)
6683 if (Elt.getOpcode() != ISD::Constant &&
6684 Elt.getOpcode() != ISD::ConstantFP)
6685 IsAllConstants = false;
6686 if (X86::isZeroNode(Elt))
6689 NonZeros |= (1 << i);
6694 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6695 if (NumNonZero == 0)
6696 return DAG.getUNDEF(VT);
6698 // Special case for single non-zero, non-undef, element.
6699 if (NumNonZero == 1) {
6700 unsigned Idx = countTrailingZeros(NonZeros);
6701 SDValue Item = Op.getOperand(Idx);
6703 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6704 // the value are obviously zero, truncate the value to i32 and do the
6705 // insertion that way. Only do this if the value is non-constant or if the
6706 // value is a constant being inserted into element 0. It is cheaper to do
6707 // a constant pool load than it is to do a movd + shuffle.
6708 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6709 (!IsAllConstants || Idx == 0)) {
6710 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6712 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6713 EVT VecVT = MVT::v4i32;
6714 unsigned VecElts = 4;
6716 // Truncate the value (which may itself be a constant) to i32, and
6717 // convert it to a vector with movd (S2V+shuffle to zero extend).
6718 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6719 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6720 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6722 // Now we have our 32-bit value zero extended in the low element of
6723 // a vector. If Idx != 0, swizzle it into place.
6725 SmallVector<int, 4> Mask;
6726 Mask.push_back(Idx);
6727 for (unsigned i = 1; i != VecElts; ++i)
6729 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6732 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6736 // If we have a constant or non-constant insertion into the low element of
6737 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6738 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6739 // depending on what the source datatype is.
6742 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6744 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6745 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6746 if (VT.is256BitVector() || VT.is512BitVector()) {
6747 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6748 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6749 Item, DAG.getIntPtrConstant(0));
6751 assert(VT.is128BitVector() && "Expected an SSE value type!");
6752 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6753 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6754 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6757 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6758 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6759 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6760 if (VT.is256BitVector()) {
6761 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6762 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6764 assert(VT.is128BitVector() && "Expected an SSE value type!");
6765 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6767 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6771 // Is it a vector logical left shift?
6772 if (NumElems == 2 && Idx == 1 &&
6773 X86::isZeroNode(Op.getOperand(0)) &&
6774 !X86::isZeroNode(Op.getOperand(1))) {
6775 unsigned NumBits = VT.getSizeInBits();
6776 return getVShift(true, VT,
6777 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6778 VT, Op.getOperand(1)),
6779 NumBits/2, DAG, *this, dl);
6782 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6785 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6786 // is a non-constant being inserted into an element other than the low one,
6787 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6788 // movd/movss) to move this into the low element, then shuffle it into
6790 if (EVTBits == 32) {
6791 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6793 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6794 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6795 SmallVector<int, 8> MaskVec;
6796 for (unsigned i = 0; i != NumElems; ++i)
6797 MaskVec.push_back(i == Idx ? 0 : 1);
6798 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6802 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6803 if (Values.size() == 1) {
6804 if (EVTBits == 32) {
6805 // Instead of a shuffle like this:
6806 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6807 // Check if it's possible to issue this instead.
6808 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6809 unsigned Idx = countTrailingZeros(NonZeros);
6810 SDValue Item = Op.getOperand(Idx);
6811 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6812 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6817 // A vector full of immediates; various special cases are already
6818 // handled, so this is best done with a single constant-pool load.
6822 // For AVX-length vectors, build the individual 128-bit pieces and use
6823 // shuffles to put them in place.
6824 if (VT.is256BitVector() || VT.is512BitVector()) {
6825 SmallVector<SDValue, 64> V;
6826 for (unsigned i = 0; i != NumElems; ++i)
6827 V.push_back(Op.getOperand(i));
6829 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6831 // Build both the lower and upper subvector.
6832 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6833 makeArrayRef(&V[0], NumElems/2));
6834 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6835 makeArrayRef(&V[NumElems / 2], NumElems/2));
6837 // Recreate the wider vector with the lower and upper part.
6838 if (VT.is256BitVector())
6839 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6840 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6843 // Let legalizer expand 2-wide build_vectors.
6844 if (EVTBits == 64) {
6845 if (NumNonZero == 1) {
6846 // One half is zero or undef.
6847 unsigned Idx = countTrailingZeros(NonZeros);
6848 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6849 Op.getOperand(Idx));
6850 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6855 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6856 if (EVTBits == 8 && NumElems == 16) {
6857 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6859 if (V.getNode()) return V;
6862 if (EVTBits == 16 && NumElems == 8) {
6863 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6865 if (V.getNode()) return V;
6868 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6869 if (EVTBits == 32 && NumElems == 4) {
6870 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6871 NumZero, DAG, Subtarget, *this);
6876 // If element VT is == 32 bits, turn it into a number of shuffles.
6877 SmallVector<SDValue, 8> V(NumElems);
6878 if (NumElems == 4 && NumZero > 0) {
6879 for (unsigned i = 0; i < 4; ++i) {
6880 bool isZero = !(NonZeros & (1 << i));
6882 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6884 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6887 for (unsigned i = 0; i < 2; ++i) {
6888 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6891 V[i] = V[i*2]; // Must be a zero vector.
6894 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6897 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6900 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6905 bool Reverse1 = (NonZeros & 0x3) == 2;
6906 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6910 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6911 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6913 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6916 if (Values.size() > 1 && VT.is128BitVector()) {
6917 // Check for a build vector of consecutive loads.
6918 for (unsigned i = 0; i < NumElems; ++i)
6919 V[i] = Op.getOperand(i);
6921 // Check for elements which are consecutive loads.
6922 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6926 // Check for a build vector from mostly shuffle plus few inserting.
6927 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6931 // For SSE 4.1, use insertps to put the high elements into the low element.
6932 if (getSubtarget()->hasSSE41()) {
6934 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6935 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6937 Result = DAG.getUNDEF(VT);
6939 for (unsigned i = 1; i < NumElems; ++i) {
6940 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6941 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6942 Op.getOperand(i), DAG.getIntPtrConstant(i));
6947 // Otherwise, expand into a number of unpckl*, start by extending each of
6948 // our (non-undef) elements to the full vector width with the element in the
6949 // bottom slot of the vector (which generates no code for SSE).
6950 for (unsigned i = 0; i < NumElems; ++i) {
6951 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6952 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6954 V[i] = DAG.getUNDEF(VT);
6957 // Next, we iteratively mix elements, e.g. for v4f32:
6958 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6959 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6960 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6961 unsigned EltStride = NumElems >> 1;
6962 while (EltStride != 0) {
6963 for (unsigned i = 0; i < EltStride; ++i) {
6964 // If V[i+EltStride] is undef and this is the first round of mixing,
6965 // then it is safe to just drop this shuffle: V[i] is already in the
6966 // right place, the one element (since it's the first round) being
6967 // inserted as undef can be dropped. This isn't safe for successive
6968 // rounds because they will permute elements within both vectors.
6969 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6970 EltStride == NumElems/2)
6973 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6982 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6983 // to create 256-bit vectors from two other 128-bit ones.
6984 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6986 MVT ResVT = Op.getSimpleValueType();
6988 assert((ResVT.is256BitVector() ||
6989 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6991 SDValue V1 = Op.getOperand(0);
6992 SDValue V2 = Op.getOperand(1);
6993 unsigned NumElems = ResVT.getVectorNumElements();
6994 if(ResVT.is256BitVector())
6995 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6997 if (Op.getNumOperands() == 4) {
6998 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6999 ResVT.getVectorNumElements()/2);
7000 SDValue V3 = Op.getOperand(2);
7001 SDValue V4 = Op.getOperand(3);
7002 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7003 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7005 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7008 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7009 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7010 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7011 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7012 Op.getNumOperands() == 4)));
7014 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7015 // from two other 128-bit ones.
7017 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7018 return LowerAVXCONCAT_VECTORS(Op, DAG);
7022 //===----------------------------------------------------------------------===//
7023 // Vector shuffle lowering
7025 // This is an experimental code path for lowering vector shuffles on x86. It is
7026 // designed to handle arbitrary vector shuffles and blends, gracefully
7027 // degrading performance as necessary. It works hard to recognize idiomatic
7028 // shuffles and lower them to optimal instruction patterns without leaving
7029 // a framework that allows reasonably efficient handling of all vector shuffle
7031 //===----------------------------------------------------------------------===//
7033 /// \brief Tiny helper function to identify a no-op mask.
7035 /// This is a somewhat boring predicate function. It checks whether the mask
7036 /// array input, which is assumed to be a single-input shuffle mask of the kind
7037 /// used by the X86 shuffle instructions (not a fully general
7038 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7039 /// in-place shuffle are 'no-op's.
7040 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7041 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7042 if (Mask[i] != -1 && Mask[i] != i)
7047 /// \brief Helper function to classify a mask as a single-input mask.
7049 /// This isn't a generic single-input test because in the vector shuffle
7050 /// lowering we canonicalize single inputs to be the first input operand. This
7051 /// means we can more quickly test for a single input by only checking whether
7052 /// an input from the second operand exists. We also assume that the size of
7053 /// mask corresponds to the size of the input vectors which isn't true in the
7054 /// fully general case.
7055 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7057 if (M >= (int)Mask.size())
7062 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7064 /// This helper function produces an 8-bit shuffle immediate corresponding to
7065 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7066 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7069 /// NB: We rely heavily on "undef" masks preserving the input lane.
7070 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7071 SelectionDAG &DAG) {
7072 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7073 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7074 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7075 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7076 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7079 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7080 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7081 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7082 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7083 return DAG.getConstant(Imm, MVT::i8);
7086 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7088 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7089 /// support for floating point shuffles but not integer shuffles. These
7090 /// instructions will incur a domain crossing penalty on some chips though so
7091 /// it is better to avoid lowering through this for integer vectors where
7093 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7094 const X86Subtarget *Subtarget,
7095 SelectionDAG &DAG) {
7097 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7098 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7099 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7100 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7101 ArrayRef<int> Mask = SVOp->getMask();
7102 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7104 if (isSingleInputShuffleMask(Mask)) {
7105 // Straight shuffle of a single input vector. Simulate this by using the
7106 // single input as both of the "inputs" to this instruction..
7107 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7108 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7109 DAG.getConstant(SHUFPDMask, MVT::i8));
7111 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7112 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7114 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7115 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7116 DAG.getConstant(SHUFPDMask, MVT::i8));
7119 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7121 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7122 /// the integer unit to minimize domain crossing penalties. However, for blends
7123 /// it falls back to the floating point shuffle operation with appropriate bit
7125 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7126 const X86Subtarget *Subtarget,
7127 SelectionDAG &DAG) {
7129 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7130 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7131 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7133 ArrayRef<int> Mask = SVOp->getMask();
7134 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7136 if (isSingleInputShuffleMask(Mask)) {
7137 // Straight shuffle of a single input vector. For everything from SSE2
7138 // onward this has a single fast instruction with no scary immediates.
7139 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7140 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7141 int WidenedMask[4] = {
7142 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7143 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7145 ISD::BITCAST, DL, MVT::v2i64,
7146 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7147 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7150 // We implement this with SHUFPD which is pretty lame because it will likely
7151 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7152 // However, all the alternatives are still more cycles and newer chips don't
7153 // have this problem. It would be really nice if x86 had better shuffles here.
7154 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7155 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7156 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7157 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7160 /// \brief Lower 4-lane 32-bit floating point shuffles.
7162 /// Uses instructions exclusively from the floating point unit to minimize
7163 /// domain crossing penalties, as these are sufficient to implement all v4f32
7165 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7166 const X86Subtarget *Subtarget,
7167 SelectionDAG &DAG) {
7169 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7170 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7171 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7172 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7173 ArrayRef<int> Mask = SVOp->getMask();
7174 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7176 SDValue LowV = V1, HighV = V2;
7177 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7180 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7182 if (NumV2Elements == 0)
7183 // Straight shuffle of a single input vector. We pass the input vector to
7184 // both operands to simulate this with a SHUFPS.
7185 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7186 getV4X86ShuffleImm8ForMask(Mask, DAG));
7188 if (NumV2Elements == 1) {
7190 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7192 // Compute the index adjacent to V2Index and in the same half by toggling
7194 int V2AdjIndex = V2Index ^ 1;
7196 if (Mask[V2AdjIndex] == -1) {
7197 // Handles all the cases where we have a single V2 element and an undef.
7198 // This will only ever happen in the high lanes because we commute the
7199 // vector otherwise.
7201 std::swap(LowV, HighV);
7202 NewMask[V2Index] -= 4;
7204 // Handle the case where the V2 element ends up adjacent to a V1 element.
7205 // To make this work, blend them together as the first step.
7206 int V1Index = V2AdjIndex;
7207 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7208 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7209 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7211 // Now proceed to reconstruct the final blend as we have the necessary
7212 // high or low half formed.
7219 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7220 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7222 } else if (NumV2Elements == 2) {
7223 if (Mask[0] < 4 && Mask[1] < 4) {
7224 // Handle the easy case where we have V1 in the low lanes and V2 in the
7225 // high lanes. We never see this reversed because we sort the shuffle.
7229 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7230 // trying to place elements directly, just blend them and set up the final
7231 // shuffle to place them.
7233 // The first two blend mask elements are for V1, the second two are for
7235 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7236 Mask[2] < 4 ? Mask[2] : Mask[3],
7237 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7238 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7239 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7240 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7242 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7245 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7246 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7247 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7248 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7251 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7252 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7255 /// \brief Lower 4-lane i32 vector shuffles.
7257 /// We try to handle these with integer-domain shuffles where we can, but for
7258 /// blends we use the floating point domain blend instructions.
7259 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7260 const X86Subtarget *Subtarget,
7261 SelectionDAG &DAG) {
7263 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7264 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7265 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7266 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7267 ArrayRef<int> Mask = SVOp->getMask();
7268 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7270 if (isSingleInputShuffleMask(Mask))
7271 // Straight shuffle of a single input vector. For everything from SSE2
7272 // onward this has a single fast instruction with no scary immediates.
7273 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7274 getV4X86ShuffleImm8ForMask(Mask, DAG));
7276 // We implement this with SHUFPS because it can blend from two vectors.
7277 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7278 // up the inputs, bypassing domain shift penalties that we would encur if we
7279 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7281 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7282 DAG.getVectorShuffle(
7284 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7285 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7288 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7289 /// shuffle lowering, and the most complex part.
7291 /// The lowering strategy is to try to form pairs of input lanes which are
7292 /// targeted at the same half of the final vector, and then use a dword shuffle
7293 /// to place them onto the right half, and finally unpack the paired lanes into
7294 /// their final position.
7296 /// The exact breakdown of how to form these dword pairs and align them on the
7297 /// correct sides is really tricky. See the comments within the function for
7298 /// more of the details.
7299 static SDValue lowerV8I16SingleInputVectorShuffle(
7300 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7301 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7302 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7303 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7304 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7306 SmallVector<int, 4> LoInputs;
7307 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7308 [](int M) { return M >= 0; });
7309 std::sort(LoInputs.begin(), LoInputs.end());
7310 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7311 SmallVector<int, 4> HiInputs;
7312 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7313 [](int M) { return M >= 0; });
7314 std::sort(HiInputs.begin(), HiInputs.end());
7315 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7317 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7318 int NumHToL = LoInputs.size() - NumLToL;
7320 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7321 int NumHToH = HiInputs.size() - NumLToH;
7322 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7323 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7324 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7325 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7327 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7328 // such inputs we can swap two of the dwords across the half mark and end up
7329 // with <=2 inputs to each half in each half. Once there, we can fall through
7330 // to the generic code below. For example:
7332 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7333 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7335 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7337 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7338 int ThreeInputHalfSum, int OneInputHalfOffset) {
7339 // Compute the index of dword with only one word among the three inputs in
7340 // a half by taking the sum of the half with three inputs and subtracting
7341 // the sum of the actual three inputs. The difference is the remaining
7343 int DWordA = (ThreeInputHalfSum -
7344 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7346 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7348 int PSHUFDMask[] = {0, 1, 2, 3};
7349 PSHUFDMask[DWordA] = DWordB;
7350 PSHUFDMask[DWordB] = DWordA;
7351 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7352 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7353 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7354 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7356 // Adjust the mask to match the new locations of A and B.
7358 if (M != -1 && M/2 == DWordA)
7359 M = 2 * DWordB + M % 2;
7360 else if (M != -1 && M/2 == DWordB)
7361 M = 2 * DWordA + M % 2;
7363 // Recurse back into this routine to re-compute state now that this isn't
7364 // a 3 and 1 problem.
7365 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7368 if (NumLToL == 3 && NumHToL == 1)
7369 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7370 else if (NumLToL == 1 && NumHToL == 3)
7371 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7372 else if (NumLToH == 1 && NumHToH == 3)
7373 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7374 else if (NumLToH == 3 && NumHToH == 1)
7375 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7377 // At this point there are at most two inputs to the low and high halves from
7378 // each half. That means the inputs can always be grouped into dwords and
7379 // those dwords can then be moved to the correct half with a dword shuffle.
7380 // We use at most one low and one high word shuffle to collect these paired
7381 // inputs into dwords, and finally a dword shuffle to place them.
7382 int PSHUFLMask[4] = {-1, -1, -1, -1};
7383 int PSHUFHMask[4] = {-1, -1, -1, -1};
7384 int PSHUFDMask[4] = {-1, -1, -1, -1};
7386 // First fix the masks for all the inputs that are staying in their
7387 // original halves. This will then dictate the targets of the cross-half
7389 auto fixInPlaceInputs = [&PSHUFDMask](
7390 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7391 MutableArrayRef<int> HalfMask, int HalfOffset) {
7392 if (InPlaceInputs.empty())
7394 if (InPlaceInputs.size() == 1) {
7395 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7396 InPlaceInputs[0] - HalfOffset;
7397 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7401 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7402 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7403 InPlaceInputs[0] - HalfOffset;
7404 // Put the second input next to the first so that they are packed into
7405 // a dword. We find the adjacent index by toggling the low bit.
7406 int AdjIndex = InPlaceInputs[0] ^ 1;
7407 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7408 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7409 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7411 if (!HToLInputs.empty())
7412 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7413 if (!LToHInputs.empty())
7414 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7416 // Now gather the cross-half inputs and place them into a free dword of
7417 // their target half.
7418 // FIXME: This operation could almost certainly be simplified dramatically to
7419 // look more like the 3-1 fixing operation.
7420 auto moveInputsToRightHalf = [&PSHUFDMask](
7421 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7422 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7423 int SourceOffset, int DestOffset) {
7424 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7425 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7427 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7429 int LowWord = Word & ~1;
7430 int HighWord = Word | 1;
7431 return isWordClobbered(SourceHalfMask, LowWord) ||
7432 isWordClobbered(SourceHalfMask, HighWord);
7435 if (IncomingInputs.empty())
7438 if (ExistingInputs.empty()) {
7439 // Map any dwords with inputs from them into the right half.
7440 for (int Input : IncomingInputs) {
7441 // If the source half mask maps over the inputs, turn those into
7442 // swaps and use the swapped lane.
7443 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7444 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7445 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7446 Input - SourceOffset;
7447 // We have to swap the uses in our half mask in one sweep.
7448 for (int &M : HalfMask)
7449 if (M == SourceHalfMask[Input - SourceOffset])
7451 else if (M == Input)
7452 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7454 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7455 Input - SourceOffset &&
7456 "Previous placement doesn't match!");
7458 // Note that this correctly re-maps both when we do a swap and when
7459 // we observe the other side of the swap above. We rely on that to
7460 // avoid swapping the members of the input list directly.
7461 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7464 // Map the input's dword into the correct half.
7465 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7466 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7468 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7470 "Previous placement doesn't match!");
7473 // And just directly shift any other-half mask elements to be same-half
7474 // as we will have mirrored the dword containing the element into the
7475 // same position within that half.
7476 for (int &M : HalfMask)
7477 if (M >= SourceOffset && M < SourceOffset + 4) {
7478 M = M - SourceOffset + DestOffset;
7479 assert(M >= 0 && "This should never wrap below zero!");
7484 // Ensure we have the input in a viable dword of its current half. This
7485 // is particularly tricky because the original position may be clobbered
7486 // by inputs being moved and *staying* in that half.
7487 if (IncomingInputs.size() == 1) {
7488 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7489 int InputFixed = std::find(std::begin(SourceHalfMask),
7490 std::end(SourceHalfMask), -1) -
7491 std::begin(SourceHalfMask) + SourceOffset;
7492 SourceHalfMask[InputFixed - SourceOffset] =
7493 IncomingInputs[0] - SourceOffset;
7494 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7496 IncomingInputs[0] = InputFixed;
7498 } else if (IncomingInputs.size() == 2) {
7499 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7500 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7501 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7502 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7503 "Not all dwords can be clobbered!");
7504 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7505 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7506 for (int &M : HalfMask)
7507 if (M == IncomingInputs[0])
7508 M = SourceDWordBase + SourceOffset;
7509 else if (M == IncomingInputs[1])
7510 M = SourceDWordBase + 1 + SourceOffset;
7511 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7512 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7515 llvm_unreachable("Unhandled input size!");
7518 // Now hoist the DWord down to the right half.
7519 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7520 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7521 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7522 for (int Input : IncomingInputs)
7523 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7524 FreeDWord * 2 + Input % 2);
7526 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7527 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7528 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7529 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7531 // Now enact all the shuffles we've computed to move the inputs into their
7533 if (!isNoopShuffleMask(PSHUFLMask))
7534 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7535 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7536 if (!isNoopShuffleMask(PSHUFHMask))
7537 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7538 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7539 if (!isNoopShuffleMask(PSHUFDMask))
7540 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7541 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7542 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7543 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7545 // At this point, each half should contain all its inputs, and we can then
7546 // just shuffle them into their final position.
7547 assert(std::count_if(LoMask.begin(), LoMask.end(),
7548 [](int M) { return M >= 4; }) == 0 &&
7549 "Failed to lift all the high half inputs to the low mask!");
7550 assert(std::count_if(HiMask.begin(), HiMask.end(),
7551 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7552 "Failed to lift all the low half inputs to the high mask!");
7554 // Do a half shuffle for the low mask.
7555 if (!isNoopShuffleMask(LoMask))
7556 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7557 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7559 // Do a half shuffle with the high mask after shifting its values down.
7560 for (int &M : HiMask)
7563 if (!isNoopShuffleMask(HiMask))
7564 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7565 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7570 /// \brief Detect whether the mask pattern should be lowered through
7573 /// This essentially tests whether viewing the mask as an interleaving of two
7574 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7575 /// lowering it through interleaving is a significantly better strategy.
7576 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7577 int NumEvenInputs[2] = {0, 0};
7578 int NumOddInputs[2] = {0, 0};
7579 int NumLoInputs[2] = {0, 0};
7580 int NumHiInputs[2] = {0, 0};
7581 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7585 int InputIdx = Mask[i] >= Size;
7588 ++NumLoInputs[InputIdx];
7590 ++NumHiInputs[InputIdx];
7593 ++NumEvenInputs[InputIdx];
7595 ++NumOddInputs[InputIdx];
7598 // The minimum number of cross-input results for both the interleaved and
7599 // split cases. If interleaving results in fewer cross-input results, return
7601 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7602 NumEvenInputs[0] + NumOddInputs[1]);
7603 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7604 NumLoInputs[0] + NumHiInputs[1]);
7605 return InterleavedCrosses < SplitCrosses;
7608 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7610 /// This strategy only works when the inputs from each vector fit into a single
7611 /// half of that vector, and generally there are not so many inputs as to leave
7612 /// the in-place shuffles required highly constrained (and thus expensive). It
7613 /// shifts all the inputs into a single side of both input vectors and then
7614 /// uses an unpack to interleave these inputs in a single vector. At that
7615 /// point, we will fall back on the generic single input shuffle lowering.
7616 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7618 MutableArrayRef<int> Mask,
7619 const X86Subtarget *Subtarget,
7620 SelectionDAG &DAG) {
7621 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7622 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7623 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7624 for (int i = 0; i < 8; ++i)
7625 if (Mask[i] >= 0 && Mask[i] < 4)
7626 LoV1Inputs.push_back(i);
7627 else if (Mask[i] >= 4 && Mask[i] < 8)
7628 HiV1Inputs.push_back(i);
7629 else if (Mask[i] >= 8 && Mask[i] < 12)
7630 LoV2Inputs.push_back(i);
7631 else if (Mask[i] >= 12)
7632 HiV2Inputs.push_back(i);
7634 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7635 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7638 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7639 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7640 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7642 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7643 HiV1Inputs.size() + HiV2Inputs.size();
7645 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7646 ArrayRef<int> HiInputs, bool MoveToLo,
7648 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7649 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7650 if (BadInputs.empty())
7653 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7654 int MoveOffset = MoveToLo ? 0 : 4;
7656 if (GoodInputs.empty()) {
7657 for (int BadInput : BadInputs) {
7658 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7659 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7662 if (GoodInputs.size() == 2) {
7663 // If the low inputs are spread across two dwords, pack them into
7665 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7666 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7667 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7668 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7670 // Otherwise pin the good inputs.
7671 for (int GoodInput : GoodInputs)
7672 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7675 if (BadInputs.size() == 2) {
7676 // If we have two bad inputs then there may be either one or two good
7677 // inputs fixed in place. Find a fixed input, and then find the *other*
7678 // two adjacent indices by using modular arithmetic.
7680 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7681 [](int M) { return M >= 0; }) -
7682 std::begin(MoveMask);
7684 (((GoodMaskIdx - MoveOffset) & ~1) + 2 % 4) + MoveOffset;
7685 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7686 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7687 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7688 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7689 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7690 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7692 assert(BadInputs.size() == 1 && "All sizes handled");
7693 int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7694 std::end(MoveMask), -1) -
7695 std::begin(MoveMask);
7696 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7697 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7701 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7704 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7706 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7709 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7710 // cross-half traffic in the final shuffle.
7712 // Munge the mask to be a single-input mask after the unpack merges the
7716 M = 2 * (M % 4) + (M / 8);
7718 return DAG.getVectorShuffle(
7719 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7720 DL, MVT::v8i16, V1, V2),
7721 DAG.getUNDEF(MVT::v8i16), Mask);
7724 /// \brief Generic lowering of 8-lane i16 shuffles.
7726 /// This handles both single-input shuffles and combined shuffle/blends with
7727 /// two inputs. The single input shuffles are immediately delegated to
7728 /// a dedicated lowering routine.
7730 /// The blends are lowered in one of three fundamental ways. If there are few
7731 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7732 /// of the input is significantly cheaper when lowered as an interleaving of
7733 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7734 /// halves of the inputs separately (making them have relatively few inputs)
7735 /// and then concatenate them.
7736 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7737 const X86Subtarget *Subtarget,
7738 SelectionDAG &DAG) {
7740 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7741 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7742 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7743 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7744 ArrayRef<int> OrigMask = SVOp->getMask();
7745 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7746 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7747 MutableArrayRef<int> Mask(MaskStorage);
7749 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7751 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7752 auto isV2 = [](int M) { return M >= 8; };
7754 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7755 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7757 if (NumV2Inputs == 0)
7758 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7760 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7761 "to be V1-input shuffles.");
7763 if (NumV1Inputs + NumV2Inputs <= 4)
7764 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7766 // Check whether an interleaving lowering is likely to be more efficient.
7767 // This isn't perfect but it is a strong heuristic that tends to work well on
7768 // the kinds of shuffles that show up in practice.
7770 // FIXME: Handle 1x, 2x, and 4x interleaving.
7771 if (shouldLowerAsInterleaving(Mask)) {
7772 // FIXME: Figure out whether we should pack these into the low or high
7775 int EMask[8], OMask[8];
7776 for (int i = 0; i < 4; ++i) {
7777 EMask[i] = Mask[2*i];
7778 OMask[i] = Mask[2*i + 1];
7783 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7784 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7786 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7789 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7790 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7792 for (int i = 0; i < 4; ++i) {
7793 LoBlendMask[i] = Mask[i];
7794 HiBlendMask[i] = Mask[i + 4];
7797 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7798 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7799 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7800 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7802 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7803 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7806 /// \brief Check whether a compaction lowering can be done by dropping even
7807 /// elements and compute how many times even elements must be dropped.
7809 /// This handles shuffles which take every Nth element where N is a power of
7810 /// two. Example shuffle masks:
7812 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
7813 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
7814 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
7815 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
7816 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
7817 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
7819 /// Any of these lanes can of course be undef.
7821 /// This routine only supports N <= 3.
7822 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
7825 /// \returns N above, or the number of times even elements must be dropped if
7826 /// there is such a number. Otherwise returns zero.
7827 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
7828 // Figure out whether we're looping over two inputs or just one.
7829 bool IsSingleInput = isSingleInputShuffleMask(Mask);
7831 // The modulus for the shuffle vector entries is based on whether this is
7832 // a single input or not.
7833 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
7834 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
7835 "We should only be called with masks with a power-of-2 size!");
7837 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
7839 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
7840 // and 2^3 simultaneously. This is because we may have ambiguity with
7841 // partially undef inputs.
7842 bool ViableForN[3] = {true, true, true};
7844 for (int i = 0, e = Mask.size(); i < e; ++i) {
7845 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
7850 bool IsAnyViable = false;
7851 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7852 if (ViableForN[j]) {
7855 // The shuffle mask must be equal to (i * 2^N) % M.
7856 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
7859 ViableForN[j] = false;
7861 // Early exit if we exhaust the possible powers of two.
7866 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7870 // Return 0 as there is no viable power of two.
7874 /// \brief Generic lowering of v16i8 shuffles.
7876 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7877 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7878 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7879 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7881 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7882 const X86Subtarget *Subtarget,
7883 SelectionDAG &DAG) {
7885 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7886 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7887 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7888 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7889 ArrayRef<int> OrigMask = SVOp->getMask();
7890 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7891 int MaskStorage[16] = {
7892 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7893 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7894 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7895 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7896 MutableArrayRef<int> Mask(MaskStorage);
7897 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7898 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7900 // For single-input shuffles, there are some nicer lowering tricks we can use.
7901 if (isSingleInputShuffleMask(Mask)) {
7902 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7903 // Notably, this handles splat and partial-splat shuffles more efficiently.
7904 // However, it only makes sense if the pre-duplication shuffle simplifies
7905 // things significantly. Currently, this means we need to be able to
7906 // express the pre-duplication shuffle as an i16 shuffle.
7908 // FIXME: We should check for other patterns which can be widened into an
7909 // i16 shuffle as well.
7910 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7911 for (int i = 0; i < 16; i += 2) {
7912 if (Mask[i] != Mask[i + 1])
7917 auto tryToWidenViaDuplication = [&]() -> SDValue {
7918 if (!canWidenViaDuplication(Mask))
7920 SmallVector<int, 4> LoInputs;
7921 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7922 [](int M) { return M >= 0 && M < 8; });
7923 std::sort(LoInputs.begin(), LoInputs.end());
7924 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7926 SmallVector<int, 4> HiInputs;
7927 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7928 [](int M) { return M >= 8; });
7929 std::sort(HiInputs.begin(), HiInputs.end());
7930 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7933 bool TargetLo = LoInputs.size() >= HiInputs.size();
7934 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7935 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7937 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7938 SmallDenseMap<int, int, 8> LaneMap;
7939 for (int I : InPlaceInputs) {
7940 PreDupI16Shuffle[I/2] = I/2;
7943 int j = TargetLo ? 0 : 4, je = j + 4;
7944 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7945 // Check if j is already a shuffle of this input. This happens when
7946 // there are two adjacent bytes after we move the low one.
7947 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7948 // If we haven't yet mapped the input, search for a slot into which
7950 while (j < je && PreDupI16Shuffle[j] != -1)
7954 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7957 // Map this input with the i16 shuffle.
7958 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7961 // Update the lane map based on the mapping we ended up with.
7962 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7965 ISD::BITCAST, DL, MVT::v16i8,
7966 DAG.getVectorShuffle(MVT::v8i16, DL,
7967 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7968 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7970 // Unpack the bytes to form the i16s that will be shuffled into place.
7971 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7972 MVT::v16i8, V1, V1);
7974 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7975 for (int i = 0; i < 16; i += 2) {
7977 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7978 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7981 ISD::BITCAST, DL, MVT::v16i8,
7982 DAG.getVectorShuffle(MVT::v8i16, DL,
7983 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7984 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7986 if (SDValue V = tryToWidenViaDuplication())
7990 // Check whether an interleaving lowering is likely to be more efficient.
7991 // This isn't perfect but it is a strong heuristic that tends to work well on
7992 // the kinds of shuffles that show up in practice.
7994 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7995 if (shouldLowerAsInterleaving(Mask)) {
7996 // FIXME: Figure out whether we should pack these into the low or high
7999 int EMask[16], OMask[16];
8000 for (int i = 0; i < 8; ++i) {
8001 EMask[i] = Mask[2*i];
8002 OMask[i] = Mask[2*i + 1];
8007 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8008 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8010 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8013 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8014 // with PSHUFB. It is important to do this before we attempt to generate any
8015 // blends but after all of the single-input lowerings. If the single input
8016 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8017 // want to preserve that and we can DAG combine any longer sequences into
8018 // a PSHUFB in the end. But once we start blending from multiple inputs,
8019 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8020 // and there are *very* few patterns that would actually be faster than the
8021 // PSHUFB approach because of its ability to zero lanes.
8023 // FIXME: The only exceptions to the above are blends which are exact
8024 // interleavings with direct instructions supporting them. We currently don't
8025 // handle those well here.
8026 if (Subtarget->hasSSSE3()) {
8029 for (int i = 0; i < 16; ++i)
8030 if (Mask[i] == -1) {
8031 V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8033 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8035 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8037 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8038 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8039 if (isSingleInputShuffleMask(Mask))
8040 return V1; // Single inputs are easy.
8042 // Otherwise, blend the two.
8043 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8044 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8045 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8048 // Check whether a compaction lowering can be done. This handles shuffles
8049 // which take every Nth element for some even N. See the helper function for
8052 // We special case these as they can be particularly efficiently handled with
8053 // the PACKUSB instruction on x86 and they show up in common patterns of
8054 // rearranging bytes to truncate wide elements.
8055 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8056 // NumEvenDrops is the power of two stride of the elements. Another way of
8057 // thinking about it is that we need to drop the even elements this many
8058 // times to get the original input.
8059 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8061 // First we need to zero all the dropped bytes.
8062 assert(NumEvenDrops <= 3 &&
8063 "No support for dropping even elements more than 3 times.");
8064 // We use the mask type to pick which bytes are preserved based on how many
8065 // elements are dropped.
8066 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8067 SDValue ByteClearMask =
8068 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8069 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8070 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8072 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8074 // Now pack things back together.
8075 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8076 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8077 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8078 for (int i = 1; i < NumEvenDrops; ++i) {
8079 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8080 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8086 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8087 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8088 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8089 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8091 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8092 MutableArrayRef<int> V1HalfBlendMask,
8093 MutableArrayRef<int> V2HalfBlendMask) {
8094 for (int i = 0; i < 8; ++i)
8095 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8096 V1HalfBlendMask[i] = HalfMask[i];
8098 } else if (HalfMask[i] >= 16) {
8099 V2HalfBlendMask[i] = HalfMask[i] - 16;
8100 HalfMask[i] = i + 8;
8103 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8104 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8106 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8108 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8109 MutableArrayRef<int> HiBlendMask) {
8111 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8112 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8114 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8115 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8116 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8117 [](int M) { return M >= 0 && M % 2 == 1; })) {
8118 // Use a mask to drop the high bytes.
8119 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8120 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8121 DAG.getConstant(0x00FF, MVT::v8i16));
8123 // This will be a single vector shuffle instead of a blend so nuke V2.
8124 V2 = DAG.getUNDEF(MVT::v8i16);
8126 // Squash the masks to point directly into V1.
8127 for (int &M : LoBlendMask)
8130 for (int &M : HiBlendMask)
8134 // Otherwise just unpack the low half of V into V1 and the high half into
8135 // V2 so that we can blend them as i16s.
8136 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8137 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8138 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8139 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8142 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8143 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8144 return std::make_pair(BlendedLo, BlendedHi);
8146 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8147 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8148 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8150 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8151 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8153 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8156 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8158 /// This routine breaks down the specific type of 128-bit shuffle and
8159 /// dispatches to the lowering routines accordingly.
8160 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8161 MVT VT, const X86Subtarget *Subtarget,
8162 SelectionDAG &DAG) {
8163 switch (VT.SimpleTy) {
8165 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8167 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8169 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8171 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8173 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8175 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8178 llvm_unreachable("Unimplemented!");
8182 /// \brief Tiny helper function to test whether adjacent masks are sequential.
8183 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
8184 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8185 if (Mask[i] + 1 != Mask[i+1])
8191 /// \brief Top-level lowering for x86 vector shuffles.
8193 /// This handles decomposition, canonicalization, and lowering of all x86
8194 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8195 /// above in helper routines. The canonicalization attempts to widen shuffles
8196 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8197 /// s.t. only one of the two inputs needs to be tested, etc.
8198 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8199 SelectionDAG &DAG) {
8200 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8201 ArrayRef<int> Mask = SVOp->getMask();
8202 SDValue V1 = Op.getOperand(0);
8203 SDValue V2 = Op.getOperand(1);
8204 MVT VT = Op.getSimpleValueType();
8205 int NumElements = VT.getVectorNumElements();
8208 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8210 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8211 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8212 if (V1IsUndef && V2IsUndef)
8213 return DAG.getUNDEF(VT);
8215 // When we create a shuffle node we put the UNDEF node to second operand,
8216 // but in some cases the first operand may be transformed to UNDEF.
8217 // In this case we should just commute the node.
8219 return DAG.getCommutedVectorShuffle(*SVOp);
8221 // Check for non-undef masks pointing at an undef vector and make the masks
8222 // undef as well. This makes it easier to match the shuffle based solely on
8226 if (M >= NumElements) {
8227 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8228 for (int &M : NewMask)
8229 if (M >= NumElements)
8231 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8234 // For integer vector shuffles, try to collapse them into a shuffle of fewer
8235 // lanes but wider integers. We cap this to not form integers larger than i64
8236 // but it might be interesting to form i128 integers to handle flipping the
8237 // low and high halves of AVX 256-bit vectors.
8238 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8239 areAdjacentMasksSequential(Mask)) {
8240 SmallVector<int, 8> NewMask;
8241 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8242 NewMask.push_back(Mask[i] / 2);
8244 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8245 VT.getVectorNumElements() / 2);
8246 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8247 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8248 return DAG.getNode(ISD::BITCAST, dl, VT,
8249 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8252 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8253 for (int M : SVOp->getMask())
8256 else if (M < NumElements)
8261 // Commute the shuffle as needed such that more elements come from V1 than
8262 // V2. This allows us to match the shuffle pattern strictly on how many
8263 // elements come from V1 without handling the symmetric cases.
8264 if (NumV2Elements > NumV1Elements)
8265 return DAG.getCommutedVectorShuffle(*SVOp);
8267 // When the number of V1 and V2 elements are the same, try to minimize the
8268 // number of uses of V2 in the low half of the vector.
8269 if (NumV1Elements == NumV2Elements) {
8270 int LowV1Elements = 0, LowV2Elements = 0;
8271 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8272 if (M >= NumElements)
8276 if (LowV2Elements > LowV1Elements)
8277 return DAG.getCommutedVectorShuffle(*SVOp);
8280 // For each vector width, delegate to a specialized lowering routine.
8281 if (VT.getSizeInBits() == 128)
8282 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8284 llvm_unreachable("Unimplemented!");
8288 //===----------------------------------------------------------------------===//
8289 // Legacy vector shuffle lowering
8291 // This code is the legacy code handling vector shuffles until the above
8292 // replaces its functionality and performance.
8293 //===----------------------------------------------------------------------===//
8295 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8296 bool hasInt256, unsigned *MaskOut = nullptr) {
8297 MVT EltVT = VT.getVectorElementType();
8299 // There is no blend with immediate in AVX-512.
8300 if (VT.is512BitVector())
8303 if (!hasSSE41 || EltVT == MVT::i8)
8305 if (!hasInt256 && VT == MVT::v16i16)
8308 unsigned MaskValue = 0;
8309 unsigned NumElems = VT.getVectorNumElements();
8310 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8311 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8312 unsigned NumElemsInLane = NumElems / NumLanes;
8314 // Blend for v16i16 should be symetric for the both lanes.
8315 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8317 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8318 int EltIdx = MaskVals[i];
8320 if ((EltIdx < 0 || EltIdx == (int)i) &&
8321 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8324 if (((unsigned)EltIdx == (i + NumElems)) &&
8325 (SndLaneEltIdx < 0 ||
8326 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8327 MaskValue |= (1 << i);
8333 *MaskOut = MaskValue;
8337 // Try to lower a shuffle node into a simple blend instruction.
8338 // This function assumes isBlendMask returns true for this
8339 // SuffleVectorSDNode
8340 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8342 const X86Subtarget *Subtarget,
8343 SelectionDAG &DAG) {
8344 MVT VT = SVOp->getSimpleValueType(0);
8345 MVT EltVT = VT.getVectorElementType();
8346 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8347 Subtarget->hasInt256() && "Trying to lower a "
8348 "VECTOR_SHUFFLE to a Blend but "
8349 "with the wrong mask"));
8350 SDValue V1 = SVOp->getOperand(0);
8351 SDValue V2 = SVOp->getOperand(1);
8353 unsigned NumElems = VT.getVectorNumElements();
8355 // Convert i32 vectors to floating point if it is not AVX2.
8356 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8358 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8359 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8361 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8362 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8365 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8366 DAG.getConstant(MaskValue, MVT::i32));
8367 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8370 /// In vector type \p VT, return true if the element at index \p InputIdx
8371 /// falls on a different 128-bit lane than \p OutputIdx.
8372 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8373 unsigned OutputIdx) {
8374 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8375 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8378 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8379 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8380 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8381 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8383 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8384 SelectionDAG &DAG) {
8385 MVT VT = V1.getSimpleValueType();
8386 assert(VT.is128BitVector() || VT.is256BitVector());
8388 MVT EltVT = VT.getVectorElementType();
8389 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8390 unsigned NumElts = VT.getVectorNumElements();
8392 SmallVector<SDValue, 32> PshufbMask;
8393 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8394 int InputIdx = MaskVals[OutputIdx];
8395 unsigned InputByteIdx;
8397 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8398 InputByteIdx = 0x80;
8400 // Cross lane is not allowed.
8401 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8403 InputByteIdx = InputIdx * EltSizeInBytes;
8404 // Index is an byte offset within the 128-bit lane.
8405 InputByteIdx &= 0xf;
8408 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8409 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8410 if (InputByteIdx != 0x80)
8415 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8417 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8418 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8419 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8422 // v8i16 shuffles - Prefer shuffles in the following order:
8423 // 1. [all] pshuflw, pshufhw, optional move
8424 // 2. [ssse3] 1 x pshufb
8425 // 3. [ssse3] 2 x pshufb + 1 x por
8426 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8428 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8429 SelectionDAG &DAG) {
8430 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8431 SDValue V1 = SVOp->getOperand(0);
8432 SDValue V2 = SVOp->getOperand(1);
8434 SmallVector<int, 8> MaskVals;
8436 // Determine if more than 1 of the words in each of the low and high quadwords
8437 // of the result come from the same quadword of one of the two inputs. Undef
8438 // mask values count as coming from any quadword, for better codegen.
8440 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8441 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8442 unsigned LoQuad[] = { 0, 0, 0, 0 };
8443 unsigned HiQuad[] = { 0, 0, 0, 0 };
8444 // Indices of quads used.
8445 std::bitset<4> InputQuads;
8446 for (unsigned i = 0; i < 8; ++i) {
8447 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8448 int EltIdx = SVOp->getMaskElt(i);
8449 MaskVals.push_back(EltIdx);
8458 InputQuads.set(EltIdx / 4);
8461 int BestLoQuad = -1;
8462 unsigned MaxQuad = 1;
8463 for (unsigned i = 0; i < 4; ++i) {
8464 if (LoQuad[i] > MaxQuad) {
8466 MaxQuad = LoQuad[i];
8470 int BestHiQuad = -1;
8472 for (unsigned i = 0; i < 4; ++i) {
8473 if (HiQuad[i] > MaxQuad) {
8475 MaxQuad = HiQuad[i];
8479 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8480 // of the two input vectors, shuffle them into one input vector so only a
8481 // single pshufb instruction is necessary. If there are more than 2 input
8482 // quads, disable the next transformation since it does not help SSSE3.
8483 bool V1Used = InputQuads[0] || InputQuads[1];
8484 bool V2Used = InputQuads[2] || InputQuads[3];
8485 if (Subtarget->hasSSSE3()) {
8486 if (InputQuads.count() == 2 && V1Used && V2Used) {
8487 BestLoQuad = InputQuads[0] ? 0 : 1;
8488 BestHiQuad = InputQuads[2] ? 2 : 3;
8490 if (InputQuads.count() > 2) {
8496 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8497 // the shuffle mask. If a quad is scored as -1, that means that it contains
8498 // words from all 4 input quadwords.
8500 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8502 BestLoQuad < 0 ? 0 : BestLoQuad,
8503 BestHiQuad < 0 ? 1 : BestHiQuad
8505 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8506 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8507 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8508 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8510 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8511 // source words for the shuffle, to aid later transformations.
8512 bool AllWordsInNewV = true;
8513 bool InOrder[2] = { true, true };
8514 for (unsigned i = 0; i != 8; ++i) {
8515 int idx = MaskVals[i];
8517 InOrder[i/4] = false;
8518 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8520 AllWordsInNewV = false;
8524 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8525 if (AllWordsInNewV) {
8526 for (int i = 0; i != 8; ++i) {
8527 int idx = MaskVals[i];
8530 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8531 if ((idx != i) && idx < 4)
8533 if ((idx != i) && idx > 3)
8542 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8543 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8544 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8545 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8546 unsigned TargetMask = 0;
8547 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8548 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8549 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8550 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8551 getShufflePSHUFLWImmediate(SVOp);
8552 V1 = NewV.getOperand(0);
8553 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8557 // Promote splats to a larger type which usually leads to more efficient code.
8558 // FIXME: Is this true if pshufb is available?
8559 if (SVOp->isSplat())
8560 return PromoteSplat(SVOp, DAG);
8562 // If we have SSSE3, and all words of the result are from 1 input vector,
8563 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8564 // is present, fall back to case 4.
8565 if (Subtarget->hasSSSE3()) {
8566 SmallVector<SDValue,16> pshufbMask;
8568 // If we have elements from both input vectors, set the high bit of the
8569 // shuffle mask element to zero out elements that come from V2 in the V1
8570 // mask, and elements that come from V1 in the V2 mask, so that the two
8571 // results can be OR'd together.
8572 bool TwoInputs = V1Used && V2Used;
8573 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8575 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8577 // Calculate the shuffle mask for the second input, shuffle it, and
8578 // OR it with the first shuffled input.
8579 CommuteVectorShuffleMask(MaskVals, 8);
8580 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8581 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8582 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8585 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8586 // and update MaskVals with new element order.
8587 std::bitset<8> InOrder;
8588 if (BestLoQuad >= 0) {
8589 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8590 for (int i = 0; i != 4; ++i) {
8591 int idx = MaskVals[i];
8594 } else if ((idx / 4) == BestLoQuad) {
8599 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8602 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8603 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8604 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8606 getShufflePSHUFLWImmediate(SVOp), DAG);
8610 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8611 // and update MaskVals with the new element order.
8612 if (BestHiQuad >= 0) {
8613 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8614 for (unsigned i = 4; i != 8; ++i) {
8615 int idx = MaskVals[i];
8618 } else if ((idx / 4) == BestHiQuad) {
8619 MaskV[i] = (idx & 3) + 4;
8623 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8626 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8627 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8628 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8630 getShufflePSHUFHWImmediate(SVOp), DAG);
8634 // In case BestHi & BestLo were both -1, which means each quadword has a word
8635 // from each of the four input quadwords, calculate the InOrder bitvector now
8636 // before falling through to the insert/extract cleanup.
8637 if (BestLoQuad == -1 && BestHiQuad == -1) {
8639 for (int i = 0; i != 8; ++i)
8640 if (MaskVals[i] < 0 || MaskVals[i] == i)
8644 // The other elements are put in the right place using pextrw and pinsrw.
8645 for (unsigned i = 0; i != 8; ++i) {
8648 int EltIdx = MaskVals[i];
8651 SDValue ExtOp = (EltIdx < 8) ?
8652 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8653 DAG.getIntPtrConstant(EltIdx)) :
8654 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8655 DAG.getIntPtrConstant(EltIdx - 8));
8656 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8657 DAG.getIntPtrConstant(i));
8662 /// \brief v16i16 shuffles
8664 /// FIXME: We only support generation of a single pshufb currently. We can
8665 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8666 /// well (e.g 2 x pshufb + 1 x por).
8668 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8669 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8670 SDValue V1 = SVOp->getOperand(0);
8671 SDValue V2 = SVOp->getOperand(1);
8674 if (V2.getOpcode() != ISD::UNDEF)
8677 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8678 return getPSHUFB(MaskVals, V1, dl, DAG);
8681 // v16i8 shuffles - Prefer shuffles in the following order:
8682 // 1. [ssse3] 1 x pshufb
8683 // 2. [ssse3] 2 x pshufb + 1 x por
8684 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8685 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8686 const X86Subtarget* Subtarget,
8687 SelectionDAG &DAG) {
8688 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8689 SDValue V1 = SVOp->getOperand(0);
8690 SDValue V2 = SVOp->getOperand(1);
8692 ArrayRef<int> MaskVals = SVOp->getMask();
8694 // Promote splats to a larger type which usually leads to more efficient code.
8695 // FIXME: Is this true if pshufb is available?
8696 if (SVOp->isSplat())
8697 return PromoteSplat(SVOp, DAG);
8699 // If we have SSSE3, case 1 is generated when all result bytes come from
8700 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8701 // present, fall back to case 3.
8703 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8704 if (Subtarget->hasSSSE3()) {
8705 SmallVector<SDValue,16> pshufbMask;
8707 // If all result elements are from one input vector, then only translate
8708 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8710 // Otherwise, we have elements from both input vectors, and must zero out
8711 // elements that come from V2 in the first mask, and V1 in the second mask
8712 // so that we can OR them together.
8713 for (unsigned i = 0; i != 16; ++i) {
8714 int EltIdx = MaskVals[i];
8715 if (EltIdx < 0 || EltIdx >= 16)
8717 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8719 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8720 DAG.getNode(ISD::BUILD_VECTOR, dl,
8721 MVT::v16i8, pshufbMask));
8723 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8724 // the 2nd operand if it's undefined or zero.
8725 if (V2.getOpcode() == ISD::UNDEF ||
8726 ISD::isBuildVectorAllZeros(V2.getNode()))
8729 // Calculate the shuffle mask for the second input, shuffle it, and
8730 // OR it with the first shuffled input.
8732 for (unsigned i = 0; i != 16; ++i) {
8733 int EltIdx = MaskVals[i];
8734 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8735 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8737 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8738 DAG.getNode(ISD::BUILD_VECTOR, dl,
8739 MVT::v16i8, pshufbMask));
8740 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8743 // No SSSE3 - Calculate in place words and then fix all out of place words
8744 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8745 // the 16 different words that comprise the two doublequadword input vectors.
8746 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8747 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8749 for (int i = 0; i != 8; ++i) {
8750 int Elt0 = MaskVals[i*2];
8751 int Elt1 = MaskVals[i*2+1];
8753 // This word of the result is all undef, skip it.
8754 if (Elt0 < 0 && Elt1 < 0)
8757 // This word of the result is already in the correct place, skip it.
8758 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8761 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8762 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8765 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8766 // using a single extract together, load it and store it.
8767 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8768 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8769 DAG.getIntPtrConstant(Elt1 / 2));
8770 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8771 DAG.getIntPtrConstant(i));
8775 // If Elt1 is defined, extract it from the appropriate source. If the
8776 // source byte is not also odd, shift the extracted word left 8 bits
8777 // otherwise clear the bottom 8 bits if we need to do an or.
8779 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8780 DAG.getIntPtrConstant(Elt1 / 2));
8781 if ((Elt1 & 1) == 0)
8782 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8784 TLI.getShiftAmountTy(InsElt.getValueType())));
8786 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8787 DAG.getConstant(0xFF00, MVT::i16));
8789 // If Elt0 is defined, extract it from the appropriate source. If the
8790 // source byte is not also even, shift the extracted word right 8 bits. If
8791 // Elt1 was also defined, OR the extracted values together before
8792 // inserting them in the result.
8794 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8795 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8796 if ((Elt0 & 1) != 0)
8797 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8799 TLI.getShiftAmountTy(InsElt0.getValueType())));
8801 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8802 DAG.getConstant(0x00FF, MVT::i16));
8803 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8806 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8807 DAG.getIntPtrConstant(i));
8809 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8812 // v32i8 shuffles - Translate to VPSHUFB if possible.
8814 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8815 const X86Subtarget *Subtarget,
8816 SelectionDAG &DAG) {
8817 MVT VT = SVOp->getSimpleValueType(0);
8818 SDValue V1 = SVOp->getOperand(0);
8819 SDValue V2 = SVOp->getOperand(1);
8821 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8823 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8824 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8825 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8827 // VPSHUFB may be generated if
8828 // (1) one of input vector is undefined or zeroinitializer.
8829 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8830 // And (2) the mask indexes don't cross the 128-bit lane.
8831 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8832 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8835 if (V1IsAllZero && !V2IsAllZero) {
8836 CommuteVectorShuffleMask(MaskVals, 32);
8839 return getPSHUFB(MaskVals, V1, dl, DAG);
8842 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8843 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8844 /// done when every pair / quad of shuffle mask elements point to elements in
8845 /// the right sequence. e.g.
8846 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8848 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8849 SelectionDAG &DAG) {
8850 MVT VT = SVOp->getSimpleValueType(0);
8852 unsigned NumElems = VT.getVectorNumElements();
8855 switch (VT.SimpleTy) {
8856 default: llvm_unreachable("Unexpected!");
8859 return SDValue(SVOp, 0);
8860 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8861 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8862 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8863 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8864 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8865 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8868 SmallVector<int, 8> MaskVec;
8869 for (unsigned i = 0; i != NumElems; i += Scale) {
8871 for (unsigned j = 0; j != Scale; ++j) {
8872 int EltIdx = SVOp->getMaskElt(i+j);
8876 StartIdx = (EltIdx / Scale);
8877 if (EltIdx != (int)(StartIdx*Scale + j))
8880 MaskVec.push_back(StartIdx);
8883 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8884 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8885 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8888 /// getVZextMovL - Return a zero-extending vector move low node.
8890 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8891 SDValue SrcOp, SelectionDAG &DAG,
8892 const X86Subtarget *Subtarget, SDLoc dl) {
8893 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8894 LoadSDNode *LD = nullptr;
8895 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8896 LD = dyn_cast<LoadSDNode>(SrcOp);
8898 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8900 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8901 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8902 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8903 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8904 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8906 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8907 return DAG.getNode(ISD::BITCAST, dl, VT,
8908 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8909 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8917 return DAG.getNode(ISD::BITCAST, dl, VT,
8918 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8919 DAG.getNode(ISD::BITCAST, dl,
8923 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8924 /// which could not be matched by any known target speficic shuffle
8926 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8928 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8929 if (NewOp.getNode())
8932 MVT VT = SVOp->getSimpleValueType(0);
8934 unsigned NumElems = VT.getVectorNumElements();
8935 unsigned NumLaneElems = NumElems / 2;
8938 MVT EltVT = VT.getVectorElementType();
8939 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8942 SmallVector<int, 16> Mask;
8943 for (unsigned l = 0; l < 2; ++l) {
8944 // Build a shuffle mask for the output, discovering on the fly which
8945 // input vectors to use as shuffle operands (recorded in InputUsed).
8946 // If building a suitable shuffle vector proves too hard, then bail
8947 // out with UseBuildVector set.
8948 bool UseBuildVector = false;
8949 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8950 unsigned LaneStart = l * NumLaneElems;
8951 for (unsigned i = 0; i != NumLaneElems; ++i) {
8952 // The mask element. This indexes into the input.
8953 int Idx = SVOp->getMaskElt(i+LaneStart);
8955 // the mask element does not index into any input vector.
8960 // The input vector this mask element indexes into.
8961 int Input = Idx / NumLaneElems;
8963 // Turn the index into an offset from the start of the input vector.
8964 Idx -= Input * NumLaneElems;
8966 // Find or create a shuffle vector operand to hold this input.
8968 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8969 if (InputUsed[OpNo] == Input)
8970 // This input vector is already an operand.
8972 if (InputUsed[OpNo] < 0) {
8973 // Create a new operand for this input vector.
8974 InputUsed[OpNo] = Input;
8979 if (OpNo >= array_lengthof(InputUsed)) {
8980 // More than two input vectors used! Give up on trying to create a
8981 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8982 UseBuildVector = true;
8986 // Add the mask index for the new shuffle vector.
8987 Mask.push_back(Idx + OpNo * NumLaneElems);
8990 if (UseBuildVector) {
8991 SmallVector<SDValue, 16> SVOps;
8992 for (unsigned i = 0; i != NumLaneElems; ++i) {
8993 // The mask element. This indexes into the input.
8994 int Idx = SVOp->getMaskElt(i+LaneStart);
8996 SVOps.push_back(DAG.getUNDEF(EltVT));
9000 // The input vector this mask element indexes into.
9001 int Input = Idx / NumElems;
9003 // Turn the index into an offset from the start of the input vector.
9004 Idx -= Input * NumElems;
9006 // Extract the vector element by hand.
9007 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9008 SVOp->getOperand(Input),
9009 DAG.getIntPtrConstant(Idx)));
9012 // Construct the output using a BUILD_VECTOR.
9013 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9014 } else if (InputUsed[0] < 0) {
9015 // No input vectors were used! The result is undefined.
9016 Output[l] = DAG.getUNDEF(NVT);
9018 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9019 (InputUsed[0] % 2) * NumLaneElems,
9021 // If only one input was used, use an undefined vector for the other.
9022 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9023 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9024 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9025 // At least one input vector was used. Create a new shuffle vector.
9026 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9032 // Concatenate the result back
9033 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9036 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9037 /// 4 elements, and match them with several different shuffle types.
9039 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9040 SDValue V1 = SVOp->getOperand(0);
9041 SDValue V2 = SVOp->getOperand(1);
9043 MVT VT = SVOp->getSimpleValueType(0);
9045 assert(VT.is128BitVector() && "Unsupported vector size");
9047 std::pair<int, int> Locs[4];
9048 int Mask1[] = { -1, -1, -1, -1 };
9049 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9053 for (unsigned i = 0; i != 4; ++i) {
9054 int Idx = PermMask[i];
9056 Locs[i] = std::make_pair(-1, -1);
9058 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9060 Locs[i] = std::make_pair(0, NumLo);
9064 Locs[i] = std::make_pair(1, NumHi);
9066 Mask1[2+NumHi] = Idx;
9072 if (NumLo <= 2 && NumHi <= 2) {
9073 // If no more than two elements come from either vector. This can be
9074 // implemented with two shuffles. First shuffle gather the elements.
9075 // The second shuffle, which takes the first shuffle as both of its
9076 // vector operands, put the elements into the right order.
9077 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9079 int Mask2[] = { -1, -1, -1, -1 };
9081 for (unsigned i = 0; i != 4; ++i)
9082 if (Locs[i].first != -1) {
9083 unsigned Idx = (i < 2) ? 0 : 4;
9084 Idx += Locs[i].first * 2 + Locs[i].second;
9088 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9091 if (NumLo == 3 || NumHi == 3) {
9092 // Otherwise, we must have three elements from one vector, call it X, and
9093 // one element from the other, call it Y. First, use a shufps to build an
9094 // intermediate vector with the one element from Y and the element from X
9095 // that will be in the same half in the final destination (the indexes don't
9096 // matter). Then, use a shufps to build the final vector, taking the half
9097 // containing the element from Y from the intermediate, and the other half
9100 // Normalize it so the 3 elements come from V1.
9101 CommuteVectorShuffleMask(PermMask, 4);
9105 // Find the element from V2.
9107 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9108 int Val = PermMask[HiIndex];
9115 Mask1[0] = PermMask[HiIndex];
9117 Mask1[2] = PermMask[HiIndex^1];
9119 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9122 Mask1[0] = PermMask[0];
9123 Mask1[1] = PermMask[1];
9124 Mask1[2] = HiIndex & 1 ? 6 : 4;
9125 Mask1[3] = HiIndex & 1 ? 4 : 6;
9126 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9129 Mask1[0] = HiIndex & 1 ? 2 : 0;
9130 Mask1[1] = HiIndex & 1 ? 0 : 2;
9131 Mask1[2] = PermMask[2];
9132 Mask1[3] = PermMask[3];
9137 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9140 // Break it into (shuffle shuffle_hi, shuffle_lo).
9141 int LoMask[] = { -1, -1, -1, -1 };
9142 int HiMask[] = { -1, -1, -1, -1 };
9144 int *MaskPtr = LoMask;
9145 unsigned MaskIdx = 0;
9148 for (unsigned i = 0; i != 4; ++i) {
9155 int Idx = PermMask[i];
9157 Locs[i] = std::make_pair(-1, -1);
9158 } else if (Idx < 4) {
9159 Locs[i] = std::make_pair(MaskIdx, LoIdx);
9160 MaskPtr[LoIdx] = Idx;
9163 Locs[i] = std::make_pair(MaskIdx, HiIdx);
9164 MaskPtr[HiIdx] = Idx;
9169 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9170 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9171 int MaskOps[] = { -1, -1, -1, -1 };
9172 for (unsigned i = 0; i != 4; ++i)
9173 if (Locs[i].first != -1)
9174 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9175 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9178 static bool MayFoldVectorLoad(SDValue V) {
9179 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9180 V = V.getOperand(0);
9182 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9183 V = V.getOperand(0);
9184 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9185 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9186 // BUILD_VECTOR (load), undef
9187 V = V.getOperand(0);
9189 return MayFoldLoad(V);
9193 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9194 MVT VT = Op.getSimpleValueType();
9196 // Canonizalize to v2f64.
9197 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9198 return DAG.getNode(ISD::BITCAST, dl, VT,
9199 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9204 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9206 SDValue V1 = Op.getOperand(0);
9207 SDValue V2 = Op.getOperand(1);
9208 MVT VT = Op.getSimpleValueType();
9210 assert(VT != MVT::v2i64 && "unsupported shuffle type");
9212 if (HasSSE2 && VT == MVT::v2f64)
9213 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9215 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9216 return DAG.getNode(ISD::BITCAST, dl, VT,
9217 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9218 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9219 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9223 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9224 SDValue V1 = Op.getOperand(0);
9225 SDValue V2 = Op.getOperand(1);
9226 MVT VT = Op.getSimpleValueType();
9228 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9229 "unsupported shuffle type");
9231 if (V2.getOpcode() == ISD::UNDEF)
9235 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9239 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9240 SDValue V1 = Op.getOperand(0);
9241 SDValue V2 = Op.getOperand(1);
9242 MVT VT = Op.getSimpleValueType();
9243 unsigned NumElems = VT.getVectorNumElements();
9245 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9246 // operand of these instructions is only memory, so check if there's a
9247 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9249 bool CanFoldLoad = false;
9251 // Trivial case, when V2 comes from a load.
9252 if (MayFoldVectorLoad(V2))
9255 // When V1 is a load, it can be folded later into a store in isel, example:
9256 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9258 // (MOVLPSmr addr:$src1, VR128:$src2)
9259 // So, recognize this potential and also use MOVLPS or MOVLPD
9260 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9263 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9265 if (HasSSE2 && NumElems == 2)
9266 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9269 // If we don't care about the second element, proceed to use movss.
9270 if (SVOp->getMaskElt(1) != -1)
9271 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9274 // movl and movlp will both match v2i64, but v2i64 is never matched by
9275 // movl earlier because we make it strict to avoid messing with the movlp load
9276 // folding logic (see the code above getMOVLP call). Match it here then,
9277 // this is horrible, but will stay like this until we move all shuffle
9278 // matching to x86 specific nodes. Note that for the 1st condition all
9279 // types are matched with movsd.
9281 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9282 // as to remove this logic from here, as much as possible
9283 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9284 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9285 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9288 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9290 // Invert the operand order and use SHUFPS to match it.
9291 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9292 getShuffleSHUFImmediate(SVOp), DAG);
9295 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9296 SelectionDAG &DAG) {
9298 MVT VT = Load->getSimpleValueType(0);
9299 MVT EVT = VT.getVectorElementType();
9300 SDValue Addr = Load->getOperand(1);
9301 SDValue NewAddr = DAG.getNode(
9302 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9303 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9306 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9307 DAG.getMachineFunction().getMachineMemOperand(
9308 Load->getMemOperand(), 0, EVT.getStoreSize()));
9312 // It is only safe to call this function if isINSERTPSMask is true for
9313 // this shufflevector mask.
9314 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9315 SelectionDAG &DAG) {
9316 // Generate an insertps instruction when inserting an f32 from memory onto a
9317 // v4f32 or when copying a member from one v4f32 to another.
9318 // We also use it for transferring i32 from one register to another,
9319 // since it simply copies the same bits.
9320 // If we're transferring an i32 from memory to a specific element in a
9321 // register, we output a generic DAG that will match the PINSRD
9323 MVT VT = SVOp->getSimpleValueType(0);
9324 MVT EVT = VT.getVectorElementType();
9325 SDValue V1 = SVOp->getOperand(0);
9326 SDValue V2 = SVOp->getOperand(1);
9327 auto Mask = SVOp->getMask();
9328 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9329 "unsupported vector type for insertps/pinsrd");
9331 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9332 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9333 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9341 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9344 // If we have 1 element from each vector, we have to check if we're
9345 // changing V1's element's place. If so, we're done. Otherwise, we
9346 // should assume we're changing V2's element's place and behave
9348 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9349 assert(DestIndex <= INT32_MAX && "truncated destination index");
9350 if (FromV1 == FromV2 &&
9351 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9355 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9358 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9359 "More than one element from V1 and from V2, or no elements from one "
9360 "of the vectors. This case should not have returned true from "
9365 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9368 // Get an index into the source vector in the range [0,4) (the mask is
9369 // in the range [0,8) because it can address V1 and V2)
9370 unsigned SrcIndex = Mask[DestIndex] % 4;
9371 if (MayFoldLoad(From)) {
9372 // Trivial case, when From comes from a load and is only used by the
9373 // shuffle. Make it use insertps from the vector that we need from that
9376 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9377 if (!NewLoad.getNode())
9380 if (EVT == MVT::f32) {
9381 // Create this as a scalar to vector to match the instruction pattern.
9382 SDValue LoadScalarToVector =
9383 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9384 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9385 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9387 } else { // EVT == MVT::i32
9388 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9389 // instruction, to match the PINSRD instruction, which loads an i32 to a
9390 // certain vector element.
9391 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9392 DAG.getConstant(DestIndex, MVT::i32));
9396 // Vector-element-to-vector
9397 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9398 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9401 // Reduce a vector shuffle to zext.
9402 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9403 SelectionDAG &DAG) {
9404 // PMOVZX is only available from SSE41.
9405 if (!Subtarget->hasSSE41())
9408 MVT VT = Op.getSimpleValueType();
9410 // Only AVX2 support 256-bit vector integer extending.
9411 if (!Subtarget->hasInt256() && VT.is256BitVector())
9414 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9416 SDValue V1 = Op.getOperand(0);
9417 SDValue V2 = Op.getOperand(1);
9418 unsigned NumElems = VT.getVectorNumElements();
9420 // Extending is an unary operation and the element type of the source vector
9421 // won't be equal to or larger than i64.
9422 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9423 VT.getVectorElementType() == MVT::i64)
9426 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9427 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9428 while ((1U << Shift) < NumElems) {
9429 if (SVOp->getMaskElt(1U << Shift) == 1)
9432 // The maximal ratio is 8, i.e. from i8 to i64.
9437 // Check the shuffle mask.
9438 unsigned Mask = (1U << Shift) - 1;
9439 for (unsigned i = 0; i != NumElems; ++i) {
9440 int EltIdx = SVOp->getMaskElt(i);
9441 if ((i & Mask) != 0 && EltIdx != -1)
9443 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9447 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9448 MVT NeVT = MVT::getIntegerVT(NBits);
9449 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9451 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9454 // Simplify the operand as it's prepared to be fed into shuffle.
9455 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9456 if (V1.getOpcode() == ISD::BITCAST &&
9457 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9458 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9459 V1.getOperand(0).getOperand(0)
9460 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9461 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9462 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9463 ConstantSDNode *CIdx =
9464 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9465 // If it's foldable, i.e. normal load with single use, we will let code
9466 // selection to fold it. Otherwise, we will short the conversion sequence.
9467 if (CIdx && CIdx->getZExtValue() == 0 &&
9468 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9469 MVT FullVT = V.getSimpleValueType();
9470 MVT V1VT = V1.getSimpleValueType();
9471 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9472 // The "ext_vec_elt" node is wider than the result node.
9473 // In this case we should extract subvector from V.
9474 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9475 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9476 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9477 FullVT.getVectorNumElements()/Ratio);
9478 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9479 DAG.getIntPtrConstant(0));
9481 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9485 return DAG.getNode(ISD::BITCAST, DL, VT,
9486 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9489 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9490 SelectionDAG &DAG) {
9491 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9492 MVT VT = Op.getSimpleValueType();
9494 SDValue V1 = Op.getOperand(0);
9495 SDValue V2 = Op.getOperand(1);
9497 if (isZeroShuffle(SVOp))
9498 return getZeroVector(VT, Subtarget, DAG, dl);
9500 // Handle splat operations
9501 if (SVOp->isSplat()) {
9502 // Use vbroadcast whenever the splat comes from a foldable load
9503 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9504 if (Broadcast.getNode())
9508 // Check integer expanding shuffles.
9509 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9510 if (NewOp.getNode())
9513 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9515 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9517 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9518 if (NewOp.getNode())
9519 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9520 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9521 // FIXME: Figure out a cleaner way to do this.
9522 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9523 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9524 if (NewOp.getNode()) {
9525 MVT NewVT = NewOp.getSimpleValueType();
9526 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9527 NewVT, true, false))
9528 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9531 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9532 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9533 if (NewOp.getNode()) {
9534 MVT NewVT = NewOp.getSimpleValueType();
9535 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9536 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9545 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9546 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9547 SDValue V1 = Op.getOperand(0);
9548 SDValue V2 = Op.getOperand(1);
9549 MVT VT = Op.getSimpleValueType();
9551 unsigned NumElems = VT.getVectorNumElements();
9552 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9553 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9554 bool V1IsSplat = false;
9555 bool V2IsSplat = false;
9556 bool HasSSE2 = Subtarget->hasSSE2();
9557 bool HasFp256 = Subtarget->hasFp256();
9558 bool HasInt256 = Subtarget->hasInt256();
9559 MachineFunction &MF = DAG.getMachineFunction();
9560 bool OptForSize = MF.getFunction()->getAttributes().
9561 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9563 // Check if we should use the experimental vector shuffle lowering. If so,
9564 // delegate completely to that code path.
9565 if (ExperimentalVectorShuffleLowering)
9566 return lowerVectorShuffle(Op, Subtarget, DAG);
9568 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9570 if (V1IsUndef && V2IsUndef)
9571 return DAG.getUNDEF(VT);
9573 // When we create a shuffle node we put the UNDEF node to second operand,
9574 // but in some cases the first operand may be transformed to UNDEF.
9575 // In this case we should just commute the node.
9577 return DAG.getCommutedVectorShuffle(*SVOp);
9579 // Vector shuffle lowering takes 3 steps:
9581 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9582 // narrowing and commutation of operands should be handled.
9583 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9585 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9586 // so the shuffle can be broken into other shuffles and the legalizer can
9587 // try the lowering again.
9589 // The general idea is that no vector_shuffle operation should be left to
9590 // be matched during isel, all of them must be converted to a target specific
9593 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9594 // narrowing and commutation of operands should be handled. The actual code
9595 // doesn't include all of those, work in progress...
9596 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9597 if (NewOp.getNode())
9600 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9602 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9603 // unpckh_undef). Only use pshufd if speed is more important than size.
9604 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9605 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9606 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9607 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9609 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9610 V2IsUndef && MayFoldVectorLoad(V1))
9611 return getMOVDDup(Op, dl, V1, DAG);
9613 if (isMOVHLPS_v_undef_Mask(M, VT))
9614 return getMOVHighToLow(Op, dl, DAG);
9616 // Use to match splats
9617 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9618 (VT == MVT::v2f64 || VT == MVT::v2i64))
9619 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9621 if (isPSHUFDMask(M, VT)) {
9622 // The actual implementation will match the mask in the if above and then
9623 // during isel it can match several different instructions, not only pshufd
9624 // as its name says, sad but true, emulate the behavior for now...
9625 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9626 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9628 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9630 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9631 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9633 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9634 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9637 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9641 if (isPALIGNRMask(M, VT, Subtarget))
9642 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9643 getShufflePALIGNRImmediate(SVOp),
9646 if (isVALIGNMask(M, VT, Subtarget))
9647 return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
9648 getShuffleVALIGNImmediate(SVOp),
9651 // Check if this can be converted into a logical shift.
9652 bool isLeft = false;
9655 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9656 if (isShift && ShVal.hasOneUse()) {
9657 // If the shifted value has multiple uses, it may be cheaper to use
9658 // v_set0 + movlhps or movhlps, etc.
9659 MVT EltVT = VT.getVectorElementType();
9660 ShAmt *= EltVT.getSizeInBits();
9661 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9664 if (isMOVLMask(M, VT)) {
9665 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9666 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9667 if (!isMOVLPMask(M, VT)) {
9668 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9669 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9671 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9672 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9676 // FIXME: fold these into legal mask.
9677 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9678 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9680 if (isMOVHLPSMask(M, VT))
9681 return getMOVHighToLow(Op, dl, DAG);
9683 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9684 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9686 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9687 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9689 if (isMOVLPMask(M, VT))
9690 return getMOVLP(Op, dl, DAG, HasSSE2);
9692 if (ShouldXformToMOVHLPS(M, VT) ||
9693 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9694 return DAG.getCommutedVectorShuffle(*SVOp);
9697 // No better options. Use a vshldq / vsrldq.
9698 MVT EltVT = VT.getVectorElementType();
9699 ShAmt *= EltVT.getSizeInBits();
9700 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9703 bool Commuted = false;
9704 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9705 // 1,1,1,1 -> v8i16 though.
9706 BitVector UndefElements;
9707 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9708 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9710 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9711 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9714 // Canonicalize the splat or undef, if present, to be on the RHS.
9715 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9716 CommuteVectorShuffleMask(M, NumElems);
9718 std::swap(V1IsSplat, V2IsSplat);
9722 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9723 // Shuffling low element of v1 into undef, just return v1.
9726 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9727 // the instruction selector will not match, so get a canonical MOVL with
9728 // swapped operands to undo the commute.
9729 return getMOVL(DAG, dl, VT, V2, V1);
9732 if (isUNPCKLMask(M, VT, HasInt256))
9733 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9735 if (isUNPCKHMask(M, VT, HasInt256))
9736 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9739 // Normalize mask so all entries that point to V2 points to its first
9740 // element then try to match unpck{h|l} again. If match, return a
9741 // new vector_shuffle with the corrected mask.p
9742 SmallVector<int, 8> NewMask(M.begin(), M.end());
9743 NormalizeMask(NewMask, NumElems);
9744 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9745 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9746 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9747 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9751 // Commute is back and try unpck* again.
9752 // FIXME: this seems wrong.
9753 CommuteVectorShuffleMask(M, NumElems);
9755 std::swap(V1IsSplat, V2IsSplat);
9757 if (isUNPCKLMask(M, VT, HasInt256))
9758 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9760 if (isUNPCKHMask(M, VT, HasInt256))
9761 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9764 // Normalize the node to match x86 shuffle ops if needed
9765 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9766 return DAG.getCommutedVectorShuffle(*SVOp);
9768 // The checks below are all present in isShuffleMaskLegal, but they are
9769 // inlined here right now to enable us to directly emit target specific
9770 // nodes, and remove one by one until they don't return Op anymore.
9772 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9773 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9774 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9775 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9778 if (isPSHUFHWMask(M, VT, HasInt256))
9779 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9780 getShufflePSHUFHWImmediate(SVOp),
9783 if (isPSHUFLWMask(M, VT, HasInt256))
9784 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9785 getShufflePSHUFLWImmediate(SVOp),
9789 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9791 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9793 if (isSHUFPMask(M, VT))
9794 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9795 getShuffleSHUFImmediate(SVOp), DAG);
9797 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9798 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9799 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9800 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9802 //===--------------------------------------------------------------------===//
9803 // Generate target specific nodes for 128 or 256-bit shuffles only
9804 // supported in the AVX instruction set.
9807 // Handle VMOVDDUPY permutations
9808 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9809 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9811 // Handle VPERMILPS/D* permutations
9812 if (isVPERMILPMask(M, VT)) {
9813 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9814 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9815 getShuffleSHUFImmediate(SVOp), DAG);
9816 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9817 getShuffleSHUFImmediate(SVOp), DAG);
9821 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9822 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9823 Idx*(NumElems/2), DAG, dl);
9825 // Handle VPERM2F128/VPERM2I128 permutations
9826 if (isVPERM2X128Mask(M, VT, HasFp256))
9827 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9828 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9830 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9831 return getINSERTPS(SVOp, dl, DAG);
9834 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9835 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9837 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9838 VT.is512BitVector()) {
9839 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9840 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9841 SmallVector<SDValue, 16> permclMask;
9842 for (unsigned i = 0; i != NumElems; ++i) {
9843 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9846 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9848 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9849 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9850 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9851 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9852 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9855 //===--------------------------------------------------------------------===//
9856 // Since no target specific shuffle was selected for this generic one,
9857 // lower it into other known shuffles. FIXME: this isn't true yet, but
9858 // this is the plan.
9861 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9862 if (VT == MVT::v8i16) {
9863 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9864 if (NewOp.getNode())
9868 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9869 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9870 if (NewOp.getNode())
9874 if (VT == MVT::v16i8) {
9875 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9876 if (NewOp.getNode())
9880 if (VT == MVT::v32i8) {
9881 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9882 if (NewOp.getNode())
9886 // Handle all 128-bit wide vectors with 4 elements, and match them with
9887 // several different shuffle types.
9888 if (NumElems == 4 && VT.is128BitVector())
9889 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9891 // Handle general 256-bit shuffles
9892 if (VT.is256BitVector())
9893 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9898 // This function assumes its argument is a BUILD_VECTOR of constants or
9899 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9901 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9902 unsigned &MaskValue) {
9904 unsigned NumElems = BuildVector->getNumOperands();
9905 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9906 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9907 unsigned NumElemsInLane = NumElems / NumLanes;
9909 // Blend for v16i16 should be symetric for the both lanes.
9910 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9911 SDValue EltCond = BuildVector->getOperand(i);
9912 SDValue SndLaneEltCond =
9913 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9915 int Lane1Cond = -1, Lane2Cond = -1;
9916 if (isa<ConstantSDNode>(EltCond))
9917 Lane1Cond = !isZero(EltCond);
9918 if (isa<ConstantSDNode>(SndLaneEltCond))
9919 Lane2Cond = !isZero(SndLaneEltCond);
9921 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9922 // Lane1Cond != 0, means we want the first argument.
9923 // Lane1Cond == 0, means we want the second argument.
9924 // The encoding of this argument is 0 for the first argument, 1
9925 // for the second. Therefore, invert the condition.
9926 MaskValue |= !Lane1Cond << i;
9927 else if (Lane1Cond < 0)
9928 MaskValue |= !Lane2Cond << i;
9935 // Try to lower a vselect node into a simple blend instruction.
9936 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9937 SelectionDAG &DAG) {
9938 SDValue Cond = Op.getOperand(0);
9939 SDValue LHS = Op.getOperand(1);
9940 SDValue RHS = Op.getOperand(2);
9942 MVT VT = Op.getSimpleValueType();
9943 MVT EltVT = VT.getVectorElementType();
9944 unsigned NumElems = VT.getVectorNumElements();
9946 // There is no blend with immediate in AVX-512.
9947 if (VT.is512BitVector())
9950 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9952 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9955 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9958 // Check the mask for BLEND and build the value.
9959 unsigned MaskValue = 0;
9960 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9963 // Convert i32 vectors to floating point if it is not AVX2.
9964 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9966 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9967 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9969 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9970 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9973 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9974 DAG.getConstant(MaskValue, MVT::i32));
9975 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9978 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9979 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9980 if (BlendOp.getNode())
9983 // Some types for vselect were previously set to Expand, not Legal or
9984 // Custom. Return an empty SDValue so we fall-through to Expand, after
9985 // the Custom lowering phase.
9986 MVT VT = Op.getSimpleValueType();
9987 switch (VT.SimpleTy) {
9995 // We couldn't create a "Blend with immediate" node.
9996 // This node should still be legal, but we'll have to emit a blendv*
10001 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10002 MVT VT = Op.getSimpleValueType();
10005 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10008 if (VT.getSizeInBits() == 8) {
10009 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10010 Op.getOperand(0), Op.getOperand(1));
10011 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10012 DAG.getValueType(VT));
10013 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10016 if (VT.getSizeInBits() == 16) {
10017 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10018 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10020 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10021 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10022 DAG.getNode(ISD::BITCAST, dl,
10025 Op.getOperand(1)));
10026 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10027 Op.getOperand(0), Op.getOperand(1));
10028 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10029 DAG.getValueType(VT));
10030 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10033 if (VT == MVT::f32) {
10034 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10035 // the result back to FR32 register. It's only worth matching if the
10036 // result has a single use which is a store or a bitcast to i32. And in
10037 // the case of a store, it's not worth it if the index is a constant 0,
10038 // because a MOVSSmr can be used instead, which is smaller and faster.
10039 if (!Op.hasOneUse())
10041 SDNode *User = *Op.getNode()->use_begin();
10042 if ((User->getOpcode() != ISD::STORE ||
10043 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10044 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10045 (User->getOpcode() != ISD::BITCAST ||
10046 User->getValueType(0) != MVT::i32))
10048 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10049 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10052 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10055 if (VT == MVT::i32 || VT == MVT::i64) {
10056 // ExtractPS/pextrq works with constant index.
10057 if (isa<ConstantSDNode>(Op.getOperand(1)))
10063 /// Extract one bit from mask vector, like v16i1 or v8i1.
10064 /// AVX-512 feature.
10066 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10067 SDValue Vec = Op.getOperand(0);
10069 MVT VecVT = Vec.getSimpleValueType();
10070 SDValue Idx = Op.getOperand(1);
10071 MVT EltVT = Op.getSimpleValueType();
10073 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10075 // variable index can't be handled in mask registers,
10076 // extend vector to VR512
10077 if (!isa<ConstantSDNode>(Idx)) {
10078 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10079 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10080 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10081 ExtVT.getVectorElementType(), Ext, Idx);
10082 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10085 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10086 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10087 unsigned MaxSift = rc->getSize()*8 - 1;
10088 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10089 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10090 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10091 DAG.getConstant(MaxSift, MVT::i8));
10092 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10093 DAG.getIntPtrConstant(0));
10097 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10098 SelectionDAG &DAG) const {
10100 SDValue Vec = Op.getOperand(0);
10101 MVT VecVT = Vec.getSimpleValueType();
10102 SDValue Idx = Op.getOperand(1);
10104 if (Op.getSimpleValueType() == MVT::i1)
10105 return ExtractBitFromMaskVector(Op, DAG);
10107 if (!isa<ConstantSDNode>(Idx)) {
10108 if (VecVT.is512BitVector() ||
10109 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10110 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10113 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10114 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10115 MaskEltVT.getSizeInBits());
10117 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10118 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10119 getZeroVector(MaskVT, Subtarget, DAG, dl),
10120 Idx, DAG.getConstant(0, getPointerTy()));
10121 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10122 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10123 Perm, DAG.getConstant(0, getPointerTy()));
10128 // If this is a 256-bit vector result, first extract the 128-bit vector and
10129 // then extract the element from the 128-bit vector.
10130 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10132 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10133 // Get the 128-bit vector.
10134 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10135 MVT EltVT = VecVT.getVectorElementType();
10137 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10139 //if (IdxVal >= NumElems/2)
10140 // IdxVal -= NumElems/2;
10141 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10142 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10143 DAG.getConstant(IdxVal, MVT::i32));
10146 assert(VecVT.is128BitVector() && "Unexpected vector length");
10148 if (Subtarget->hasSSE41()) {
10149 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10154 MVT VT = Op.getSimpleValueType();
10155 // TODO: handle v16i8.
10156 if (VT.getSizeInBits() == 16) {
10157 SDValue Vec = Op.getOperand(0);
10158 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10160 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10161 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10162 DAG.getNode(ISD::BITCAST, dl,
10164 Op.getOperand(1)));
10165 // Transform it so it match pextrw which produces a 32-bit result.
10166 MVT EltVT = MVT::i32;
10167 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10168 Op.getOperand(0), Op.getOperand(1));
10169 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10170 DAG.getValueType(VT));
10171 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10174 if (VT.getSizeInBits() == 32) {
10175 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10179 // SHUFPS the element to the lowest double word, then movss.
10180 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10181 MVT VVT = Op.getOperand(0).getSimpleValueType();
10182 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10183 DAG.getUNDEF(VVT), Mask);
10184 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10185 DAG.getIntPtrConstant(0));
10188 if (VT.getSizeInBits() == 64) {
10189 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10190 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10191 // to match extract_elt for f64.
10192 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10196 // UNPCKHPD the element to the lowest double word, then movsd.
10197 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10198 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10199 int Mask[2] = { 1, -1 };
10200 MVT VVT = Op.getOperand(0).getSimpleValueType();
10201 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10202 DAG.getUNDEF(VVT), Mask);
10203 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10204 DAG.getIntPtrConstant(0));
10210 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10211 MVT VT = Op.getSimpleValueType();
10212 MVT EltVT = VT.getVectorElementType();
10215 SDValue N0 = Op.getOperand(0);
10216 SDValue N1 = Op.getOperand(1);
10217 SDValue N2 = Op.getOperand(2);
10219 if (!VT.is128BitVector())
10222 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10223 isa<ConstantSDNode>(N2)) {
10225 if (VT == MVT::v8i16)
10226 Opc = X86ISD::PINSRW;
10227 else if (VT == MVT::v16i8)
10228 Opc = X86ISD::PINSRB;
10230 Opc = X86ISD::PINSRB;
10232 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10234 if (N1.getValueType() != MVT::i32)
10235 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10236 if (N2.getValueType() != MVT::i32)
10237 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10238 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10241 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10242 // Bits [7:6] of the constant are the source select. This will always be
10243 // zero here. The DAG Combiner may combine an extract_elt index into these
10244 // bits. For example (insert (extract, 3), 2) could be matched by putting
10245 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10246 // Bits [5:4] of the constant are the destination select. This is the
10247 // value of the incoming immediate.
10248 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10249 // combine either bitwise AND or insert of float 0.0 to set these bits.
10250 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10251 // Create this as a scalar to vector..
10252 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10253 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10256 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10257 // PINSR* works with constant index.
10263 /// Insert one bit to mask vector, like v16i1 or v8i1.
10264 /// AVX-512 feature.
10266 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10268 SDValue Vec = Op.getOperand(0);
10269 SDValue Elt = Op.getOperand(1);
10270 SDValue Idx = Op.getOperand(2);
10271 MVT VecVT = Vec.getSimpleValueType();
10273 if (!isa<ConstantSDNode>(Idx)) {
10274 // Non constant index. Extend source and destination,
10275 // insert element and then truncate the result.
10276 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10277 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10278 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10279 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10280 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10281 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10284 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10285 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10286 if (Vec.getOpcode() == ISD::UNDEF)
10287 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10288 DAG.getConstant(IdxVal, MVT::i8));
10289 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10290 unsigned MaxSift = rc->getSize()*8 - 1;
10291 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10292 DAG.getConstant(MaxSift, MVT::i8));
10293 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10294 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10295 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10298 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10299 MVT VT = Op.getSimpleValueType();
10300 MVT EltVT = VT.getVectorElementType();
10302 if (EltVT == MVT::i1)
10303 return InsertBitToMaskVector(Op, DAG);
10306 SDValue N0 = Op.getOperand(0);
10307 SDValue N1 = Op.getOperand(1);
10308 SDValue N2 = Op.getOperand(2);
10310 // If this is a 256-bit vector result, first extract the 128-bit vector,
10311 // insert the element into the extracted half and then place it back.
10312 if (VT.is256BitVector() || VT.is512BitVector()) {
10313 if (!isa<ConstantSDNode>(N2))
10316 // Get the desired 128-bit vector half.
10317 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10318 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10320 // Insert the element into the desired half.
10321 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10322 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10324 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10325 DAG.getConstant(IdxIn128, MVT::i32));
10327 // Insert the changed part back to the 256-bit vector
10328 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10331 if (Subtarget->hasSSE41())
10332 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10334 if (EltVT == MVT::i8)
10337 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10338 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10339 // as its second argument.
10340 if (N1.getValueType() != MVT::i32)
10341 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10342 if (N2.getValueType() != MVT::i32)
10343 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10344 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10349 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10351 MVT OpVT = Op.getSimpleValueType();
10353 // If this is a 256-bit vector result, first insert into a 128-bit
10354 // vector and then insert into the 256-bit vector.
10355 if (!OpVT.is128BitVector()) {
10356 // Insert into a 128-bit vector.
10357 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10358 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10359 OpVT.getVectorNumElements() / SizeFactor);
10361 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10363 // Insert the 128-bit vector.
10364 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10367 if (OpVT == MVT::v1i64 &&
10368 Op.getOperand(0).getValueType() == MVT::i64)
10369 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10371 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10372 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10373 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10374 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10377 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10378 // a simple subregister reference or explicit instructions to grab
10379 // upper bits of a vector.
10380 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10381 SelectionDAG &DAG) {
10383 SDValue In = Op.getOperand(0);
10384 SDValue Idx = Op.getOperand(1);
10385 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10386 MVT ResVT = Op.getSimpleValueType();
10387 MVT InVT = In.getSimpleValueType();
10389 if (Subtarget->hasFp256()) {
10390 if (ResVT.is128BitVector() &&
10391 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10392 isa<ConstantSDNode>(Idx)) {
10393 return Extract128BitVector(In, IdxVal, DAG, dl);
10395 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10396 isa<ConstantSDNode>(Idx)) {
10397 return Extract256BitVector(In, IdxVal, DAG, dl);
10403 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10404 // simple superregister reference or explicit instructions to insert
10405 // the upper bits of a vector.
10406 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10407 SelectionDAG &DAG) {
10408 if (Subtarget->hasFp256()) {
10409 SDLoc dl(Op.getNode());
10410 SDValue Vec = Op.getNode()->getOperand(0);
10411 SDValue SubVec = Op.getNode()->getOperand(1);
10412 SDValue Idx = Op.getNode()->getOperand(2);
10414 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10415 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10416 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10417 isa<ConstantSDNode>(Idx)) {
10418 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10419 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10422 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10423 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10424 isa<ConstantSDNode>(Idx)) {
10425 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10426 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10432 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10433 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10434 // one of the above mentioned nodes. It has to be wrapped because otherwise
10435 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10436 // be used to form addressing mode. These wrapped nodes will be selected
10439 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10440 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10442 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10443 // global base reg.
10444 unsigned char OpFlag = 0;
10445 unsigned WrapperKind = X86ISD::Wrapper;
10446 CodeModel::Model M = DAG.getTarget().getCodeModel();
10448 if (Subtarget->isPICStyleRIPRel() &&
10449 (M == CodeModel::Small || M == CodeModel::Kernel))
10450 WrapperKind = X86ISD::WrapperRIP;
10451 else if (Subtarget->isPICStyleGOT())
10452 OpFlag = X86II::MO_GOTOFF;
10453 else if (Subtarget->isPICStyleStubPIC())
10454 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10456 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10457 CP->getAlignment(),
10458 CP->getOffset(), OpFlag);
10460 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10461 // With PIC, the address is actually $g + Offset.
10463 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10464 DAG.getNode(X86ISD::GlobalBaseReg,
10465 SDLoc(), getPointerTy()),
10472 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10473 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10475 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10476 // global base reg.
10477 unsigned char OpFlag = 0;
10478 unsigned WrapperKind = X86ISD::Wrapper;
10479 CodeModel::Model M = DAG.getTarget().getCodeModel();
10481 if (Subtarget->isPICStyleRIPRel() &&
10482 (M == CodeModel::Small || M == CodeModel::Kernel))
10483 WrapperKind = X86ISD::WrapperRIP;
10484 else if (Subtarget->isPICStyleGOT())
10485 OpFlag = X86II::MO_GOTOFF;
10486 else if (Subtarget->isPICStyleStubPIC())
10487 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10489 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10492 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10494 // With PIC, the address is actually $g + Offset.
10496 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10497 DAG.getNode(X86ISD::GlobalBaseReg,
10498 SDLoc(), getPointerTy()),
10505 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10506 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10508 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10509 // global base reg.
10510 unsigned char OpFlag = 0;
10511 unsigned WrapperKind = X86ISD::Wrapper;
10512 CodeModel::Model M = DAG.getTarget().getCodeModel();
10514 if (Subtarget->isPICStyleRIPRel() &&
10515 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10516 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10517 OpFlag = X86II::MO_GOTPCREL;
10518 WrapperKind = X86ISD::WrapperRIP;
10519 } else if (Subtarget->isPICStyleGOT()) {
10520 OpFlag = X86II::MO_GOT;
10521 } else if (Subtarget->isPICStyleStubPIC()) {
10522 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10523 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10524 OpFlag = X86II::MO_DARWIN_NONLAZY;
10527 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10530 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10532 // With PIC, the address is actually $g + Offset.
10533 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10534 !Subtarget->is64Bit()) {
10535 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10536 DAG.getNode(X86ISD::GlobalBaseReg,
10537 SDLoc(), getPointerTy()),
10541 // For symbols that require a load from a stub to get the address, emit the
10543 if (isGlobalStubReference(OpFlag))
10544 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10545 MachinePointerInfo::getGOT(), false, false, false, 0);
10551 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10552 // Create the TargetBlockAddressAddress node.
10553 unsigned char OpFlags =
10554 Subtarget->ClassifyBlockAddressReference();
10555 CodeModel::Model M = DAG.getTarget().getCodeModel();
10556 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10557 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10559 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10562 if (Subtarget->isPICStyleRIPRel() &&
10563 (M == CodeModel::Small || M == CodeModel::Kernel))
10564 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10566 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10568 // With PIC, the address is actually $g + Offset.
10569 if (isGlobalRelativeToPICBase(OpFlags)) {
10570 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10571 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10579 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10580 int64_t Offset, SelectionDAG &DAG) const {
10581 // Create the TargetGlobalAddress node, folding in the constant
10582 // offset if it is legal.
10583 unsigned char OpFlags =
10584 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10585 CodeModel::Model M = DAG.getTarget().getCodeModel();
10587 if (OpFlags == X86II::MO_NO_FLAG &&
10588 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10589 // A direct static reference to a global.
10590 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10593 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10596 if (Subtarget->isPICStyleRIPRel() &&
10597 (M == CodeModel::Small || M == CodeModel::Kernel))
10598 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10600 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10602 // With PIC, the address is actually $g + Offset.
10603 if (isGlobalRelativeToPICBase(OpFlags)) {
10604 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10605 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10609 // For globals that require a load from a stub to get the address, emit the
10611 if (isGlobalStubReference(OpFlags))
10612 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10613 MachinePointerInfo::getGOT(), false, false, false, 0);
10615 // If there was a non-zero offset that we didn't fold, create an explicit
10616 // addition for it.
10618 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10619 DAG.getConstant(Offset, getPointerTy()));
10625 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10626 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10627 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10628 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10632 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10633 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10634 unsigned char OperandFlags, bool LocalDynamic = false) {
10635 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10636 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10638 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10639 GA->getValueType(0),
10643 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10647 SDValue Ops[] = { Chain, TGA, *InFlag };
10648 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10650 SDValue Ops[] = { Chain, TGA };
10651 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10654 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10655 MFI->setAdjustsStack(true);
10657 SDValue Flag = Chain.getValue(1);
10658 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10661 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10663 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10666 SDLoc dl(GA); // ? function entry point might be better
10667 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10668 DAG.getNode(X86ISD::GlobalBaseReg,
10669 SDLoc(), PtrVT), InFlag);
10670 InFlag = Chain.getValue(1);
10672 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10675 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10677 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10679 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10680 X86::RAX, X86II::MO_TLSGD);
10683 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10689 // Get the start address of the TLS block for this module.
10690 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10691 .getInfo<X86MachineFunctionInfo>();
10692 MFI->incNumLocalDynamicTLSAccesses();
10696 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10697 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10700 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10701 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10702 InFlag = Chain.getValue(1);
10703 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10704 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10707 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10711 unsigned char OperandFlags = X86II::MO_DTPOFF;
10712 unsigned WrapperKind = X86ISD::Wrapper;
10713 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10714 GA->getValueType(0),
10715 GA->getOffset(), OperandFlags);
10716 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10718 // Add x@dtpoff with the base.
10719 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10722 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10723 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10724 const EVT PtrVT, TLSModel::Model model,
10725 bool is64Bit, bool isPIC) {
10728 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10729 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10730 is64Bit ? 257 : 256));
10732 SDValue ThreadPointer =
10733 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10734 MachinePointerInfo(Ptr), false, false, false, 0);
10736 unsigned char OperandFlags = 0;
10737 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10739 unsigned WrapperKind = X86ISD::Wrapper;
10740 if (model == TLSModel::LocalExec) {
10741 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10742 } else if (model == TLSModel::InitialExec) {
10744 OperandFlags = X86II::MO_GOTTPOFF;
10745 WrapperKind = X86ISD::WrapperRIP;
10747 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10750 llvm_unreachable("Unexpected model");
10753 // emit "addl x@ntpoff,%eax" (local exec)
10754 // or "addl x@indntpoff,%eax" (initial exec)
10755 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10757 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10758 GA->getOffset(), OperandFlags);
10759 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10761 if (model == TLSModel::InitialExec) {
10762 if (isPIC && !is64Bit) {
10763 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10764 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10768 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10769 MachinePointerInfo::getGOT(), false, false, false, 0);
10772 // The address of the thread local variable is the add of the thread
10773 // pointer with the offset of the variable.
10774 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10778 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10780 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10781 const GlobalValue *GV = GA->getGlobal();
10783 if (Subtarget->isTargetELF()) {
10784 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10787 case TLSModel::GeneralDynamic:
10788 if (Subtarget->is64Bit())
10789 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10790 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10791 case TLSModel::LocalDynamic:
10792 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10793 Subtarget->is64Bit());
10794 case TLSModel::InitialExec:
10795 case TLSModel::LocalExec:
10796 return LowerToTLSExecModel(
10797 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10798 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10800 llvm_unreachable("Unknown TLS model.");
10803 if (Subtarget->isTargetDarwin()) {
10804 // Darwin only has one model of TLS. Lower to that.
10805 unsigned char OpFlag = 0;
10806 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10807 X86ISD::WrapperRIP : X86ISD::Wrapper;
10809 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10810 // global base reg.
10811 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10812 !Subtarget->is64Bit();
10814 OpFlag = X86II::MO_TLVP_PIC_BASE;
10816 OpFlag = X86II::MO_TLVP;
10818 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10819 GA->getValueType(0),
10820 GA->getOffset(), OpFlag);
10821 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10823 // With PIC32, the address is actually $g + Offset.
10825 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10826 DAG.getNode(X86ISD::GlobalBaseReg,
10827 SDLoc(), getPointerTy()),
10830 // Lowering the machine isd will make sure everything is in the right
10832 SDValue Chain = DAG.getEntryNode();
10833 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10834 SDValue Args[] = { Chain, Offset };
10835 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10837 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10838 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10839 MFI->setAdjustsStack(true);
10841 // And our return value (tls address) is in the standard call return value
10843 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10844 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10845 Chain.getValue(1));
10848 if (Subtarget->isTargetKnownWindowsMSVC() ||
10849 Subtarget->isTargetWindowsGNU()) {
10850 // Just use the implicit TLS architecture
10851 // Need to generate someting similar to:
10852 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10854 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10855 // mov rcx, qword [rdx+rcx*8]
10856 // mov eax, .tls$:tlsvar
10857 // [rax+rcx] contains the address
10858 // Windows 64bit: gs:0x58
10859 // Windows 32bit: fs:__tls_array
10862 SDValue Chain = DAG.getEntryNode();
10864 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10865 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10866 // use its literal value of 0x2C.
10867 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10868 ? Type::getInt8PtrTy(*DAG.getContext(),
10870 : Type::getInt32PtrTy(*DAG.getContext(),
10874 Subtarget->is64Bit()
10875 ? DAG.getIntPtrConstant(0x58)
10876 : (Subtarget->isTargetWindowsGNU()
10877 ? DAG.getIntPtrConstant(0x2C)
10878 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10880 SDValue ThreadPointer =
10881 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10882 MachinePointerInfo(Ptr), false, false, false, 0);
10884 // Load the _tls_index variable
10885 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10886 if (Subtarget->is64Bit())
10887 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10888 IDX, MachinePointerInfo(), MVT::i32,
10889 false, false, false, 0);
10891 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10892 false, false, false, 0);
10894 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10896 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10898 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10899 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10900 false, false, false, 0);
10902 // Get the offset of start of .tls section
10903 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10904 GA->getValueType(0),
10905 GA->getOffset(), X86II::MO_SECREL);
10906 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10908 // The address of the thread local variable is the add of the thread
10909 // pointer with the offset of the variable.
10910 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10913 llvm_unreachable("TLS not implemented for this target.");
10916 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10917 /// and take a 2 x i32 value to shift plus a shift amount.
10918 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10919 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10920 MVT VT = Op.getSimpleValueType();
10921 unsigned VTBits = VT.getSizeInBits();
10923 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10924 SDValue ShOpLo = Op.getOperand(0);
10925 SDValue ShOpHi = Op.getOperand(1);
10926 SDValue ShAmt = Op.getOperand(2);
10927 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10928 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10930 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10931 DAG.getConstant(VTBits - 1, MVT::i8));
10932 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10933 DAG.getConstant(VTBits - 1, MVT::i8))
10934 : DAG.getConstant(0, VT);
10936 SDValue Tmp2, Tmp3;
10937 if (Op.getOpcode() == ISD::SHL_PARTS) {
10938 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10939 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10941 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10942 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10945 // If the shift amount is larger or equal than the width of a part we can't
10946 // rely on the results of shld/shrd. Insert a test and select the appropriate
10947 // values for large shift amounts.
10948 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10949 DAG.getConstant(VTBits, MVT::i8));
10950 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10951 AndNode, DAG.getConstant(0, MVT::i8));
10954 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10955 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10956 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10958 if (Op.getOpcode() == ISD::SHL_PARTS) {
10959 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10960 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10962 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10963 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10966 SDValue Ops[2] = { Lo, Hi };
10967 return DAG.getMergeValues(Ops, dl);
10970 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10971 SelectionDAG &DAG) const {
10972 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10974 if (SrcVT.isVector())
10977 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10978 "Unknown SINT_TO_FP to lower!");
10980 // These are really Legal; return the operand so the caller accepts it as
10982 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10984 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10985 Subtarget->is64Bit()) {
10990 unsigned Size = SrcVT.getSizeInBits()/8;
10991 MachineFunction &MF = DAG.getMachineFunction();
10992 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10993 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10994 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10996 MachinePointerInfo::getFixedStack(SSFI),
10998 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11001 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11003 SelectionDAG &DAG) const {
11007 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11009 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11011 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11013 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11015 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11016 MachineMemOperand *MMO;
11018 int SSFI = FI->getIndex();
11020 DAG.getMachineFunction()
11021 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11022 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11024 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11025 StackSlot = StackSlot.getOperand(1);
11027 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11028 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11030 Tys, Ops, SrcVT, MMO);
11033 Chain = Result.getValue(1);
11034 SDValue InFlag = Result.getValue(2);
11036 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11037 // shouldn't be necessary except that RFP cannot be live across
11038 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11039 MachineFunction &MF = DAG.getMachineFunction();
11040 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11041 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11042 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11043 Tys = DAG.getVTList(MVT::Other);
11045 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11047 MachineMemOperand *MMO =
11048 DAG.getMachineFunction()
11049 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11050 MachineMemOperand::MOStore, SSFISize, SSFISize);
11052 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11053 Ops, Op.getValueType(), MMO);
11054 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11055 MachinePointerInfo::getFixedStack(SSFI),
11056 false, false, false, 0);
11062 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11063 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11064 SelectionDAG &DAG) const {
11065 // This algorithm is not obvious. Here it is what we're trying to output:
11068 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11069 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11071 haddpd %xmm0, %xmm0
11073 pshufd $0x4e, %xmm0, %xmm1
11079 LLVMContext *Context = DAG.getContext();
11081 // Build some magic constants.
11082 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11083 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11084 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11086 SmallVector<Constant*,2> CV1;
11088 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11089 APInt(64, 0x4330000000000000ULL))));
11091 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11092 APInt(64, 0x4530000000000000ULL))));
11093 Constant *C1 = ConstantVector::get(CV1);
11094 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11096 // Load the 64-bit value into an XMM register.
11097 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11099 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11100 MachinePointerInfo::getConstantPool(),
11101 false, false, false, 16);
11102 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11103 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11106 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11107 MachinePointerInfo::getConstantPool(),
11108 false, false, false, 16);
11109 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11110 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11113 if (Subtarget->hasSSE3()) {
11114 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11115 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11117 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11118 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11120 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11121 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11125 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11126 DAG.getIntPtrConstant(0));
11129 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11130 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11131 SelectionDAG &DAG) const {
11133 // FP constant to bias correct the final result.
11134 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11137 // Load the 32-bit value into an XMM register.
11138 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11141 // Zero out the upper parts of the register.
11142 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11144 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11145 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11146 DAG.getIntPtrConstant(0));
11148 // Or the load with the bias.
11149 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11150 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11151 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11152 MVT::v2f64, Load)),
11153 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11154 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11155 MVT::v2f64, Bias)));
11156 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11157 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11158 DAG.getIntPtrConstant(0));
11160 // Subtract the bias.
11161 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11163 // Handle final rounding.
11164 EVT DestVT = Op.getValueType();
11166 if (DestVT.bitsLT(MVT::f64))
11167 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11168 DAG.getIntPtrConstant(0));
11169 if (DestVT.bitsGT(MVT::f64))
11170 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11172 // Handle final rounding.
11176 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11177 SelectionDAG &DAG) const {
11178 SDValue N0 = Op.getOperand(0);
11179 MVT SVT = N0.getSimpleValueType();
11182 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11183 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11184 "Custom UINT_TO_FP is not supported!");
11186 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11187 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11188 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11191 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11192 SelectionDAG &DAG) const {
11193 SDValue N0 = Op.getOperand(0);
11196 if (Op.getValueType().isVector())
11197 return lowerUINT_TO_FP_vec(Op, DAG);
11199 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11200 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11201 // the optimization here.
11202 if (DAG.SignBitIsZero(N0))
11203 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11205 MVT SrcVT = N0.getSimpleValueType();
11206 MVT DstVT = Op.getSimpleValueType();
11207 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11208 return LowerUINT_TO_FP_i64(Op, DAG);
11209 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11210 return LowerUINT_TO_FP_i32(Op, DAG);
11211 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11214 // Make a 64-bit buffer, and use it to build an FILD.
11215 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11216 if (SrcVT == MVT::i32) {
11217 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11218 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11219 getPointerTy(), StackSlot, WordOff);
11220 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11221 StackSlot, MachinePointerInfo(),
11223 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11224 OffsetSlot, MachinePointerInfo(),
11226 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11230 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11231 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11232 StackSlot, MachinePointerInfo(),
11234 // For i64 source, we need to add the appropriate power of 2 if the input
11235 // was negative. This is the same as the optimization in
11236 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11237 // we must be careful to do the computation in x87 extended precision, not
11238 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11239 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11240 MachineMemOperand *MMO =
11241 DAG.getMachineFunction()
11242 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11243 MachineMemOperand::MOLoad, 8, 8);
11245 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11246 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11247 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11250 APInt FF(32, 0x5F800000ULL);
11252 // Check whether the sign bit is set.
11253 SDValue SignSet = DAG.getSetCC(dl,
11254 getSetCCResultType(*DAG.getContext(), MVT::i64),
11255 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11258 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11259 SDValue FudgePtr = DAG.getConstantPool(
11260 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11263 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11264 SDValue Zero = DAG.getIntPtrConstant(0);
11265 SDValue Four = DAG.getIntPtrConstant(4);
11266 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11268 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11270 // Load the value out, extending it from f32 to f80.
11271 // FIXME: Avoid the extend by constructing the right constant pool?
11272 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11273 FudgePtr, MachinePointerInfo::getConstantPool(),
11274 MVT::f32, false, false, false, 4);
11275 // Extend everything to 80 bits to force it to be done on x87.
11276 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11277 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11280 std::pair<SDValue,SDValue>
11281 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11282 bool IsSigned, bool IsReplace) const {
11285 EVT DstTy = Op.getValueType();
11287 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11288 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11292 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11293 DstTy.getSimpleVT() >= MVT::i16 &&
11294 "Unknown FP_TO_INT to lower!");
11296 // These are really Legal.
11297 if (DstTy == MVT::i32 &&
11298 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11299 return std::make_pair(SDValue(), SDValue());
11300 if (Subtarget->is64Bit() &&
11301 DstTy == MVT::i64 &&
11302 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11303 return std::make_pair(SDValue(), SDValue());
11305 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11306 // stack slot, or into the FTOL runtime function.
11307 MachineFunction &MF = DAG.getMachineFunction();
11308 unsigned MemSize = DstTy.getSizeInBits()/8;
11309 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11310 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11313 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11314 Opc = X86ISD::WIN_FTOL;
11316 switch (DstTy.getSimpleVT().SimpleTy) {
11317 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11318 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11319 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11320 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11323 SDValue Chain = DAG.getEntryNode();
11324 SDValue Value = Op.getOperand(0);
11325 EVT TheVT = Op.getOperand(0).getValueType();
11326 // FIXME This causes a redundant load/store if the SSE-class value is already
11327 // in memory, such as if it is on the callstack.
11328 if (isScalarFPTypeInSSEReg(TheVT)) {
11329 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11330 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11331 MachinePointerInfo::getFixedStack(SSFI),
11333 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11335 Chain, StackSlot, DAG.getValueType(TheVT)
11338 MachineMemOperand *MMO =
11339 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11340 MachineMemOperand::MOLoad, MemSize, MemSize);
11341 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11342 Chain = Value.getValue(1);
11343 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11344 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11347 MachineMemOperand *MMO =
11348 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11349 MachineMemOperand::MOStore, MemSize, MemSize);
11351 if (Opc != X86ISD::WIN_FTOL) {
11352 // Build the FP_TO_INT*_IN_MEM
11353 SDValue Ops[] = { Chain, Value, StackSlot };
11354 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11356 return std::make_pair(FIST, StackSlot);
11358 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11359 DAG.getVTList(MVT::Other, MVT::Glue),
11361 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11362 MVT::i32, ftol.getValue(1));
11363 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11364 MVT::i32, eax.getValue(2));
11365 SDValue Ops[] = { eax, edx };
11366 SDValue pair = IsReplace
11367 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11368 : DAG.getMergeValues(Ops, DL);
11369 return std::make_pair(pair, SDValue());
11373 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11374 const X86Subtarget *Subtarget) {
11375 MVT VT = Op->getSimpleValueType(0);
11376 SDValue In = Op->getOperand(0);
11377 MVT InVT = In.getSimpleValueType();
11380 // Optimize vectors in AVX mode:
11383 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11384 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11385 // Concat upper and lower parts.
11388 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11389 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11390 // Concat upper and lower parts.
11393 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11394 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11395 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11398 if (Subtarget->hasInt256())
11399 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11401 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11402 SDValue Undef = DAG.getUNDEF(InVT);
11403 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11404 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11405 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11407 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11408 VT.getVectorNumElements()/2);
11410 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11411 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11413 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11416 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11417 SelectionDAG &DAG) {
11418 MVT VT = Op->getSimpleValueType(0);
11419 SDValue In = Op->getOperand(0);
11420 MVT InVT = In.getSimpleValueType();
11422 unsigned int NumElts = VT.getVectorNumElements();
11423 if (NumElts != 8 && NumElts != 16)
11426 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11427 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11429 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11430 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11431 // Now we have only mask extension
11432 assert(InVT.getVectorElementType() == MVT::i1);
11433 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11434 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11435 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11436 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11437 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11438 MachinePointerInfo::getConstantPool(),
11439 false, false, false, Alignment);
11441 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11442 if (VT.is512BitVector())
11444 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11447 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11448 SelectionDAG &DAG) {
11449 if (Subtarget->hasFp256()) {
11450 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11458 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11459 SelectionDAG &DAG) {
11461 MVT VT = Op.getSimpleValueType();
11462 SDValue In = Op.getOperand(0);
11463 MVT SVT = In.getSimpleValueType();
11465 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11466 return LowerZERO_EXTEND_AVX512(Op, DAG);
11468 if (Subtarget->hasFp256()) {
11469 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11474 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11475 VT.getVectorNumElements() != SVT.getVectorNumElements());
11479 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11481 MVT VT = Op.getSimpleValueType();
11482 SDValue In = Op.getOperand(0);
11483 MVT InVT = In.getSimpleValueType();
11485 if (VT == MVT::i1) {
11486 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11487 "Invalid scalar TRUNCATE operation");
11488 if (InVT == MVT::i32)
11490 if (InVT.getSizeInBits() == 64)
11491 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11492 else if (InVT.getSizeInBits() < 32)
11493 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11494 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11496 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11497 "Invalid TRUNCATE operation");
11499 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11500 if (VT.getVectorElementType().getSizeInBits() >=8)
11501 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11503 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11504 unsigned NumElts = InVT.getVectorNumElements();
11505 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11506 if (InVT.getSizeInBits() < 512) {
11507 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11508 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11512 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11513 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11514 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11515 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11516 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11517 MachinePointerInfo::getConstantPool(),
11518 false, false, false, Alignment);
11519 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11520 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11521 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11524 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11525 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11526 if (Subtarget->hasInt256()) {
11527 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11528 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11529 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11531 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11532 DAG.getIntPtrConstant(0));
11535 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11536 DAG.getIntPtrConstant(0));
11537 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11538 DAG.getIntPtrConstant(2));
11539 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11540 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11541 static const int ShufMask[] = {0, 2, 4, 6};
11542 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11545 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11546 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11547 if (Subtarget->hasInt256()) {
11548 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11550 SmallVector<SDValue,32> pshufbMask;
11551 for (unsigned i = 0; i < 2; ++i) {
11552 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11553 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11554 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11555 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11556 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11557 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11558 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11559 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11560 for (unsigned j = 0; j < 8; ++j)
11561 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11563 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11564 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11565 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11567 static const int ShufMask[] = {0, 2, -1, -1};
11568 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11570 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11571 DAG.getIntPtrConstant(0));
11572 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11575 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11576 DAG.getIntPtrConstant(0));
11578 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11579 DAG.getIntPtrConstant(4));
11581 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11582 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11584 // The PSHUFB mask:
11585 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11586 -1, -1, -1, -1, -1, -1, -1, -1};
11588 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11589 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11590 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11592 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11593 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11595 // The MOVLHPS Mask:
11596 static const int ShufMask2[] = {0, 1, 4, 5};
11597 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11598 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11601 // Handle truncation of V256 to V128 using shuffles.
11602 if (!VT.is128BitVector() || !InVT.is256BitVector())
11605 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11607 unsigned NumElems = VT.getVectorNumElements();
11608 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11610 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11611 // Prepare truncation shuffle mask
11612 for (unsigned i = 0; i != NumElems; ++i)
11613 MaskVec[i] = i * 2;
11614 SDValue V = DAG.getVectorShuffle(NVT, DL,
11615 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11616 DAG.getUNDEF(NVT), &MaskVec[0]);
11617 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11618 DAG.getIntPtrConstant(0));
11621 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11622 SelectionDAG &DAG) const {
11623 assert(!Op.getSimpleValueType().isVector());
11625 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11626 /*IsSigned=*/ true, /*IsReplace=*/ false);
11627 SDValue FIST = Vals.first, StackSlot = Vals.second;
11628 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11629 if (!FIST.getNode()) return Op;
11631 if (StackSlot.getNode())
11632 // Load the result.
11633 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11634 FIST, StackSlot, MachinePointerInfo(),
11635 false, false, false, 0);
11637 // The node is the result.
11641 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11642 SelectionDAG &DAG) const {
11643 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11644 /*IsSigned=*/ false, /*IsReplace=*/ false);
11645 SDValue FIST = Vals.first, StackSlot = Vals.second;
11646 assert(FIST.getNode() && "Unexpected failure");
11648 if (StackSlot.getNode())
11649 // Load the result.
11650 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11651 FIST, StackSlot, MachinePointerInfo(),
11652 false, false, false, 0);
11654 // The node is the result.
11658 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11660 MVT VT = Op.getSimpleValueType();
11661 SDValue In = Op.getOperand(0);
11662 MVT SVT = In.getSimpleValueType();
11664 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11666 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11667 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11668 In, DAG.getUNDEF(SVT)));
11671 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11672 LLVMContext *Context = DAG.getContext();
11674 MVT VT = Op.getSimpleValueType();
11676 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11677 if (VT.isVector()) {
11678 EltVT = VT.getVectorElementType();
11679 NumElts = VT.getVectorNumElements();
11682 if (EltVT == MVT::f64)
11683 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11684 APInt(64, ~(1ULL << 63))));
11686 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11687 APInt(32, ~(1U << 31))));
11688 C = ConstantVector::getSplat(NumElts, C);
11689 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11690 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11691 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11692 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11693 MachinePointerInfo::getConstantPool(),
11694 false, false, false, Alignment);
11695 if (VT.isVector()) {
11696 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11697 return DAG.getNode(ISD::BITCAST, dl, VT,
11698 DAG.getNode(ISD::AND, dl, ANDVT,
11699 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11701 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11703 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11706 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11707 LLVMContext *Context = DAG.getContext();
11709 MVT VT = Op.getSimpleValueType();
11711 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11712 if (VT.isVector()) {
11713 EltVT = VT.getVectorElementType();
11714 NumElts = VT.getVectorNumElements();
11717 if (EltVT == MVT::f64)
11718 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11719 APInt(64, 1ULL << 63)));
11721 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11722 APInt(32, 1U << 31)));
11723 C = ConstantVector::getSplat(NumElts, C);
11724 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11725 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11726 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11727 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11728 MachinePointerInfo::getConstantPool(),
11729 false, false, false, Alignment);
11730 if (VT.isVector()) {
11731 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11732 return DAG.getNode(ISD::BITCAST, dl, VT,
11733 DAG.getNode(ISD::XOR, dl, XORVT,
11734 DAG.getNode(ISD::BITCAST, dl, XORVT,
11736 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11739 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11742 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11743 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11744 LLVMContext *Context = DAG.getContext();
11745 SDValue Op0 = Op.getOperand(0);
11746 SDValue Op1 = Op.getOperand(1);
11748 MVT VT = Op.getSimpleValueType();
11749 MVT SrcVT = Op1.getSimpleValueType();
11751 // If second operand is smaller, extend it first.
11752 if (SrcVT.bitsLT(VT)) {
11753 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11756 // And if it is bigger, shrink it first.
11757 if (SrcVT.bitsGT(VT)) {
11758 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11762 // At this point the operands and the result should have the same
11763 // type, and that won't be f80 since that is not custom lowered.
11765 // First get the sign bit of second operand.
11766 SmallVector<Constant*,4> CV;
11767 if (SrcVT == MVT::f64) {
11768 const fltSemantics &Sem = APFloat::IEEEdouble;
11769 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11770 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11772 const fltSemantics &Sem = APFloat::IEEEsingle;
11773 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11774 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11775 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11776 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11778 Constant *C = ConstantVector::get(CV);
11779 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11780 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11781 MachinePointerInfo::getConstantPool(),
11782 false, false, false, 16);
11783 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11785 // Shift sign bit right or left if the two operands have different types.
11786 if (SrcVT.bitsGT(VT)) {
11787 // Op0 is MVT::f32, Op1 is MVT::f64.
11788 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11789 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11790 DAG.getConstant(32, MVT::i32));
11791 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11792 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11793 DAG.getIntPtrConstant(0));
11796 // Clear first operand sign bit.
11798 if (VT == MVT::f64) {
11799 const fltSemantics &Sem = APFloat::IEEEdouble;
11800 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11801 APInt(64, ~(1ULL << 63)))));
11802 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11804 const fltSemantics &Sem = APFloat::IEEEsingle;
11805 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11806 APInt(32, ~(1U << 31)))));
11807 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11808 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11809 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11811 C = ConstantVector::get(CV);
11812 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11813 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11814 MachinePointerInfo::getConstantPool(),
11815 false, false, false, 16);
11816 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11818 // Or the value with the sign bit.
11819 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11822 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11823 SDValue N0 = Op.getOperand(0);
11825 MVT VT = Op.getSimpleValueType();
11827 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11828 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11829 DAG.getConstant(1, VT));
11830 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11833 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11835 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11836 SelectionDAG &DAG) {
11837 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11839 if (!Subtarget->hasSSE41())
11842 if (!Op->hasOneUse())
11845 SDNode *N = Op.getNode();
11848 SmallVector<SDValue, 8> Opnds;
11849 DenseMap<SDValue, unsigned> VecInMap;
11850 SmallVector<SDValue, 8> VecIns;
11851 EVT VT = MVT::Other;
11853 // Recognize a special case where a vector is casted into wide integer to
11855 Opnds.push_back(N->getOperand(0));
11856 Opnds.push_back(N->getOperand(1));
11858 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11859 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11860 // BFS traverse all OR'd operands.
11861 if (I->getOpcode() == ISD::OR) {
11862 Opnds.push_back(I->getOperand(0));
11863 Opnds.push_back(I->getOperand(1));
11864 // Re-evaluate the number of nodes to be traversed.
11865 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11869 // Quit if a non-EXTRACT_VECTOR_ELT
11870 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11873 // Quit if without a constant index.
11874 SDValue Idx = I->getOperand(1);
11875 if (!isa<ConstantSDNode>(Idx))
11878 SDValue ExtractedFromVec = I->getOperand(0);
11879 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11880 if (M == VecInMap.end()) {
11881 VT = ExtractedFromVec.getValueType();
11882 // Quit if not 128/256-bit vector.
11883 if (!VT.is128BitVector() && !VT.is256BitVector())
11885 // Quit if not the same type.
11886 if (VecInMap.begin() != VecInMap.end() &&
11887 VT != VecInMap.begin()->first.getValueType())
11889 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11890 VecIns.push_back(ExtractedFromVec);
11892 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11895 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11896 "Not extracted from 128-/256-bit vector.");
11898 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11900 for (DenseMap<SDValue, unsigned>::const_iterator
11901 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11902 // Quit if not all elements are used.
11903 if (I->second != FullMask)
11907 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11909 // Cast all vectors into TestVT for PTEST.
11910 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11911 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11913 // If more than one full vectors are evaluated, OR them first before PTEST.
11914 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11915 // Each iteration will OR 2 nodes and append the result until there is only
11916 // 1 node left, i.e. the final OR'd value of all vectors.
11917 SDValue LHS = VecIns[Slot];
11918 SDValue RHS = VecIns[Slot + 1];
11919 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11922 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11923 VecIns.back(), VecIns.back());
11926 /// \brief return true if \c Op has a use that doesn't just read flags.
11927 static bool hasNonFlagsUse(SDValue Op) {
11928 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11930 SDNode *User = *UI;
11931 unsigned UOpNo = UI.getOperandNo();
11932 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11933 // Look pass truncate.
11934 UOpNo = User->use_begin().getOperandNo();
11935 User = *User->use_begin();
11938 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11939 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11945 /// Emit nodes that will be selected as "test Op0,Op0", or something
11947 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11948 SelectionDAG &DAG) const {
11949 if (Op.getValueType() == MVT::i1)
11950 // KORTEST instruction should be selected
11951 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11952 DAG.getConstant(0, Op.getValueType()));
11954 // CF and OF aren't always set the way we want. Determine which
11955 // of these we need.
11956 bool NeedCF = false;
11957 bool NeedOF = false;
11960 case X86::COND_A: case X86::COND_AE:
11961 case X86::COND_B: case X86::COND_BE:
11964 case X86::COND_G: case X86::COND_GE:
11965 case X86::COND_L: case X86::COND_LE:
11966 case X86::COND_O: case X86::COND_NO: {
11967 // Check if we really need to set the
11968 // Overflow flag. If NoSignedWrap is present
11969 // that is not actually needed.
11970 switch (Op->getOpcode()) {
11975 const BinaryWithFlagsSDNode *BinNode =
11976 cast<BinaryWithFlagsSDNode>(Op.getNode());
11977 if (BinNode->hasNoSignedWrap())
11987 // See if we can use the EFLAGS value from the operand instead of
11988 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11989 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11990 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11991 // Emit a CMP with 0, which is the TEST pattern.
11992 //if (Op.getValueType() == MVT::i1)
11993 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11994 // DAG.getConstant(0, MVT::i1));
11995 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11996 DAG.getConstant(0, Op.getValueType()));
11998 unsigned Opcode = 0;
11999 unsigned NumOperands = 0;
12001 // Truncate operations may prevent the merge of the SETCC instruction
12002 // and the arithmetic instruction before it. Attempt to truncate the operands
12003 // of the arithmetic instruction and use a reduced bit-width instruction.
12004 bool NeedTruncation = false;
12005 SDValue ArithOp = Op;
12006 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12007 SDValue Arith = Op->getOperand(0);
12008 // Both the trunc and the arithmetic op need to have one user each.
12009 if (Arith->hasOneUse())
12010 switch (Arith.getOpcode()) {
12017 NeedTruncation = true;
12023 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12024 // which may be the result of a CAST. We use the variable 'Op', which is the
12025 // non-casted variable when we check for possible users.
12026 switch (ArithOp.getOpcode()) {
12028 // Due to an isel shortcoming, be conservative if this add is likely to be
12029 // selected as part of a load-modify-store instruction. When the root node
12030 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12031 // uses of other nodes in the match, such as the ADD in this case. This
12032 // leads to the ADD being left around and reselected, with the result being
12033 // two adds in the output. Alas, even if none our users are stores, that
12034 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12035 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12036 // climbing the DAG back to the root, and it doesn't seem to be worth the
12038 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12039 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12040 if (UI->getOpcode() != ISD::CopyToReg &&
12041 UI->getOpcode() != ISD::SETCC &&
12042 UI->getOpcode() != ISD::STORE)
12045 if (ConstantSDNode *C =
12046 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12047 // An add of one will be selected as an INC.
12048 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12049 Opcode = X86ISD::INC;
12054 // An add of negative one (subtract of one) will be selected as a DEC.
12055 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12056 Opcode = X86ISD::DEC;
12062 // Otherwise use a regular EFLAGS-setting add.
12063 Opcode = X86ISD::ADD;
12068 // If we have a constant logical shift that's only used in a comparison
12069 // against zero turn it into an equivalent AND. This allows turning it into
12070 // a TEST instruction later.
12071 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12072 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12073 EVT VT = Op.getValueType();
12074 unsigned BitWidth = VT.getSizeInBits();
12075 unsigned ShAmt = Op->getConstantOperandVal(1);
12076 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12078 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12079 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12080 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12081 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12083 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12084 DAG.getConstant(Mask, VT));
12085 DAG.ReplaceAllUsesWith(Op, New);
12091 // If the primary and result isn't used, don't bother using X86ISD::AND,
12092 // because a TEST instruction will be better.
12093 if (!hasNonFlagsUse(Op))
12099 // Due to the ISEL shortcoming noted above, be conservative if this op is
12100 // likely to be selected as part of a load-modify-store instruction.
12101 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12102 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12103 if (UI->getOpcode() == ISD::STORE)
12106 // Otherwise use a regular EFLAGS-setting instruction.
12107 switch (ArithOp.getOpcode()) {
12108 default: llvm_unreachable("unexpected operator!");
12109 case ISD::SUB: Opcode = X86ISD::SUB; break;
12110 case ISD::XOR: Opcode = X86ISD::XOR; break;
12111 case ISD::AND: Opcode = X86ISD::AND; break;
12113 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12114 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12115 if (EFLAGS.getNode())
12118 Opcode = X86ISD::OR;
12132 return SDValue(Op.getNode(), 1);
12138 // If we found that truncation is beneficial, perform the truncation and
12140 if (NeedTruncation) {
12141 EVT VT = Op.getValueType();
12142 SDValue WideVal = Op->getOperand(0);
12143 EVT WideVT = WideVal.getValueType();
12144 unsigned ConvertedOp = 0;
12145 // Use a target machine opcode to prevent further DAGCombine
12146 // optimizations that may separate the arithmetic operations
12147 // from the setcc node.
12148 switch (WideVal.getOpcode()) {
12150 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12151 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12152 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12153 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12154 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12158 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12159 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12160 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12161 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12162 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12168 // Emit a CMP with 0, which is the TEST pattern.
12169 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12170 DAG.getConstant(0, Op.getValueType()));
12172 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12173 SmallVector<SDValue, 4> Ops;
12174 for (unsigned i = 0; i != NumOperands; ++i)
12175 Ops.push_back(Op.getOperand(i));
12177 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12178 DAG.ReplaceAllUsesWith(Op, New);
12179 return SDValue(New.getNode(), 1);
12182 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12184 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12185 SDLoc dl, SelectionDAG &DAG) const {
12186 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12187 if (C->getAPIntValue() == 0)
12188 return EmitTest(Op0, X86CC, dl, DAG);
12190 if (Op0.getValueType() == MVT::i1)
12191 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12194 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12195 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12196 // Do the comparison at i32 if it's smaller, besides the Atom case.
12197 // This avoids subregister aliasing issues. Keep the smaller reference
12198 // if we're optimizing for size, however, as that'll allow better folding
12199 // of memory operations.
12200 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12201 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12202 AttributeSet::FunctionIndex, Attribute::MinSize) &&
12203 !Subtarget->isAtom()) {
12204 unsigned ExtendOp =
12205 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12206 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12207 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12209 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12210 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12211 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12213 return SDValue(Sub.getNode(), 1);
12215 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12218 /// Convert a comparison if required by the subtarget.
12219 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12220 SelectionDAG &DAG) const {
12221 // If the subtarget does not support the FUCOMI instruction, floating-point
12222 // comparisons have to be converted.
12223 if (Subtarget->hasCMov() ||
12224 Cmp.getOpcode() != X86ISD::CMP ||
12225 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12226 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12229 // The instruction selector will select an FUCOM instruction instead of
12230 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12231 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12232 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12234 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12235 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12236 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12237 DAG.getConstant(8, MVT::i8));
12238 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12239 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12242 static bool isAllOnes(SDValue V) {
12243 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12244 return C && C->isAllOnesValue();
12247 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12248 /// if it's possible.
12249 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12250 SDLoc dl, SelectionDAG &DAG) const {
12251 SDValue Op0 = And.getOperand(0);
12252 SDValue Op1 = And.getOperand(1);
12253 if (Op0.getOpcode() == ISD::TRUNCATE)
12254 Op0 = Op0.getOperand(0);
12255 if (Op1.getOpcode() == ISD::TRUNCATE)
12256 Op1 = Op1.getOperand(0);
12259 if (Op1.getOpcode() == ISD::SHL)
12260 std::swap(Op0, Op1);
12261 if (Op0.getOpcode() == ISD::SHL) {
12262 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12263 if (And00C->getZExtValue() == 1) {
12264 // If we looked past a truncate, check that it's only truncating away
12266 unsigned BitWidth = Op0.getValueSizeInBits();
12267 unsigned AndBitWidth = And.getValueSizeInBits();
12268 if (BitWidth > AndBitWidth) {
12270 DAG.computeKnownBits(Op0, Zeros, Ones);
12271 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12275 RHS = Op0.getOperand(1);
12277 } else if (Op1.getOpcode() == ISD::Constant) {
12278 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12279 uint64_t AndRHSVal = AndRHS->getZExtValue();
12280 SDValue AndLHS = Op0;
12282 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12283 LHS = AndLHS.getOperand(0);
12284 RHS = AndLHS.getOperand(1);
12287 // Use BT if the immediate can't be encoded in a TEST instruction.
12288 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12290 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12294 if (LHS.getNode()) {
12295 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12296 // instruction. Since the shift amount is in-range-or-undefined, we know
12297 // that doing a bittest on the i32 value is ok. We extend to i32 because
12298 // the encoding for the i16 version is larger than the i32 version.
12299 // Also promote i16 to i32 for performance / code size reason.
12300 if (LHS.getValueType() == MVT::i8 ||
12301 LHS.getValueType() == MVT::i16)
12302 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12304 // If the operand types disagree, extend the shift amount to match. Since
12305 // BT ignores high bits (like shifts) we can use anyextend.
12306 if (LHS.getValueType() != RHS.getValueType())
12307 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12309 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12310 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12311 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12312 DAG.getConstant(Cond, MVT::i8), BT);
12318 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12320 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12325 // SSE Condition code mapping:
12334 switch (SetCCOpcode) {
12335 default: llvm_unreachable("Unexpected SETCC condition");
12337 case ISD::SETEQ: SSECC = 0; break;
12339 case ISD::SETGT: Swap = true; // Fallthrough
12341 case ISD::SETOLT: SSECC = 1; break;
12343 case ISD::SETGE: Swap = true; // Fallthrough
12345 case ISD::SETOLE: SSECC = 2; break;
12346 case ISD::SETUO: SSECC = 3; break;
12348 case ISD::SETNE: SSECC = 4; break;
12349 case ISD::SETULE: Swap = true; // Fallthrough
12350 case ISD::SETUGE: SSECC = 5; break;
12351 case ISD::SETULT: Swap = true; // Fallthrough
12352 case ISD::SETUGT: SSECC = 6; break;
12353 case ISD::SETO: SSECC = 7; break;
12355 case ISD::SETONE: SSECC = 8; break;
12358 std::swap(Op0, Op1);
12363 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12364 // ones, and then concatenate the result back.
12365 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12366 MVT VT = Op.getSimpleValueType();
12368 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12369 "Unsupported value type for operation");
12371 unsigned NumElems = VT.getVectorNumElements();
12373 SDValue CC = Op.getOperand(2);
12375 // Extract the LHS vectors
12376 SDValue LHS = Op.getOperand(0);
12377 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12378 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12380 // Extract the RHS vectors
12381 SDValue RHS = Op.getOperand(1);
12382 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12383 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12385 // Issue the operation on the smaller types and concatenate the result back
12386 MVT EltVT = VT.getVectorElementType();
12387 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12388 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12389 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12390 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12393 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12394 const X86Subtarget *Subtarget) {
12395 SDValue Op0 = Op.getOperand(0);
12396 SDValue Op1 = Op.getOperand(1);
12397 SDValue CC = Op.getOperand(2);
12398 MVT VT = Op.getSimpleValueType();
12401 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12402 Op.getValueType().getScalarType() == MVT::i1 &&
12403 "Cannot set masked compare for this operation");
12405 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12407 bool Unsigned = false;
12410 switch (SetCCOpcode) {
12411 default: llvm_unreachable("Unexpected SETCC condition");
12412 case ISD::SETNE: SSECC = 4; break;
12413 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12414 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12415 case ISD::SETLT: Swap = true; //fall-through
12416 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12417 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12418 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12419 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12420 case ISD::SETULE: Unsigned = true; //fall-through
12421 case ISD::SETLE: SSECC = 2; break;
12425 std::swap(Op0, Op1);
12427 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12428 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12429 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12430 DAG.getConstant(SSECC, MVT::i8));
12433 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12434 /// operand \p Op1. If non-trivial (for example because it's not constant)
12435 /// return an empty value.
12436 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12438 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12442 MVT VT = Op1.getSimpleValueType();
12443 MVT EVT = VT.getVectorElementType();
12444 unsigned n = VT.getVectorNumElements();
12445 SmallVector<SDValue, 8> ULTOp1;
12447 for (unsigned i = 0; i < n; ++i) {
12448 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12449 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12452 // Avoid underflow.
12453 APInt Val = Elt->getAPIntValue();
12457 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12460 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12463 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12464 SelectionDAG &DAG) {
12465 SDValue Op0 = Op.getOperand(0);
12466 SDValue Op1 = Op.getOperand(1);
12467 SDValue CC = Op.getOperand(2);
12468 MVT VT = Op.getSimpleValueType();
12469 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12470 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12475 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12476 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12479 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12480 unsigned Opc = X86ISD::CMPP;
12481 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12482 assert(VT.getVectorNumElements() <= 16);
12483 Opc = X86ISD::CMPM;
12485 // In the two special cases we can't handle, emit two comparisons.
12488 unsigned CombineOpc;
12489 if (SetCCOpcode == ISD::SETUEQ) {
12490 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12492 assert(SetCCOpcode == ISD::SETONE);
12493 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12496 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12497 DAG.getConstant(CC0, MVT::i8));
12498 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12499 DAG.getConstant(CC1, MVT::i8));
12500 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12502 // Handle all other FP comparisons here.
12503 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12504 DAG.getConstant(SSECC, MVT::i8));
12507 // Break 256-bit integer vector compare into smaller ones.
12508 if (VT.is256BitVector() && !Subtarget->hasInt256())
12509 return Lower256IntVSETCC(Op, DAG);
12511 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12512 EVT OpVT = Op1.getValueType();
12513 if (Subtarget->hasAVX512()) {
12514 if (Op1.getValueType().is512BitVector() ||
12515 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12516 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12518 // In AVX-512 architecture setcc returns mask with i1 elements,
12519 // But there is no compare instruction for i8 and i16 elements.
12520 // We are not talking about 512-bit operands in this case, these
12521 // types are illegal.
12523 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12524 OpVT.getVectorElementType().getSizeInBits() >= 8))
12525 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12526 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12529 // We are handling one of the integer comparisons here. Since SSE only has
12530 // GT and EQ comparisons for integer, swapping operands and multiple
12531 // operations may be required for some comparisons.
12533 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12534 bool Subus = false;
12536 switch (SetCCOpcode) {
12537 default: llvm_unreachable("Unexpected SETCC condition");
12538 case ISD::SETNE: Invert = true;
12539 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12540 case ISD::SETLT: Swap = true;
12541 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12542 case ISD::SETGE: Swap = true;
12543 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12544 Invert = true; break;
12545 case ISD::SETULT: Swap = true;
12546 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12547 FlipSigns = true; break;
12548 case ISD::SETUGE: Swap = true;
12549 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12550 FlipSigns = true; Invert = true; break;
12553 // Special case: Use min/max operations for SETULE/SETUGE
12554 MVT VET = VT.getVectorElementType();
12556 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12557 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12560 switch (SetCCOpcode) {
12562 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12563 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12566 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12569 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12570 if (!MinMax && hasSubus) {
12571 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12573 // t = psubus Op0, Op1
12574 // pcmpeq t, <0..0>
12575 switch (SetCCOpcode) {
12577 case ISD::SETULT: {
12578 // If the comparison is against a constant we can turn this into a
12579 // setule. With psubus, setule does not require a swap. This is
12580 // beneficial because the constant in the register is no longer
12581 // destructed as the destination so it can be hoisted out of a loop.
12582 // Only do this pre-AVX since vpcmp* is no longer destructive.
12583 if (Subtarget->hasAVX())
12585 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12586 if (ULEOp1.getNode()) {
12588 Subus = true; Invert = false; Swap = false;
12592 // Psubus is better than flip-sign because it requires no inversion.
12593 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12594 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12598 Opc = X86ISD::SUBUS;
12604 std::swap(Op0, Op1);
12606 // Check that the operation in question is available (most are plain SSE2,
12607 // but PCMPGTQ and PCMPEQQ have different requirements).
12608 if (VT == MVT::v2i64) {
12609 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12610 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12612 // First cast everything to the right type.
12613 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12614 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12616 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12617 // bits of the inputs before performing those operations. The lower
12618 // compare is always unsigned.
12621 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12623 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12624 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12625 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12626 Sign, Zero, Sign, Zero);
12628 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12629 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12631 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12632 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12633 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12635 // Create masks for only the low parts/high parts of the 64 bit integers.
12636 static const int MaskHi[] = { 1, 1, 3, 3 };
12637 static const int MaskLo[] = { 0, 0, 2, 2 };
12638 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12639 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12640 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12642 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12643 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12646 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12648 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12651 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12652 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12653 // pcmpeqd + pshufd + pand.
12654 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12656 // First cast everything to the right type.
12657 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12658 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12661 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12663 // Make sure the lower and upper halves are both all-ones.
12664 static const int Mask[] = { 1, 0, 3, 2 };
12665 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12666 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12669 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12671 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12675 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12676 // bits of the inputs before performing those operations.
12678 EVT EltVT = VT.getVectorElementType();
12679 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12680 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12681 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12684 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12686 // If the logical-not of the result is required, perform that now.
12688 Result = DAG.getNOT(dl, Result, VT);
12691 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12694 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12695 getZeroVector(VT, Subtarget, DAG, dl));
12700 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12702 MVT VT = Op.getSimpleValueType();
12704 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12706 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12707 && "SetCC type must be 8-bit or 1-bit integer");
12708 SDValue Op0 = Op.getOperand(0);
12709 SDValue Op1 = Op.getOperand(1);
12711 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12713 // Optimize to BT if possible.
12714 // Lower (X & (1 << N)) == 0 to BT(X, N).
12715 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12716 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12717 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12718 Op1.getOpcode() == ISD::Constant &&
12719 cast<ConstantSDNode>(Op1)->isNullValue() &&
12720 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12721 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12722 if (NewSetCC.getNode())
12726 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12728 if (Op1.getOpcode() == ISD::Constant &&
12729 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12730 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12731 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12733 // If the input is a setcc, then reuse the input setcc or use a new one with
12734 // the inverted condition.
12735 if (Op0.getOpcode() == X86ISD::SETCC) {
12736 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12737 bool Invert = (CC == ISD::SETNE) ^
12738 cast<ConstantSDNode>(Op1)->isNullValue();
12742 CCode = X86::GetOppositeBranchCondition(CCode);
12743 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12744 DAG.getConstant(CCode, MVT::i8),
12745 Op0.getOperand(1));
12747 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12751 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12752 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12753 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12755 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12756 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12759 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12760 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12761 if (X86CC == X86::COND_INVALID)
12764 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12765 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12766 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12767 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12769 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12773 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12774 static bool isX86LogicalCmp(SDValue Op) {
12775 unsigned Opc = Op.getNode()->getOpcode();
12776 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12777 Opc == X86ISD::SAHF)
12779 if (Op.getResNo() == 1 &&
12780 (Opc == X86ISD::ADD ||
12781 Opc == X86ISD::SUB ||
12782 Opc == X86ISD::ADC ||
12783 Opc == X86ISD::SBB ||
12784 Opc == X86ISD::SMUL ||
12785 Opc == X86ISD::UMUL ||
12786 Opc == X86ISD::INC ||
12787 Opc == X86ISD::DEC ||
12788 Opc == X86ISD::OR ||
12789 Opc == X86ISD::XOR ||
12790 Opc == X86ISD::AND))
12793 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12799 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12800 if (V.getOpcode() != ISD::TRUNCATE)
12803 SDValue VOp0 = V.getOperand(0);
12804 unsigned InBits = VOp0.getValueSizeInBits();
12805 unsigned Bits = V.getValueSizeInBits();
12806 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12809 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12810 bool addTest = true;
12811 SDValue Cond = Op.getOperand(0);
12812 SDValue Op1 = Op.getOperand(1);
12813 SDValue Op2 = Op.getOperand(2);
12815 EVT VT = Op1.getValueType();
12818 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12819 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12820 // sequence later on.
12821 if (Cond.getOpcode() == ISD::SETCC &&
12822 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12823 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12824 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12825 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12826 int SSECC = translateX86FSETCC(
12827 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12830 if (Subtarget->hasAVX512()) {
12831 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12832 DAG.getConstant(SSECC, MVT::i8));
12833 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12835 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12836 DAG.getConstant(SSECC, MVT::i8));
12837 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12838 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12839 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12843 if (Cond.getOpcode() == ISD::SETCC) {
12844 SDValue NewCond = LowerSETCC(Cond, DAG);
12845 if (NewCond.getNode())
12849 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12850 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12851 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12852 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12853 if (Cond.getOpcode() == X86ISD::SETCC &&
12854 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12855 isZero(Cond.getOperand(1).getOperand(1))) {
12856 SDValue Cmp = Cond.getOperand(1);
12858 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12860 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12861 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12862 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12864 SDValue CmpOp0 = Cmp.getOperand(0);
12865 // Apply further optimizations for special cases
12866 // (select (x != 0), -1, 0) -> neg & sbb
12867 // (select (x == 0), 0, -1) -> neg & sbb
12868 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12869 if (YC->isNullValue() &&
12870 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12871 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12872 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12873 DAG.getConstant(0, CmpOp0.getValueType()),
12875 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12876 DAG.getConstant(X86::COND_B, MVT::i8),
12877 SDValue(Neg.getNode(), 1));
12881 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12882 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12883 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12885 SDValue Res = // Res = 0 or -1.
12886 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12887 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12889 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12890 Res = DAG.getNOT(DL, Res, Res.getValueType());
12892 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12893 if (!N2C || !N2C->isNullValue())
12894 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12899 // Look past (and (setcc_carry (cmp ...)), 1).
12900 if (Cond.getOpcode() == ISD::AND &&
12901 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12902 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12903 if (C && C->getAPIntValue() == 1)
12904 Cond = Cond.getOperand(0);
12907 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12908 // setting operand in place of the X86ISD::SETCC.
12909 unsigned CondOpcode = Cond.getOpcode();
12910 if (CondOpcode == X86ISD::SETCC ||
12911 CondOpcode == X86ISD::SETCC_CARRY) {
12912 CC = Cond.getOperand(0);
12914 SDValue Cmp = Cond.getOperand(1);
12915 unsigned Opc = Cmp.getOpcode();
12916 MVT VT = Op.getSimpleValueType();
12918 bool IllegalFPCMov = false;
12919 if (VT.isFloatingPoint() && !VT.isVector() &&
12920 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12921 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12923 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12924 Opc == X86ISD::BT) { // FIXME
12928 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12929 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12930 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12931 Cond.getOperand(0).getValueType() != MVT::i8)) {
12932 SDValue LHS = Cond.getOperand(0);
12933 SDValue RHS = Cond.getOperand(1);
12934 unsigned X86Opcode;
12937 switch (CondOpcode) {
12938 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12939 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12940 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12941 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12942 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12943 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12944 default: llvm_unreachable("unexpected overflowing operator");
12946 if (CondOpcode == ISD::UMULO)
12947 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12950 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12952 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12954 if (CondOpcode == ISD::UMULO)
12955 Cond = X86Op.getValue(2);
12957 Cond = X86Op.getValue(1);
12959 CC = DAG.getConstant(X86Cond, MVT::i8);
12964 // Look pass the truncate if the high bits are known zero.
12965 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12966 Cond = Cond.getOperand(0);
12968 // We know the result of AND is compared against zero. Try to match
12970 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12971 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12972 if (NewSetCC.getNode()) {
12973 CC = NewSetCC.getOperand(0);
12974 Cond = NewSetCC.getOperand(1);
12981 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12982 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12985 // a < b ? -1 : 0 -> RES = ~setcc_carry
12986 // a < b ? 0 : -1 -> RES = setcc_carry
12987 // a >= b ? -1 : 0 -> RES = setcc_carry
12988 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12989 if (Cond.getOpcode() == X86ISD::SUB) {
12990 Cond = ConvertCmpIfNecessary(Cond, DAG);
12991 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12993 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12994 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12995 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12996 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12997 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12998 return DAG.getNOT(DL, Res, Res.getValueType());
13003 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13004 // widen the cmov and push the truncate through. This avoids introducing a new
13005 // branch during isel and doesn't add any extensions.
13006 if (Op.getValueType() == MVT::i8 &&
13007 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13008 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13009 if (T1.getValueType() == T2.getValueType() &&
13010 // Blacklist CopyFromReg to avoid partial register stalls.
13011 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13012 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13013 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13014 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13018 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13019 // condition is true.
13020 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13021 SDValue Ops[] = { Op2, Op1, CC, Cond };
13022 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13025 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13026 MVT VT = Op->getSimpleValueType(0);
13027 SDValue In = Op->getOperand(0);
13028 MVT InVT = In.getSimpleValueType();
13031 unsigned int NumElts = VT.getVectorNumElements();
13032 if (NumElts != 8 && NumElts != 16)
13035 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13036 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13039 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13041 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13042 Constant *C = ConstantInt::get(*DAG.getContext(),
13043 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13045 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13046 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13047 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13048 MachinePointerInfo::getConstantPool(),
13049 false, false, false, Alignment);
13050 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13051 if (VT.is512BitVector())
13053 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13056 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13057 SelectionDAG &DAG) {
13058 MVT VT = Op->getSimpleValueType(0);
13059 SDValue In = Op->getOperand(0);
13060 MVT InVT = In.getSimpleValueType();
13063 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13064 return LowerSIGN_EXTEND_AVX512(Op, DAG);
13066 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13067 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13068 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13071 if (Subtarget->hasInt256())
13072 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13074 // Optimize vectors in AVX mode
13075 // Sign extend v8i16 to v8i32 and
13078 // Divide input vector into two parts
13079 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13080 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13081 // concat the vectors to original VT
13083 unsigned NumElems = InVT.getVectorNumElements();
13084 SDValue Undef = DAG.getUNDEF(InVT);
13086 SmallVector<int,8> ShufMask1(NumElems, -1);
13087 for (unsigned i = 0; i != NumElems/2; ++i)
13090 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13092 SmallVector<int,8> ShufMask2(NumElems, -1);
13093 for (unsigned i = 0; i != NumElems/2; ++i)
13094 ShufMask2[i] = i + NumElems/2;
13096 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13098 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13099 VT.getVectorNumElements()/2);
13101 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13102 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13104 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13107 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13108 // may emit an illegal shuffle but the expansion is still better than scalar
13109 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13110 // we'll emit a shuffle and a arithmetic shift.
13111 // TODO: It is possible to support ZExt by zeroing the undef values during
13112 // the shuffle phase or after the shuffle.
13113 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13114 SelectionDAG &DAG) {
13115 MVT RegVT = Op.getSimpleValueType();
13116 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13117 assert(RegVT.isInteger() &&
13118 "We only custom lower integer vector sext loads.");
13120 // Nothing useful we can do without SSE2 shuffles.
13121 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13123 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13125 EVT MemVT = Ld->getMemoryVT();
13126 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13127 unsigned RegSz = RegVT.getSizeInBits();
13129 ISD::LoadExtType Ext = Ld->getExtensionType();
13131 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13132 && "Only anyext and sext are currently implemented.");
13133 assert(MemVT != RegVT && "Cannot extend to the same type");
13134 assert(MemVT.isVector() && "Must load a vector from memory");
13136 unsigned NumElems = RegVT.getVectorNumElements();
13137 unsigned MemSz = MemVT.getSizeInBits();
13138 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13140 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13141 // The only way in which we have a legal 256-bit vector result but not the
13142 // integer 256-bit operations needed to directly lower a sextload is if we
13143 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13144 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13145 // correctly legalized. We do this late to allow the canonical form of
13146 // sextload to persist throughout the rest of the DAG combiner -- it wants
13147 // to fold together any extensions it can, and so will fuse a sign_extend
13148 // of an sextload into an sextload targeting a wider value.
13150 if (MemSz == 128) {
13151 // Just switch this to a normal load.
13152 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13153 "it must be a legal 128-bit vector "
13155 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13156 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13157 Ld->isInvariant(), Ld->getAlignment());
13159 assert(MemSz < 128 &&
13160 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13161 // Do an sext load to a 128-bit vector type. We want to use the same
13162 // number of elements, but elements half as wide. This will end up being
13163 // recursively lowered by this routine, but will succeed as we definitely
13164 // have all the necessary features if we're using AVX1.
13166 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13167 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13169 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13170 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13171 Ld->isNonTemporal(), Ld->isInvariant(),
13172 Ld->getAlignment());
13175 // Replace chain users with the new chain.
13176 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13177 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13179 // Finally, do a normal sign-extend to the desired register.
13180 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13183 // All sizes must be a power of two.
13184 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13185 "Non-power-of-two elements are not custom lowered!");
13187 // Attempt to load the original value using scalar loads.
13188 // Find the largest scalar type that divides the total loaded size.
13189 MVT SclrLoadTy = MVT::i8;
13190 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13191 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13192 MVT Tp = (MVT::SimpleValueType)tp;
13193 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13198 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13199 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13201 SclrLoadTy = MVT::f64;
13203 // Calculate the number of scalar loads that we need to perform
13204 // in order to load our vector from memory.
13205 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13207 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13208 "Can only lower sext loads with a single scalar load!");
13210 unsigned loadRegZize = RegSz;
13211 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13214 // Represent our vector as a sequence of elements which are the
13215 // largest scalar that we can load.
13216 EVT LoadUnitVecVT = EVT::getVectorVT(
13217 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13219 // Represent the data using the same element type that is stored in
13220 // memory. In practice, we ''widen'' MemVT.
13222 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13223 loadRegZize / MemVT.getScalarType().getSizeInBits());
13225 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13226 "Invalid vector type");
13228 // We can't shuffle using an illegal type.
13229 assert(TLI.isTypeLegal(WideVecVT) &&
13230 "We only lower types that form legal widened vector types");
13232 SmallVector<SDValue, 8> Chains;
13233 SDValue Ptr = Ld->getBasePtr();
13234 SDValue Increment =
13235 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13236 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13238 for (unsigned i = 0; i < NumLoads; ++i) {
13239 // Perform a single load.
13240 SDValue ScalarLoad =
13241 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13242 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13243 Ld->getAlignment());
13244 Chains.push_back(ScalarLoad.getValue(1));
13245 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13246 // another round of DAGCombining.
13248 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13250 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13251 ScalarLoad, DAG.getIntPtrConstant(i));
13253 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13256 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13258 // Bitcast the loaded value to a vector of the original element type, in
13259 // the size of the target vector type.
13260 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13261 unsigned SizeRatio = RegSz / MemSz;
13263 if (Ext == ISD::SEXTLOAD) {
13264 // If we have SSE4.1 we can directly emit a VSEXT node.
13265 if (Subtarget->hasSSE41()) {
13266 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13267 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13271 // Otherwise we'll shuffle the small elements in the high bits of the
13272 // larger type and perform an arithmetic shift. If the shift is not legal
13273 // it's better to scalarize.
13274 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13275 "We can't implement an sext load without a arithmetic right shift!");
13277 // Redistribute the loaded elements into the different locations.
13278 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13279 for (unsigned i = 0; i != NumElems; ++i)
13280 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13282 SDValue Shuff = DAG.getVectorShuffle(
13283 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13285 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13287 // Build the arithmetic shift.
13288 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13289 MemVT.getVectorElementType().getSizeInBits();
13291 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13293 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13297 // Redistribute the loaded elements into the different locations.
13298 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13299 for (unsigned i = 0; i != NumElems; ++i)
13300 ShuffleVec[i * SizeRatio] = i;
13302 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13303 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13305 // Bitcast to the requested type.
13306 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13307 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13311 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13312 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13313 // from the AND / OR.
13314 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13315 Opc = Op.getOpcode();
13316 if (Opc != ISD::OR && Opc != ISD::AND)
13318 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13319 Op.getOperand(0).hasOneUse() &&
13320 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13321 Op.getOperand(1).hasOneUse());
13324 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13325 // 1 and that the SETCC node has a single use.
13326 static bool isXor1OfSetCC(SDValue Op) {
13327 if (Op.getOpcode() != ISD::XOR)
13329 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13330 if (N1C && N1C->getAPIntValue() == 1) {
13331 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13332 Op.getOperand(0).hasOneUse();
13337 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13338 bool addTest = true;
13339 SDValue Chain = Op.getOperand(0);
13340 SDValue Cond = Op.getOperand(1);
13341 SDValue Dest = Op.getOperand(2);
13344 bool Inverted = false;
13346 if (Cond.getOpcode() == ISD::SETCC) {
13347 // Check for setcc([su]{add,sub,mul}o == 0).
13348 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13349 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13350 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13351 Cond.getOperand(0).getResNo() == 1 &&
13352 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13353 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13354 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13355 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13356 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13357 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13359 Cond = Cond.getOperand(0);
13361 SDValue NewCond = LowerSETCC(Cond, DAG);
13362 if (NewCond.getNode())
13367 // FIXME: LowerXALUO doesn't handle these!!
13368 else if (Cond.getOpcode() == X86ISD::ADD ||
13369 Cond.getOpcode() == X86ISD::SUB ||
13370 Cond.getOpcode() == X86ISD::SMUL ||
13371 Cond.getOpcode() == X86ISD::UMUL)
13372 Cond = LowerXALUO(Cond, DAG);
13375 // Look pass (and (setcc_carry (cmp ...)), 1).
13376 if (Cond.getOpcode() == ISD::AND &&
13377 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13378 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13379 if (C && C->getAPIntValue() == 1)
13380 Cond = Cond.getOperand(0);
13383 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13384 // setting operand in place of the X86ISD::SETCC.
13385 unsigned CondOpcode = Cond.getOpcode();
13386 if (CondOpcode == X86ISD::SETCC ||
13387 CondOpcode == X86ISD::SETCC_CARRY) {
13388 CC = Cond.getOperand(0);
13390 SDValue Cmp = Cond.getOperand(1);
13391 unsigned Opc = Cmp.getOpcode();
13392 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13393 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13397 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13401 // These can only come from an arithmetic instruction with overflow,
13402 // e.g. SADDO, UADDO.
13403 Cond = Cond.getNode()->getOperand(1);
13409 CondOpcode = Cond.getOpcode();
13410 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13411 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13412 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13413 Cond.getOperand(0).getValueType() != MVT::i8)) {
13414 SDValue LHS = Cond.getOperand(0);
13415 SDValue RHS = Cond.getOperand(1);
13416 unsigned X86Opcode;
13419 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13420 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13422 switch (CondOpcode) {
13423 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13425 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13427 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13430 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13431 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13435 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13438 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13439 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13440 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13441 default: llvm_unreachable("unexpected overflowing operator");
13444 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13445 if (CondOpcode == ISD::UMULO)
13446 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13449 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13451 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13453 if (CondOpcode == ISD::UMULO)
13454 Cond = X86Op.getValue(2);
13456 Cond = X86Op.getValue(1);
13458 CC = DAG.getConstant(X86Cond, MVT::i8);
13462 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13463 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13464 if (CondOpc == ISD::OR) {
13465 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13466 // two branches instead of an explicit OR instruction with a
13468 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13469 isX86LogicalCmp(Cmp)) {
13470 CC = Cond.getOperand(0).getOperand(0);
13471 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13472 Chain, Dest, CC, Cmp);
13473 CC = Cond.getOperand(1).getOperand(0);
13477 } else { // ISD::AND
13478 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13479 // two branches instead of an explicit AND instruction with a
13480 // separate test. However, we only do this if this block doesn't
13481 // have a fall-through edge, because this requires an explicit
13482 // jmp when the condition is false.
13483 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13484 isX86LogicalCmp(Cmp) &&
13485 Op.getNode()->hasOneUse()) {
13486 X86::CondCode CCode =
13487 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13488 CCode = X86::GetOppositeBranchCondition(CCode);
13489 CC = DAG.getConstant(CCode, MVT::i8);
13490 SDNode *User = *Op.getNode()->use_begin();
13491 // Look for an unconditional branch following this conditional branch.
13492 // We need this because we need to reverse the successors in order
13493 // to implement FCMP_OEQ.
13494 if (User->getOpcode() == ISD::BR) {
13495 SDValue FalseBB = User->getOperand(1);
13497 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13498 assert(NewBR == User);
13502 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13503 Chain, Dest, CC, Cmp);
13504 X86::CondCode CCode =
13505 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13506 CCode = X86::GetOppositeBranchCondition(CCode);
13507 CC = DAG.getConstant(CCode, MVT::i8);
13513 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13514 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13515 // It should be transformed during dag combiner except when the condition
13516 // is set by a arithmetics with overflow node.
13517 X86::CondCode CCode =
13518 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13519 CCode = X86::GetOppositeBranchCondition(CCode);
13520 CC = DAG.getConstant(CCode, MVT::i8);
13521 Cond = Cond.getOperand(0).getOperand(1);
13523 } else if (Cond.getOpcode() == ISD::SETCC &&
13524 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13525 // For FCMP_OEQ, we can emit
13526 // two branches instead of an explicit AND instruction with a
13527 // separate test. However, we only do this if this block doesn't
13528 // have a fall-through edge, because this requires an explicit
13529 // jmp when the condition is false.
13530 if (Op.getNode()->hasOneUse()) {
13531 SDNode *User = *Op.getNode()->use_begin();
13532 // Look for an unconditional branch following this conditional branch.
13533 // We need this because we need to reverse the successors in order
13534 // to implement FCMP_OEQ.
13535 if (User->getOpcode() == ISD::BR) {
13536 SDValue FalseBB = User->getOperand(1);
13538 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13539 assert(NewBR == User);
13543 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13544 Cond.getOperand(0), Cond.getOperand(1));
13545 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13546 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13547 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13548 Chain, Dest, CC, Cmp);
13549 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13554 } else if (Cond.getOpcode() == ISD::SETCC &&
13555 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13556 // For FCMP_UNE, we can emit
13557 // two branches instead of an explicit AND instruction with a
13558 // separate test. However, we only do this if this block doesn't
13559 // have a fall-through edge, because this requires an explicit
13560 // jmp when the condition is false.
13561 if (Op.getNode()->hasOneUse()) {
13562 SDNode *User = *Op.getNode()->use_begin();
13563 // Look for an unconditional branch following this conditional branch.
13564 // We need this because we need to reverse the successors in order
13565 // to implement FCMP_UNE.
13566 if (User->getOpcode() == ISD::BR) {
13567 SDValue FalseBB = User->getOperand(1);
13569 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13570 assert(NewBR == User);
13573 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13574 Cond.getOperand(0), Cond.getOperand(1));
13575 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13576 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13577 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13578 Chain, Dest, CC, Cmp);
13579 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13589 // Look pass the truncate if the high bits are known zero.
13590 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13591 Cond = Cond.getOperand(0);
13593 // We know the result of AND is compared against zero. Try to match
13595 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13596 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13597 if (NewSetCC.getNode()) {
13598 CC = NewSetCC.getOperand(0);
13599 Cond = NewSetCC.getOperand(1);
13606 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13607 CC = DAG.getConstant(X86Cond, MVT::i8);
13608 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13610 Cond = ConvertCmpIfNecessary(Cond, DAG);
13611 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13612 Chain, Dest, CC, Cond);
13615 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13616 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13617 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13618 // that the guard pages used by the OS virtual memory manager are allocated in
13619 // correct sequence.
13621 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13622 SelectionDAG &DAG) const {
13623 MachineFunction &MF = DAG.getMachineFunction();
13624 bool SplitStack = MF.shouldSplitStack();
13625 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13631 SDNode* Node = Op.getNode();
13633 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13634 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13635 " not tell us which reg is the stack pointer!");
13636 EVT VT = Node->getValueType(0);
13637 SDValue Tmp1 = SDValue(Node, 0);
13638 SDValue Tmp2 = SDValue(Node, 1);
13639 SDValue Tmp3 = Node->getOperand(2);
13640 SDValue Chain = Tmp1.getOperand(0);
13642 // Chain the dynamic stack allocation so that it doesn't modify the stack
13643 // pointer when other instructions are using the stack.
13644 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13647 SDValue Size = Tmp2.getOperand(1);
13648 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13649 Chain = SP.getValue(1);
13650 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13651 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
13652 unsigned StackAlign = TFI.getStackAlignment();
13653 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13654 if (Align > StackAlign)
13655 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13656 DAG.getConstant(-(uint64_t)Align, VT));
13657 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13659 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13660 DAG.getIntPtrConstant(0, true), SDValue(),
13663 SDValue Ops[2] = { Tmp1, Tmp2 };
13664 return DAG.getMergeValues(Ops, dl);
13668 SDValue Chain = Op.getOperand(0);
13669 SDValue Size = Op.getOperand(1);
13670 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13671 EVT VT = Op.getNode()->getValueType(0);
13673 bool Is64Bit = Subtarget->is64Bit();
13674 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13677 MachineRegisterInfo &MRI = MF.getRegInfo();
13680 // The 64 bit implementation of segmented stacks needs to clobber both r10
13681 // r11. This makes it impossible to use it along with nested parameters.
13682 const Function *F = MF.getFunction();
13684 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13686 if (I->hasNestAttr())
13687 report_fatal_error("Cannot use segmented stacks with functions that "
13688 "have nested arguments.");
13691 const TargetRegisterClass *AddrRegClass =
13692 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13693 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13694 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13695 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13696 DAG.getRegister(Vreg, SPTy));
13697 SDValue Ops1[2] = { Value, Chain };
13698 return DAG.getMergeValues(Ops1, dl);
13701 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13703 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13704 Flag = Chain.getValue(1);
13705 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13707 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13709 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
13710 DAG.getSubtarget().getRegisterInfo());
13711 unsigned SPReg = RegInfo->getStackRegister();
13712 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13713 Chain = SP.getValue(1);
13716 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13717 DAG.getConstant(-(uint64_t)Align, VT));
13718 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13721 SDValue Ops1[2] = { SP, Chain };
13722 return DAG.getMergeValues(Ops1, dl);
13726 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13727 MachineFunction &MF = DAG.getMachineFunction();
13728 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13730 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13733 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13734 // vastart just stores the address of the VarArgsFrameIndex slot into the
13735 // memory location argument.
13736 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13738 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13739 MachinePointerInfo(SV), false, false, 0);
13743 // gp_offset (0 - 6 * 8)
13744 // fp_offset (48 - 48 + 8 * 16)
13745 // overflow_arg_area (point to parameters coming in memory).
13747 SmallVector<SDValue, 8> MemOps;
13748 SDValue FIN = Op.getOperand(1);
13750 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13751 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13753 FIN, MachinePointerInfo(SV), false, false, 0);
13754 MemOps.push_back(Store);
13757 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13758 FIN, DAG.getIntPtrConstant(4));
13759 Store = DAG.getStore(Op.getOperand(0), DL,
13760 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13762 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13763 MemOps.push_back(Store);
13765 // Store ptr to overflow_arg_area
13766 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13767 FIN, DAG.getIntPtrConstant(4));
13768 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13770 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13771 MachinePointerInfo(SV, 8),
13773 MemOps.push_back(Store);
13775 // Store ptr to reg_save_area.
13776 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13777 FIN, DAG.getIntPtrConstant(8));
13778 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13780 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13781 MachinePointerInfo(SV, 16), false, false, 0);
13782 MemOps.push_back(Store);
13783 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13786 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13787 assert(Subtarget->is64Bit() &&
13788 "LowerVAARG only handles 64-bit va_arg!");
13789 assert((Subtarget->isTargetLinux() ||
13790 Subtarget->isTargetDarwin()) &&
13791 "Unhandled target in LowerVAARG");
13792 assert(Op.getNode()->getNumOperands() == 4);
13793 SDValue Chain = Op.getOperand(0);
13794 SDValue SrcPtr = Op.getOperand(1);
13795 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13796 unsigned Align = Op.getConstantOperandVal(3);
13799 EVT ArgVT = Op.getNode()->getValueType(0);
13800 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13801 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13804 // Decide which area this value should be read from.
13805 // TODO: Implement the AMD64 ABI in its entirety. This simple
13806 // selection mechanism works only for the basic types.
13807 if (ArgVT == MVT::f80) {
13808 llvm_unreachable("va_arg for f80 not yet implemented");
13809 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13810 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13811 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13812 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13814 llvm_unreachable("Unhandled argument type in LowerVAARG");
13817 if (ArgMode == 2) {
13818 // Sanity Check: Make sure using fp_offset makes sense.
13819 assert(!DAG.getTarget().Options.UseSoftFloat &&
13820 !(DAG.getMachineFunction()
13821 .getFunction()->getAttributes()
13822 .hasAttribute(AttributeSet::FunctionIndex,
13823 Attribute::NoImplicitFloat)) &&
13824 Subtarget->hasSSE1());
13827 // Insert VAARG_64 node into the DAG
13828 // VAARG_64 returns two values: Variable Argument Address, Chain
13829 SmallVector<SDValue, 11> InstOps;
13830 InstOps.push_back(Chain);
13831 InstOps.push_back(SrcPtr);
13832 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13833 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13834 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13835 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13836 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13837 VTs, InstOps, MVT::i64,
13838 MachinePointerInfo(SV),
13840 /*Volatile=*/false,
13842 /*WriteMem=*/true);
13843 Chain = VAARG.getValue(1);
13845 // Load the next argument and return it
13846 return DAG.getLoad(ArgVT, dl,
13849 MachinePointerInfo(),
13850 false, false, false, 0);
13853 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13854 SelectionDAG &DAG) {
13855 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13856 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13857 SDValue Chain = Op.getOperand(0);
13858 SDValue DstPtr = Op.getOperand(1);
13859 SDValue SrcPtr = Op.getOperand(2);
13860 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13861 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13864 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13865 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13867 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13870 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13871 // amount is a constant. Takes immediate version of shift as input.
13872 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13873 SDValue SrcOp, uint64_t ShiftAmt,
13874 SelectionDAG &DAG) {
13875 MVT ElementType = VT.getVectorElementType();
13877 // Fold this packed shift into its first operand if ShiftAmt is 0.
13881 // Check for ShiftAmt >= element width
13882 if (ShiftAmt >= ElementType.getSizeInBits()) {
13883 if (Opc == X86ISD::VSRAI)
13884 ShiftAmt = ElementType.getSizeInBits() - 1;
13886 return DAG.getConstant(0, VT);
13889 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13890 && "Unknown target vector shift-by-constant node");
13892 // Fold this packed vector shift into a build vector if SrcOp is a
13893 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13894 if (VT == SrcOp.getSimpleValueType() &&
13895 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13896 SmallVector<SDValue, 8> Elts;
13897 unsigned NumElts = SrcOp->getNumOperands();
13898 ConstantSDNode *ND;
13901 default: llvm_unreachable(nullptr);
13902 case X86ISD::VSHLI:
13903 for (unsigned i=0; i!=NumElts; ++i) {
13904 SDValue CurrentOp = SrcOp->getOperand(i);
13905 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13906 Elts.push_back(CurrentOp);
13909 ND = cast<ConstantSDNode>(CurrentOp);
13910 const APInt &C = ND->getAPIntValue();
13911 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13914 case X86ISD::VSRLI:
13915 for (unsigned i=0; i!=NumElts; ++i) {
13916 SDValue CurrentOp = SrcOp->getOperand(i);
13917 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13918 Elts.push_back(CurrentOp);
13921 ND = cast<ConstantSDNode>(CurrentOp);
13922 const APInt &C = ND->getAPIntValue();
13923 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13926 case X86ISD::VSRAI:
13927 for (unsigned i=0; i!=NumElts; ++i) {
13928 SDValue CurrentOp = SrcOp->getOperand(i);
13929 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13930 Elts.push_back(CurrentOp);
13933 ND = cast<ConstantSDNode>(CurrentOp);
13934 const APInt &C = ND->getAPIntValue();
13935 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13940 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13943 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13946 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13947 // may or may not be a constant. Takes immediate version of shift as input.
13948 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13949 SDValue SrcOp, SDValue ShAmt,
13950 SelectionDAG &DAG) {
13951 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13953 // Catch shift-by-constant.
13954 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13955 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13956 CShAmt->getZExtValue(), DAG);
13958 // Change opcode to non-immediate version
13960 default: llvm_unreachable("Unknown target vector shift node");
13961 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13962 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13963 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13966 // Need to build a vector containing shift amount
13967 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13970 ShOps[1] = DAG.getConstant(0, MVT::i32);
13971 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13972 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13974 // The return type has to be a 128-bit type with the same element
13975 // type as the input type.
13976 MVT EltVT = VT.getVectorElementType();
13977 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13979 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13980 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13983 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13985 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13987 default: return SDValue(); // Don't custom lower most intrinsics.
13988 // Comparison intrinsics.
13989 case Intrinsic::x86_sse_comieq_ss:
13990 case Intrinsic::x86_sse_comilt_ss:
13991 case Intrinsic::x86_sse_comile_ss:
13992 case Intrinsic::x86_sse_comigt_ss:
13993 case Intrinsic::x86_sse_comige_ss:
13994 case Intrinsic::x86_sse_comineq_ss:
13995 case Intrinsic::x86_sse_ucomieq_ss:
13996 case Intrinsic::x86_sse_ucomilt_ss:
13997 case Intrinsic::x86_sse_ucomile_ss:
13998 case Intrinsic::x86_sse_ucomigt_ss:
13999 case Intrinsic::x86_sse_ucomige_ss:
14000 case Intrinsic::x86_sse_ucomineq_ss:
14001 case Intrinsic::x86_sse2_comieq_sd:
14002 case Intrinsic::x86_sse2_comilt_sd:
14003 case Intrinsic::x86_sse2_comile_sd:
14004 case Intrinsic::x86_sse2_comigt_sd:
14005 case Intrinsic::x86_sse2_comige_sd:
14006 case Intrinsic::x86_sse2_comineq_sd:
14007 case Intrinsic::x86_sse2_ucomieq_sd:
14008 case Intrinsic::x86_sse2_ucomilt_sd:
14009 case Intrinsic::x86_sse2_ucomile_sd:
14010 case Intrinsic::x86_sse2_ucomigt_sd:
14011 case Intrinsic::x86_sse2_ucomige_sd:
14012 case Intrinsic::x86_sse2_ucomineq_sd: {
14016 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14017 case Intrinsic::x86_sse_comieq_ss:
14018 case Intrinsic::x86_sse2_comieq_sd:
14019 Opc = X86ISD::COMI;
14022 case Intrinsic::x86_sse_comilt_ss:
14023 case Intrinsic::x86_sse2_comilt_sd:
14024 Opc = X86ISD::COMI;
14027 case Intrinsic::x86_sse_comile_ss:
14028 case Intrinsic::x86_sse2_comile_sd:
14029 Opc = X86ISD::COMI;
14032 case Intrinsic::x86_sse_comigt_ss:
14033 case Intrinsic::x86_sse2_comigt_sd:
14034 Opc = X86ISD::COMI;
14037 case Intrinsic::x86_sse_comige_ss:
14038 case Intrinsic::x86_sse2_comige_sd:
14039 Opc = X86ISD::COMI;
14042 case Intrinsic::x86_sse_comineq_ss:
14043 case Intrinsic::x86_sse2_comineq_sd:
14044 Opc = X86ISD::COMI;
14047 case Intrinsic::x86_sse_ucomieq_ss:
14048 case Intrinsic::x86_sse2_ucomieq_sd:
14049 Opc = X86ISD::UCOMI;
14052 case Intrinsic::x86_sse_ucomilt_ss:
14053 case Intrinsic::x86_sse2_ucomilt_sd:
14054 Opc = X86ISD::UCOMI;
14057 case Intrinsic::x86_sse_ucomile_ss:
14058 case Intrinsic::x86_sse2_ucomile_sd:
14059 Opc = X86ISD::UCOMI;
14062 case Intrinsic::x86_sse_ucomigt_ss:
14063 case Intrinsic::x86_sse2_ucomigt_sd:
14064 Opc = X86ISD::UCOMI;
14067 case Intrinsic::x86_sse_ucomige_ss:
14068 case Intrinsic::x86_sse2_ucomige_sd:
14069 Opc = X86ISD::UCOMI;
14072 case Intrinsic::x86_sse_ucomineq_ss:
14073 case Intrinsic::x86_sse2_ucomineq_sd:
14074 Opc = X86ISD::UCOMI;
14079 SDValue LHS = Op.getOperand(1);
14080 SDValue RHS = Op.getOperand(2);
14081 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14082 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14083 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14084 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14085 DAG.getConstant(X86CC, MVT::i8), Cond);
14086 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14089 // Arithmetic intrinsics.
14090 case Intrinsic::x86_sse2_pmulu_dq:
14091 case Intrinsic::x86_avx2_pmulu_dq:
14092 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14093 Op.getOperand(1), Op.getOperand(2));
14095 case Intrinsic::x86_sse41_pmuldq:
14096 case Intrinsic::x86_avx2_pmul_dq:
14097 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14098 Op.getOperand(1), Op.getOperand(2));
14100 case Intrinsic::x86_sse2_pmulhu_w:
14101 case Intrinsic::x86_avx2_pmulhu_w:
14102 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14103 Op.getOperand(1), Op.getOperand(2));
14105 case Intrinsic::x86_sse2_pmulh_w:
14106 case Intrinsic::x86_avx2_pmulh_w:
14107 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14108 Op.getOperand(1), Op.getOperand(2));
14110 // SSE2/AVX2 sub with unsigned saturation intrinsics
14111 case Intrinsic::x86_sse2_psubus_b:
14112 case Intrinsic::x86_sse2_psubus_w:
14113 case Intrinsic::x86_avx2_psubus_b:
14114 case Intrinsic::x86_avx2_psubus_w:
14115 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14116 Op.getOperand(1), Op.getOperand(2));
14118 // SSE3/AVX horizontal add/sub intrinsics
14119 case Intrinsic::x86_sse3_hadd_ps:
14120 case Intrinsic::x86_sse3_hadd_pd:
14121 case Intrinsic::x86_avx_hadd_ps_256:
14122 case Intrinsic::x86_avx_hadd_pd_256:
14123 case Intrinsic::x86_sse3_hsub_ps:
14124 case Intrinsic::x86_sse3_hsub_pd:
14125 case Intrinsic::x86_avx_hsub_ps_256:
14126 case Intrinsic::x86_avx_hsub_pd_256:
14127 case Intrinsic::x86_ssse3_phadd_w_128:
14128 case Intrinsic::x86_ssse3_phadd_d_128:
14129 case Intrinsic::x86_avx2_phadd_w:
14130 case Intrinsic::x86_avx2_phadd_d:
14131 case Intrinsic::x86_ssse3_phsub_w_128:
14132 case Intrinsic::x86_ssse3_phsub_d_128:
14133 case Intrinsic::x86_avx2_phsub_w:
14134 case Intrinsic::x86_avx2_phsub_d: {
14137 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14138 case Intrinsic::x86_sse3_hadd_ps:
14139 case Intrinsic::x86_sse3_hadd_pd:
14140 case Intrinsic::x86_avx_hadd_ps_256:
14141 case Intrinsic::x86_avx_hadd_pd_256:
14142 Opcode = X86ISD::FHADD;
14144 case Intrinsic::x86_sse3_hsub_ps:
14145 case Intrinsic::x86_sse3_hsub_pd:
14146 case Intrinsic::x86_avx_hsub_ps_256:
14147 case Intrinsic::x86_avx_hsub_pd_256:
14148 Opcode = X86ISD::FHSUB;
14150 case Intrinsic::x86_ssse3_phadd_w_128:
14151 case Intrinsic::x86_ssse3_phadd_d_128:
14152 case Intrinsic::x86_avx2_phadd_w:
14153 case Intrinsic::x86_avx2_phadd_d:
14154 Opcode = X86ISD::HADD;
14156 case Intrinsic::x86_ssse3_phsub_w_128:
14157 case Intrinsic::x86_ssse3_phsub_d_128:
14158 case Intrinsic::x86_avx2_phsub_w:
14159 case Intrinsic::x86_avx2_phsub_d:
14160 Opcode = X86ISD::HSUB;
14163 return DAG.getNode(Opcode, dl, Op.getValueType(),
14164 Op.getOperand(1), Op.getOperand(2));
14167 // SSE2/SSE41/AVX2 integer max/min intrinsics.
14168 case Intrinsic::x86_sse2_pmaxu_b:
14169 case Intrinsic::x86_sse41_pmaxuw:
14170 case Intrinsic::x86_sse41_pmaxud:
14171 case Intrinsic::x86_avx2_pmaxu_b:
14172 case Intrinsic::x86_avx2_pmaxu_w:
14173 case Intrinsic::x86_avx2_pmaxu_d:
14174 case Intrinsic::x86_sse2_pminu_b:
14175 case Intrinsic::x86_sse41_pminuw:
14176 case Intrinsic::x86_sse41_pminud:
14177 case Intrinsic::x86_avx2_pminu_b:
14178 case Intrinsic::x86_avx2_pminu_w:
14179 case Intrinsic::x86_avx2_pminu_d:
14180 case Intrinsic::x86_sse41_pmaxsb:
14181 case Intrinsic::x86_sse2_pmaxs_w:
14182 case Intrinsic::x86_sse41_pmaxsd:
14183 case Intrinsic::x86_avx2_pmaxs_b:
14184 case Intrinsic::x86_avx2_pmaxs_w:
14185 case Intrinsic::x86_avx2_pmaxs_d:
14186 case Intrinsic::x86_sse41_pminsb:
14187 case Intrinsic::x86_sse2_pmins_w:
14188 case Intrinsic::x86_sse41_pminsd:
14189 case Intrinsic::x86_avx2_pmins_b:
14190 case Intrinsic::x86_avx2_pmins_w:
14191 case Intrinsic::x86_avx2_pmins_d: {
14194 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14195 case Intrinsic::x86_sse2_pmaxu_b:
14196 case Intrinsic::x86_sse41_pmaxuw:
14197 case Intrinsic::x86_sse41_pmaxud:
14198 case Intrinsic::x86_avx2_pmaxu_b:
14199 case Intrinsic::x86_avx2_pmaxu_w:
14200 case Intrinsic::x86_avx2_pmaxu_d:
14201 Opcode = X86ISD::UMAX;
14203 case Intrinsic::x86_sse2_pminu_b:
14204 case Intrinsic::x86_sse41_pminuw:
14205 case Intrinsic::x86_sse41_pminud:
14206 case Intrinsic::x86_avx2_pminu_b:
14207 case Intrinsic::x86_avx2_pminu_w:
14208 case Intrinsic::x86_avx2_pminu_d:
14209 Opcode = X86ISD::UMIN;
14211 case Intrinsic::x86_sse41_pmaxsb:
14212 case Intrinsic::x86_sse2_pmaxs_w:
14213 case Intrinsic::x86_sse41_pmaxsd:
14214 case Intrinsic::x86_avx2_pmaxs_b:
14215 case Intrinsic::x86_avx2_pmaxs_w:
14216 case Intrinsic::x86_avx2_pmaxs_d:
14217 Opcode = X86ISD::SMAX;
14219 case Intrinsic::x86_sse41_pminsb:
14220 case Intrinsic::x86_sse2_pmins_w:
14221 case Intrinsic::x86_sse41_pminsd:
14222 case Intrinsic::x86_avx2_pmins_b:
14223 case Intrinsic::x86_avx2_pmins_w:
14224 case Intrinsic::x86_avx2_pmins_d:
14225 Opcode = X86ISD::SMIN;
14228 return DAG.getNode(Opcode, dl, Op.getValueType(),
14229 Op.getOperand(1), Op.getOperand(2));
14232 // SSE/SSE2/AVX floating point max/min intrinsics.
14233 case Intrinsic::x86_sse_max_ps:
14234 case Intrinsic::x86_sse2_max_pd:
14235 case Intrinsic::x86_avx_max_ps_256:
14236 case Intrinsic::x86_avx_max_pd_256:
14237 case Intrinsic::x86_sse_min_ps:
14238 case Intrinsic::x86_sse2_min_pd:
14239 case Intrinsic::x86_avx_min_ps_256:
14240 case Intrinsic::x86_avx_min_pd_256: {
14243 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14244 case Intrinsic::x86_sse_max_ps:
14245 case Intrinsic::x86_sse2_max_pd:
14246 case Intrinsic::x86_avx_max_ps_256:
14247 case Intrinsic::x86_avx_max_pd_256:
14248 Opcode = X86ISD::FMAX;
14250 case Intrinsic::x86_sse_min_ps:
14251 case Intrinsic::x86_sse2_min_pd:
14252 case Intrinsic::x86_avx_min_ps_256:
14253 case Intrinsic::x86_avx_min_pd_256:
14254 Opcode = X86ISD::FMIN;
14257 return DAG.getNode(Opcode, dl, Op.getValueType(),
14258 Op.getOperand(1), Op.getOperand(2));
14261 // AVX2 variable shift intrinsics
14262 case Intrinsic::x86_avx2_psllv_d:
14263 case Intrinsic::x86_avx2_psllv_q:
14264 case Intrinsic::x86_avx2_psllv_d_256:
14265 case Intrinsic::x86_avx2_psllv_q_256:
14266 case Intrinsic::x86_avx2_psrlv_d:
14267 case Intrinsic::x86_avx2_psrlv_q:
14268 case Intrinsic::x86_avx2_psrlv_d_256:
14269 case Intrinsic::x86_avx2_psrlv_q_256:
14270 case Intrinsic::x86_avx2_psrav_d:
14271 case Intrinsic::x86_avx2_psrav_d_256: {
14274 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14275 case Intrinsic::x86_avx2_psllv_d:
14276 case Intrinsic::x86_avx2_psllv_q:
14277 case Intrinsic::x86_avx2_psllv_d_256:
14278 case Intrinsic::x86_avx2_psllv_q_256:
14281 case Intrinsic::x86_avx2_psrlv_d:
14282 case Intrinsic::x86_avx2_psrlv_q:
14283 case Intrinsic::x86_avx2_psrlv_d_256:
14284 case Intrinsic::x86_avx2_psrlv_q_256:
14287 case Intrinsic::x86_avx2_psrav_d:
14288 case Intrinsic::x86_avx2_psrav_d_256:
14292 return DAG.getNode(Opcode, dl, Op.getValueType(),
14293 Op.getOperand(1), Op.getOperand(2));
14296 case Intrinsic::x86_sse2_packssdw_128:
14297 case Intrinsic::x86_sse2_packsswb_128:
14298 case Intrinsic::x86_avx2_packssdw:
14299 case Intrinsic::x86_avx2_packsswb:
14300 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14301 Op.getOperand(1), Op.getOperand(2));
14303 case Intrinsic::x86_sse2_packuswb_128:
14304 case Intrinsic::x86_sse41_packusdw:
14305 case Intrinsic::x86_avx2_packuswb:
14306 case Intrinsic::x86_avx2_packusdw:
14307 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14308 Op.getOperand(1), Op.getOperand(2));
14310 case Intrinsic::x86_ssse3_pshuf_b_128:
14311 case Intrinsic::x86_avx2_pshuf_b:
14312 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14313 Op.getOperand(1), Op.getOperand(2));
14315 case Intrinsic::x86_sse2_pshuf_d:
14316 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14317 Op.getOperand(1), Op.getOperand(2));
14319 case Intrinsic::x86_sse2_pshufl_w:
14320 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14321 Op.getOperand(1), Op.getOperand(2));
14323 case Intrinsic::x86_sse2_pshufh_w:
14324 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14325 Op.getOperand(1), Op.getOperand(2));
14327 case Intrinsic::x86_ssse3_psign_b_128:
14328 case Intrinsic::x86_ssse3_psign_w_128:
14329 case Intrinsic::x86_ssse3_psign_d_128:
14330 case Intrinsic::x86_avx2_psign_b:
14331 case Intrinsic::x86_avx2_psign_w:
14332 case Intrinsic::x86_avx2_psign_d:
14333 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14334 Op.getOperand(1), Op.getOperand(2));
14336 case Intrinsic::x86_sse41_insertps:
14337 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14338 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14340 case Intrinsic::x86_avx_vperm2f128_ps_256:
14341 case Intrinsic::x86_avx_vperm2f128_pd_256:
14342 case Intrinsic::x86_avx_vperm2f128_si_256:
14343 case Intrinsic::x86_avx2_vperm2i128:
14344 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14345 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14347 case Intrinsic::x86_avx2_permd:
14348 case Intrinsic::x86_avx2_permps:
14349 // Operands intentionally swapped. Mask is last operand to intrinsic,
14350 // but second operand for node/instruction.
14351 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14352 Op.getOperand(2), Op.getOperand(1));
14354 case Intrinsic::x86_sse_sqrt_ps:
14355 case Intrinsic::x86_sse2_sqrt_pd:
14356 case Intrinsic::x86_avx_sqrt_ps_256:
14357 case Intrinsic::x86_avx_sqrt_pd_256:
14358 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14360 // ptest and testp intrinsics. The intrinsic these come from are designed to
14361 // return an integer value, not just an instruction so lower it to the ptest
14362 // or testp pattern and a setcc for the result.
14363 case Intrinsic::x86_sse41_ptestz:
14364 case Intrinsic::x86_sse41_ptestc:
14365 case Intrinsic::x86_sse41_ptestnzc:
14366 case Intrinsic::x86_avx_ptestz_256:
14367 case Intrinsic::x86_avx_ptestc_256:
14368 case Intrinsic::x86_avx_ptestnzc_256:
14369 case Intrinsic::x86_avx_vtestz_ps:
14370 case Intrinsic::x86_avx_vtestc_ps:
14371 case Intrinsic::x86_avx_vtestnzc_ps:
14372 case Intrinsic::x86_avx_vtestz_pd:
14373 case Intrinsic::x86_avx_vtestc_pd:
14374 case Intrinsic::x86_avx_vtestnzc_pd:
14375 case Intrinsic::x86_avx_vtestz_ps_256:
14376 case Intrinsic::x86_avx_vtestc_ps_256:
14377 case Intrinsic::x86_avx_vtestnzc_ps_256:
14378 case Intrinsic::x86_avx_vtestz_pd_256:
14379 case Intrinsic::x86_avx_vtestc_pd_256:
14380 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14381 bool IsTestPacked = false;
14384 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14385 case Intrinsic::x86_avx_vtestz_ps:
14386 case Intrinsic::x86_avx_vtestz_pd:
14387 case Intrinsic::x86_avx_vtestz_ps_256:
14388 case Intrinsic::x86_avx_vtestz_pd_256:
14389 IsTestPacked = true; // Fallthrough
14390 case Intrinsic::x86_sse41_ptestz:
14391 case Intrinsic::x86_avx_ptestz_256:
14393 X86CC = X86::COND_E;
14395 case Intrinsic::x86_avx_vtestc_ps:
14396 case Intrinsic::x86_avx_vtestc_pd:
14397 case Intrinsic::x86_avx_vtestc_ps_256:
14398 case Intrinsic::x86_avx_vtestc_pd_256:
14399 IsTestPacked = true; // Fallthrough
14400 case Intrinsic::x86_sse41_ptestc:
14401 case Intrinsic::x86_avx_ptestc_256:
14403 X86CC = X86::COND_B;
14405 case Intrinsic::x86_avx_vtestnzc_ps:
14406 case Intrinsic::x86_avx_vtestnzc_pd:
14407 case Intrinsic::x86_avx_vtestnzc_ps_256:
14408 case Intrinsic::x86_avx_vtestnzc_pd_256:
14409 IsTestPacked = true; // Fallthrough
14410 case Intrinsic::x86_sse41_ptestnzc:
14411 case Intrinsic::x86_avx_ptestnzc_256:
14413 X86CC = X86::COND_A;
14417 SDValue LHS = Op.getOperand(1);
14418 SDValue RHS = Op.getOperand(2);
14419 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14420 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14421 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14422 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14423 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14425 case Intrinsic::x86_avx512_kortestz_w:
14426 case Intrinsic::x86_avx512_kortestc_w: {
14427 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14428 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14429 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14430 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14431 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14432 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14433 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14436 // SSE/AVX shift intrinsics
14437 case Intrinsic::x86_sse2_psll_w:
14438 case Intrinsic::x86_sse2_psll_d:
14439 case Intrinsic::x86_sse2_psll_q:
14440 case Intrinsic::x86_avx2_psll_w:
14441 case Intrinsic::x86_avx2_psll_d:
14442 case Intrinsic::x86_avx2_psll_q:
14443 case Intrinsic::x86_sse2_psrl_w:
14444 case Intrinsic::x86_sse2_psrl_d:
14445 case Intrinsic::x86_sse2_psrl_q:
14446 case Intrinsic::x86_avx2_psrl_w:
14447 case Intrinsic::x86_avx2_psrl_d:
14448 case Intrinsic::x86_avx2_psrl_q:
14449 case Intrinsic::x86_sse2_psra_w:
14450 case Intrinsic::x86_sse2_psra_d:
14451 case Intrinsic::x86_avx2_psra_w:
14452 case Intrinsic::x86_avx2_psra_d: {
14455 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14456 case Intrinsic::x86_sse2_psll_w:
14457 case Intrinsic::x86_sse2_psll_d:
14458 case Intrinsic::x86_sse2_psll_q:
14459 case Intrinsic::x86_avx2_psll_w:
14460 case Intrinsic::x86_avx2_psll_d:
14461 case Intrinsic::x86_avx2_psll_q:
14462 Opcode = X86ISD::VSHL;
14464 case Intrinsic::x86_sse2_psrl_w:
14465 case Intrinsic::x86_sse2_psrl_d:
14466 case Intrinsic::x86_sse2_psrl_q:
14467 case Intrinsic::x86_avx2_psrl_w:
14468 case Intrinsic::x86_avx2_psrl_d:
14469 case Intrinsic::x86_avx2_psrl_q:
14470 Opcode = X86ISD::VSRL;
14472 case Intrinsic::x86_sse2_psra_w:
14473 case Intrinsic::x86_sse2_psra_d:
14474 case Intrinsic::x86_avx2_psra_w:
14475 case Intrinsic::x86_avx2_psra_d:
14476 Opcode = X86ISD::VSRA;
14479 return DAG.getNode(Opcode, dl, Op.getValueType(),
14480 Op.getOperand(1), Op.getOperand(2));
14483 // SSE/AVX immediate shift intrinsics
14484 case Intrinsic::x86_sse2_pslli_w:
14485 case Intrinsic::x86_sse2_pslli_d:
14486 case Intrinsic::x86_sse2_pslli_q:
14487 case Intrinsic::x86_avx2_pslli_w:
14488 case Intrinsic::x86_avx2_pslli_d:
14489 case Intrinsic::x86_avx2_pslli_q:
14490 case Intrinsic::x86_sse2_psrli_w:
14491 case Intrinsic::x86_sse2_psrli_d:
14492 case Intrinsic::x86_sse2_psrli_q:
14493 case Intrinsic::x86_avx2_psrli_w:
14494 case Intrinsic::x86_avx2_psrli_d:
14495 case Intrinsic::x86_avx2_psrli_q:
14496 case Intrinsic::x86_sse2_psrai_w:
14497 case Intrinsic::x86_sse2_psrai_d:
14498 case Intrinsic::x86_avx2_psrai_w:
14499 case Intrinsic::x86_avx2_psrai_d: {
14502 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14503 case Intrinsic::x86_sse2_pslli_w:
14504 case Intrinsic::x86_sse2_pslli_d:
14505 case Intrinsic::x86_sse2_pslli_q:
14506 case Intrinsic::x86_avx2_pslli_w:
14507 case Intrinsic::x86_avx2_pslli_d:
14508 case Intrinsic::x86_avx2_pslli_q:
14509 Opcode = X86ISD::VSHLI;
14511 case Intrinsic::x86_sse2_psrli_w:
14512 case Intrinsic::x86_sse2_psrli_d:
14513 case Intrinsic::x86_sse2_psrli_q:
14514 case Intrinsic::x86_avx2_psrli_w:
14515 case Intrinsic::x86_avx2_psrli_d:
14516 case Intrinsic::x86_avx2_psrli_q:
14517 Opcode = X86ISD::VSRLI;
14519 case Intrinsic::x86_sse2_psrai_w:
14520 case Intrinsic::x86_sse2_psrai_d:
14521 case Intrinsic::x86_avx2_psrai_w:
14522 case Intrinsic::x86_avx2_psrai_d:
14523 Opcode = X86ISD::VSRAI;
14526 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14527 Op.getOperand(1), Op.getOperand(2), DAG);
14530 case Intrinsic::x86_sse42_pcmpistria128:
14531 case Intrinsic::x86_sse42_pcmpestria128:
14532 case Intrinsic::x86_sse42_pcmpistric128:
14533 case Intrinsic::x86_sse42_pcmpestric128:
14534 case Intrinsic::x86_sse42_pcmpistrio128:
14535 case Intrinsic::x86_sse42_pcmpestrio128:
14536 case Intrinsic::x86_sse42_pcmpistris128:
14537 case Intrinsic::x86_sse42_pcmpestris128:
14538 case Intrinsic::x86_sse42_pcmpistriz128:
14539 case Intrinsic::x86_sse42_pcmpestriz128: {
14543 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14544 case Intrinsic::x86_sse42_pcmpistria128:
14545 Opcode = X86ISD::PCMPISTRI;
14546 X86CC = X86::COND_A;
14548 case Intrinsic::x86_sse42_pcmpestria128:
14549 Opcode = X86ISD::PCMPESTRI;
14550 X86CC = X86::COND_A;
14552 case Intrinsic::x86_sse42_pcmpistric128:
14553 Opcode = X86ISD::PCMPISTRI;
14554 X86CC = X86::COND_B;
14556 case Intrinsic::x86_sse42_pcmpestric128:
14557 Opcode = X86ISD::PCMPESTRI;
14558 X86CC = X86::COND_B;
14560 case Intrinsic::x86_sse42_pcmpistrio128:
14561 Opcode = X86ISD::PCMPISTRI;
14562 X86CC = X86::COND_O;
14564 case Intrinsic::x86_sse42_pcmpestrio128:
14565 Opcode = X86ISD::PCMPESTRI;
14566 X86CC = X86::COND_O;
14568 case Intrinsic::x86_sse42_pcmpistris128:
14569 Opcode = X86ISD::PCMPISTRI;
14570 X86CC = X86::COND_S;
14572 case Intrinsic::x86_sse42_pcmpestris128:
14573 Opcode = X86ISD::PCMPESTRI;
14574 X86CC = X86::COND_S;
14576 case Intrinsic::x86_sse42_pcmpistriz128:
14577 Opcode = X86ISD::PCMPISTRI;
14578 X86CC = X86::COND_E;
14580 case Intrinsic::x86_sse42_pcmpestriz128:
14581 Opcode = X86ISD::PCMPESTRI;
14582 X86CC = X86::COND_E;
14585 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14586 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14587 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14588 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14589 DAG.getConstant(X86CC, MVT::i8),
14590 SDValue(PCMP.getNode(), 1));
14591 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14594 case Intrinsic::x86_sse42_pcmpistri128:
14595 case Intrinsic::x86_sse42_pcmpestri128: {
14597 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14598 Opcode = X86ISD::PCMPISTRI;
14600 Opcode = X86ISD::PCMPESTRI;
14602 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14603 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14604 return DAG.getNode(Opcode, dl, VTs, NewOps);
14606 case Intrinsic::x86_fma_vfmadd_ps:
14607 case Intrinsic::x86_fma_vfmadd_pd:
14608 case Intrinsic::x86_fma_vfmsub_ps:
14609 case Intrinsic::x86_fma_vfmsub_pd:
14610 case Intrinsic::x86_fma_vfnmadd_ps:
14611 case Intrinsic::x86_fma_vfnmadd_pd:
14612 case Intrinsic::x86_fma_vfnmsub_ps:
14613 case Intrinsic::x86_fma_vfnmsub_pd:
14614 case Intrinsic::x86_fma_vfmaddsub_ps:
14615 case Intrinsic::x86_fma_vfmaddsub_pd:
14616 case Intrinsic::x86_fma_vfmsubadd_ps:
14617 case Intrinsic::x86_fma_vfmsubadd_pd:
14618 case Intrinsic::x86_fma_vfmadd_ps_256:
14619 case Intrinsic::x86_fma_vfmadd_pd_256:
14620 case Intrinsic::x86_fma_vfmsub_ps_256:
14621 case Intrinsic::x86_fma_vfmsub_pd_256:
14622 case Intrinsic::x86_fma_vfnmadd_ps_256:
14623 case Intrinsic::x86_fma_vfnmadd_pd_256:
14624 case Intrinsic::x86_fma_vfnmsub_ps_256:
14625 case Intrinsic::x86_fma_vfnmsub_pd_256:
14626 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14627 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14628 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14629 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14630 case Intrinsic::x86_fma_vfmadd_ps_512:
14631 case Intrinsic::x86_fma_vfmadd_pd_512:
14632 case Intrinsic::x86_fma_vfmsub_ps_512:
14633 case Intrinsic::x86_fma_vfmsub_pd_512:
14634 case Intrinsic::x86_fma_vfnmadd_ps_512:
14635 case Intrinsic::x86_fma_vfnmadd_pd_512:
14636 case Intrinsic::x86_fma_vfnmsub_ps_512:
14637 case Intrinsic::x86_fma_vfnmsub_pd_512:
14638 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14639 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14640 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14641 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14644 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14645 case Intrinsic::x86_fma_vfmadd_ps:
14646 case Intrinsic::x86_fma_vfmadd_pd:
14647 case Intrinsic::x86_fma_vfmadd_ps_256:
14648 case Intrinsic::x86_fma_vfmadd_pd_256:
14649 case Intrinsic::x86_fma_vfmadd_ps_512:
14650 case Intrinsic::x86_fma_vfmadd_pd_512:
14651 Opc = X86ISD::FMADD;
14653 case Intrinsic::x86_fma_vfmsub_ps:
14654 case Intrinsic::x86_fma_vfmsub_pd:
14655 case Intrinsic::x86_fma_vfmsub_ps_256:
14656 case Intrinsic::x86_fma_vfmsub_pd_256:
14657 case Intrinsic::x86_fma_vfmsub_ps_512:
14658 case Intrinsic::x86_fma_vfmsub_pd_512:
14659 Opc = X86ISD::FMSUB;
14661 case Intrinsic::x86_fma_vfnmadd_ps:
14662 case Intrinsic::x86_fma_vfnmadd_pd:
14663 case Intrinsic::x86_fma_vfnmadd_ps_256:
14664 case Intrinsic::x86_fma_vfnmadd_pd_256:
14665 case Intrinsic::x86_fma_vfnmadd_ps_512:
14666 case Intrinsic::x86_fma_vfnmadd_pd_512:
14667 Opc = X86ISD::FNMADD;
14669 case Intrinsic::x86_fma_vfnmsub_ps:
14670 case Intrinsic::x86_fma_vfnmsub_pd:
14671 case Intrinsic::x86_fma_vfnmsub_ps_256:
14672 case Intrinsic::x86_fma_vfnmsub_pd_256:
14673 case Intrinsic::x86_fma_vfnmsub_ps_512:
14674 case Intrinsic::x86_fma_vfnmsub_pd_512:
14675 Opc = X86ISD::FNMSUB;
14677 case Intrinsic::x86_fma_vfmaddsub_ps:
14678 case Intrinsic::x86_fma_vfmaddsub_pd:
14679 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14680 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14681 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14682 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14683 Opc = X86ISD::FMADDSUB;
14685 case Intrinsic::x86_fma_vfmsubadd_ps:
14686 case Intrinsic::x86_fma_vfmsubadd_pd:
14687 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14688 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14689 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14690 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14691 Opc = X86ISD::FMSUBADD;
14695 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14696 Op.getOperand(2), Op.getOperand(3));
14701 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14702 SDValue Src, SDValue Mask, SDValue Base,
14703 SDValue Index, SDValue ScaleOp, SDValue Chain,
14704 const X86Subtarget * Subtarget) {
14706 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14707 assert(C && "Invalid scale type");
14708 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14709 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14710 Index.getSimpleValueType().getVectorNumElements());
14712 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14714 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14716 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14717 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14718 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14719 SDValue Segment = DAG.getRegister(0, MVT::i32);
14720 if (Src.getOpcode() == ISD::UNDEF)
14721 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14722 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14723 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14724 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14725 return DAG.getMergeValues(RetOps, dl);
14728 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14729 SDValue Src, SDValue Mask, SDValue Base,
14730 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14732 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14733 assert(C && "Invalid scale type");
14734 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14735 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14736 SDValue Segment = DAG.getRegister(0, MVT::i32);
14737 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14738 Index.getSimpleValueType().getVectorNumElements());
14740 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14742 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14744 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14745 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14746 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14747 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14748 return SDValue(Res, 1);
14751 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14752 SDValue Mask, SDValue Base, SDValue Index,
14753 SDValue ScaleOp, SDValue Chain) {
14755 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14756 assert(C && "Invalid scale type");
14757 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14758 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14759 SDValue Segment = DAG.getRegister(0, MVT::i32);
14761 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14763 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14765 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14767 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14768 //SDVTList VTs = DAG.getVTList(MVT::Other);
14769 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14770 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14771 return SDValue(Res, 0);
14774 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14775 // read performance monitor counters (x86_rdpmc).
14776 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14777 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14778 SmallVectorImpl<SDValue> &Results) {
14779 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14780 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14783 // The ECX register is used to select the index of the performance counter
14785 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14787 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14789 // Reads the content of a 64-bit performance counter and returns it in the
14790 // registers EDX:EAX.
14791 if (Subtarget->is64Bit()) {
14792 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14793 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14796 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14797 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14800 Chain = HI.getValue(1);
14802 if (Subtarget->is64Bit()) {
14803 // The EAX register is loaded with the low-order 32 bits. The EDX register
14804 // is loaded with the supported high-order bits of the counter.
14805 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14806 DAG.getConstant(32, MVT::i8));
14807 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14808 Results.push_back(Chain);
14812 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14813 SDValue Ops[] = { LO, HI };
14814 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14815 Results.push_back(Pair);
14816 Results.push_back(Chain);
14819 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14820 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14821 // also used to custom lower READCYCLECOUNTER nodes.
14822 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14823 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14824 SmallVectorImpl<SDValue> &Results) {
14825 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14826 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14829 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14830 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14831 // and the EAX register is loaded with the low-order 32 bits.
14832 if (Subtarget->is64Bit()) {
14833 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14834 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14837 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14838 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14841 SDValue Chain = HI.getValue(1);
14843 if (Opcode == X86ISD::RDTSCP_DAG) {
14844 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14846 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14847 // the ECX register. Add 'ecx' explicitly to the chain.
14848 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14850 // Explicitly store the content of ECX at the location passed in input
14851 // to the 'rdtscp' intrinsic.
14852 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14853 MachinePointerInfo(), false, false, 0);
14856 if (Subtarget->is64Bit()) {
14857 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14858 // the EAX register is loaded with the low-order 32 bits.
14859 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14860 DAG.getConstant(32, MVT::i8));
14861 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14862 Results.push_back(Chain);
14866 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14867 SDValue Ops[] = { LO, HI };
14868 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14869 Results.push_back(Pair);
14870 Results.push_back(Chain);
14873 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14874 SelectionDAG &DAG) {
14875 SmallVector<SDValue, 2> Results;
14877 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14879 return DAG.getMergeValues(Results, DL);
14882 enum IntrinsicType {
14883 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14886 struct IntrinsicData {
14887 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14888 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14889 IntrinsicType Type;
14894 std::map < unsigned, IntrinsicData> IntrMap;
14895 static void InitIntinsicsMap() {
14896 static bool Initialized = false;
14899 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14900 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14901 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14902 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14903 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14904 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14905 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14906 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14907 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14908 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14909 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14910 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14911 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14912 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14913 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14914 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14915 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14916 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14918 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14919 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14920 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14921 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14922 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14923 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14924 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14925 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14926 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14927 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14928 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14929 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14930 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14931 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14932 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14933 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14935 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14936 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14937 X86::VGATHERPF1QPSm)));
14938 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14939 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14940 X86::VGATHERPF1QPDm)));
14941 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14942 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14943 X86::VGATHERPF1DPDm)));
14944 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14945 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14946 X86::VGATHERPF1DPSm)));
14947 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14948 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14949 X86::VSCATTERPF1QPSm)));
14950 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14951 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14952 X86::VSCATTERPF1QPDm)));
14953 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14954 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14955 X86::VSCATTERPF1DPDm)));
14956 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14957 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14958 X86::VSCATTERPF1DPSm)));
14959 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14960 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14961 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14962 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14963 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14964 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14965 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14966 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14967 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14968 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14969 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14970 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14971 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14972 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14973 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14974 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14975 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14976 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14977 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14978 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14979 Initialized = true;
14982 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14983 SelectionDAG &DAG) {
14984 InitIntinsicsMap();
14985 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14986 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14987 if (itr == IntrMap.end())
14991 IntrinsicData Intr = itr->second;
14992 switch(Intr.Type) {
14995 // Emit the node with the right value type.
14996 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14997 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14999 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15000 // Otherwise return the value from Rand, which is always 0, casted to i32.
15001 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15002 DAG.getConstant(1, Op->getValueType(1)),
15003 DAG.getConstant(X86::COND_B, MVT::i32),
15004 SDValue(Result.getNode(), 1) };
15005 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15006 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15009 // Return { result, isValid, chain }.
15010 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15011 SDValue(Result.getNode(), 2));
15014 //gather(v1, mask, index, base, scale);
15015 SDValue Chain = Op.getOperand(0);
15016 SDValue Src = Op.getOperand(2);
15017 SDValue Base = Op.getOperand(3);
15018 SDValue Index = Op.getOperand(4);
15019 SDValue Mask = Op.getOperand(5);
15020 SDValue Scale = Op.getOperand(6);
15021 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15025 //scatter(base, mask, index, v1, scale);
15026 SDValue Chain = Op.getOperand(0);
15027 SDValue Base = Op.getOperand(2);
15028 SDValue Mask = Op.getOperand(3);
15029 SDValue Index = Op.getOperand(4);
15030 SDValue Src = Op.getOperand(5);
15031 SDValue Scale = Op.getOperand(6);
15032 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15035 SDValue Hint = Op.getOperand(6);
15037 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15038 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15039 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15040 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15041 SDValue Chain = Op.getOperand(0);
15042 SDValue Mask = Op.getOperand(2);
15043 SDValue Index = Op.getOperand(3);
15044 SDValue Base = Op.getOperand(4);
15045 SDValue Scale = Op.getOperand(5);
15046 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15048 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15050 SmallVector<SDValue, 2> Results;
15051 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15052 return DAG.getMergeValues(Results, dl);
15054 // Read Performance Monitoring Counters.
15056 SmallVector<SDValue, 2> Results;
15057 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15058 return DAG.getMergeValues(Results, dl);
15060 // XTEST intrinsics.
15062 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15063 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15064 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15065 DAG.getConstant(X86::COND_NE, MVT::i8),
15067 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15068 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15069 Ret, SDValue(InTrans.getNode(), 1));
15072 llvm_unreachable("Unknown Intrinsic Type");
15075 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15076 SelectionDAG &DAG) const {
15077 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15078 MFI->setReturnAddressIsTaken(true);
15080 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15083 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15085 EVT PtrVT = getPointerTy();
15088 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15089 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15090 DAG.getSubtarget().getRegisterInfo());
15091 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15092 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15093 DAG.getNode(ISD::ADD, dl, PtrVT,
15094 FrameAddr, Offset),
15095 MachinePointerInfo(), false, false, false, 0);
15098 // Just load the return address.
15099 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15100 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15101 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15104 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15105 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15106 MFI->setFrameAddressIsTaken(true);
15108 EVT VT = Op.getValueType();
15109 SDLoc dl(Op); // FIXME probably not meaningful
15110 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15111 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15112 DAG.getSubtarget().getRegisterInfo());
15113 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15114 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15115 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15116 "Invalid Frame Register!");
15117 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15119 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15120 MachinePointerInfo(),
15121 false, false, false, 0);
15125 // FIXME? Maybe this could be a TableGen attribute on some registers and
15126 // this table could be generated automatically from RegInfo.
15127 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15129 unsigned Reg = StringSwitch<unsigned>(RegName)
15130 .Case("esp", X86::ESP)
15131 .Case("rsp", X86::RSP)
15135 report_fatal_error("Invalid register name global variable");
15138 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15139 SelectionDAG &DAG) const {
15140 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15141 DAG.getSubtarget().getRegisterInfo());
15142 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15145 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15146 SDValue Chain = Op.getOperand(0);
15147 SDValue Offset = Op.getOperand(1);
15148 SDValue Handler = Op.getOperand(2);
15151 EVT PtrVT = getPointerTy();
15152 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15153 DAG.getSubtarget().getRegisterInfo());
15154 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15155 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15156 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15157 "Invalid Frame Register!");
15158 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15159 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15161 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15162 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15163 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15164 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15166 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15168 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15169 DAG.getRegister(StoreAddrReg, PtrVT));
15172 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15173 SelectionDAG &DAG) const {
15175 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15176 DAG.getVTList(MVT::i32, MVT::Other),
15177 Op.getOperand(0), Op.getOperand(1));
15180 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15181 SelectionDAG &DAG) const {
15183 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15184 Op.getOperand(0), Op.getOperand(1));
15187 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15188 return Op.getOperand(0);
15191 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15192 SelectionDAG &DAG) const {
15193 SDValue Root = Op.getOperand(0);
15194 SDValue Trmp = Op.getOperand(1); // trampoline
15195 SDValue FPtr = Op.getOperand(2); // nested function
15196 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15199 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15200 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15202 if (Subtarget->is64Bit()) {
15203 SDValue OutChains[6];
15205 // Large code-model.
15206 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15207 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15209 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15210 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15212 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15214 // Load the pointer to the nested function into R11.
15215 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15216 SDValue Addr = Trmp;
15217 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15218 Addr, MachinePointerInfo(TrmpAddr),
15221 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15222 DAG.getConstant(2, MVT::i64));
15223 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15224 MachinePointerInfo(TrmpAddr, 2),
15227 // Load the 'nest' parameter value into R10.
15228 // R10 is specified in X86CallingConv.td
15229 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15230 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15231 DAG.getConstant(10, MVT::i64));
15232 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15233 Addr, MachinePointerInfo(TrmpAddr, 10),
15236 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15237 DAG.getConstant(12, MVT::i64));
15238 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15239 MachinePointerInfo(TrmpAddr, 12),
15242 // Jump to the nested function.
15243 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15244 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15245 DAG.getConstant(20, MVT::i64));
15246 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15247 Addr, MachinePointerInfo(TrmpAddr, 20),
15250 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15251 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15252 DAG.getConstant(22, MVT::i64));
15253 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15254 MachinePointerInfo(TrmpAddr, 22),
15257 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15259 const Function *Func =
15260 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15261 CallingConv::ID CC = Func->getCallingConv();
15266 llvm_unreachable("Unsupported calling convention");
15267 case CallingConv::C:
15268 case CallingConv::X86_StdCall: {
15269 // Pass 'nest' parameter in ECX.
15270 // Must be kept in sync with X86CallingConv.td
15271 NestReg = X86::ECX;
15273 // Check that ECX wasn't needed by an 'inreg' parameter.
15274 FunctionType *FTy = Func->getFunctionType();
15275 const AttributeSet &Attrs = Func->getAttributes();
15277 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15278 unsigned InRegCount = 0;
15281 for (FunctionType::param_iterator I = FTy->param_begin(),
15282 E = FTy->param_end(); I != E; ++I, ++Idx)
15283 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15284 // FIXME: should only count parameters that are lowered to integers.
15285 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15287 if (InRegCount > 2) {
15288 report_fatal_error("Nest register in use - reduce number of inreg"
15294 case CallingConv::X86_FastCall:
15295 case CallingConv::X86_ThisCall:
15296 case CallingConv::Fast:
15297 // Pass 'nest' parameter in EAX.
15298 // Must be kept in sync with X86CallingConv.td
15299 NestReg = X86::EAX;
15303 SDValue OutChains[4];
15304 SDValue Addr, Disp;
15306 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15307 DAG.getConstant(10, MVT::i32));
15308 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15310 // This is storing the opcode for MOV32ri.
15311 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15312 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15313 OutChains[0] = DAG.getStore(Root, dl,
15314 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15315 Trmp, MachinePointerInfo(TrmpAddr),
15318 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15319 DAG.getConstant(1, MVT::i32));
15320 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15321 MachinePointerInfo(TrmpAddr, 1),
15324 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15325 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15326 DAG.getConstant(5, MVT::i32));
15327 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15328 MachinePointerInfo(TrmpAddr, 5),
15331 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15332 DAG.getConstant(6, MVT::i32));
15333 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15334 MachinePointerInfo(TrmpAddr, 6),
15337 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15341 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15342 SelectionDAG &DAG) const {
15344 The rounding mode is in bits 11:10 of FPSR, and has the following
15346 00 Round to nearest
15351 FLT_ROUNDS, on the other hand, expects the following:
15358 To perform the conversion, we do:
15359 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15362 MachineFunction &MF = DAG.getMachineFunction();
15363 const TargetMachine &TM = MF.getTarget();
15364 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15365 unsigned StackAlignment = TFI.getStackAlignment();
15366 MVT VT = Op.getSimpleValueType();
15369 // Save FP Control Word to stack slot
15370 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15371 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15373 MachineMemOperand *MMO =
15374 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15375 MachineMemOperand::MOStore, 2, 2);
15377 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15378 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15379 DAG.getVTList(MVT::Other),
15380 Ops, MVT::i16, MMO);
15382 // Load FP Control Word from stack slot
15383 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15384 MachinePointerInfo(), false, false, false, 0);
15386 // Transform as necessary
15388 DAG.getNode(ISD::SRL, DL, MVT::i16,
15389 DAG.getNode(ISD::AND, DL, MVT::i16,
15390 CWD, DAG.getConstant(0x800, MVT::i16)),
15391 DAG.getConstant(11, MVT::i8));
15393 DAG.getNode(ISD::SRL, DL, MVT::i16,
15394 DAG.getNode(ISD::AND, DL, MVT::i16,
15395 CWD, DAG.getConstant(0x400, MVT::i16)),
15396 DAG.getConstant(9, MVT::i8));
15399 DAG.getNode(ISD::AND, DL, MVT::i16,
15400 DAG.getNode(ISD::ADD, DL, MVT::i16,
15401 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15402 DAG.getConstant(1, MVT::i16)),
15403 DAG.getConstant(3, MVT::i16));
15405 return DAG.getNode((VT.getSizeInBits() < 16 ?
15406 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15409 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15410 MVT VT = Op.getSimpleValueType();
15412 unsigned NumBits = VT.getSizeInBits();
15415 Op = Op.getOperand(0);
15416 if (VT == MVT::i8) {
15417 // Zero extend to i32 since there is not an i8 bsr.
15419 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15422 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15423 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15424 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15426 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15429 DAG.getConstant(NumBits+NumBits-1, OpVT),
15430 DAG.getConstant(X86::COND_E, MVT::i8),
15433 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15435 // Finally xor with NumBits-1.
15436 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15439 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15443 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15444 MVT VT = Op.getSimpleValueType();
15446 unsigned NumBits = VT.getSizeInBits();
15449 Op = Op.getOperand(0);
15450 if (VT == MVT::i8) {
15451 // Zero extend to i32 since there is not an i8 bsr.
15453 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15456 // Issue a bsr (scan bits in reverse).
15457 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15458 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15460 // And xor with NumBits-1.
15461 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15464 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15468 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15469 MVT VT = Op.getSimpleValueType();
15470 unsigned NumBits = VT.getSizeInBits();
15472 Op = Op.getOperand(0);
15474 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15475 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15476 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15478 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15481 DAG.getConstant(NumBits, VT),
15482 DAG.getConstant(X86::COND_E, MVT::i8),
15485 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15488 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15489 // ones, and then concatenate the result back.
15490 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15491 MVT VT = Op.getSimpleValueType();
15493 assert(VT.is256BitVector() && VT.isInteger() &&
15494 "Unsupported value type for operation");
15496 unsigned NumElems = VT.getVectorNumElements();
15499 // Extract the LHS vectors
15500 SDValue LHS = Op.getOperand(0);
15501 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15502 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15504 // Extract the RHS vectors
15505 SDValue RHS = Op.getOperand(1);
15506 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15507 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15509 MVT EltVT = VT.getVectorElementType();
15510 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15512 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15513 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15514 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15517 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15518 assert(Op.getSimpleValueType().is256BitVector() &&
15519 Op.getSimpleValueType().isInteger() &&
15520 "Only handle AVX 256-bit vector integer operation");
15521 return Lower256IntArith(Op, DAG);
15524 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15525 assert(Op.getSimpleValueType().is256BitVector() &&
15526 Op.getSimpleValueType().isInteger() &&
15527 "Only handle AVX 256-bit vector integer operation");
15528 return Lower256IntArith(Op, DAG);
15531 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15532 SelectionDAG &DAG) {
15534 MVT VT = Op.getSimpleValueType();
15536 // Decompose 256-bit ops into smaller 128-bit ops.
15537 if (VT.is256BitVector() && !Subtarget->hasInt256())
15538 return Lower256IntArith(Op, DAG);
15540 SDValue A = Op.getOperand(0);
15541 SDValue B = Op.getOperand(1);
15543 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15544 if (VT == MVT::v4i32) {
15545 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15546 "Should not custom lower when pmuldq is available!");
15548 // Extract the odd parts.
15549 static const int UnpackMask[] = { 1, -1, 3, -1 };
15550 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15551 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15553 // Multiply the even parts.
15554 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15555 // Now multiply odd parts.
15556 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15558 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15559 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15561 // Merge the two vectors back together with a shuffle. This expands into 2
15563 static const int ShufMask[] = { 0, 4, 2, 6 };
15564 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15567 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15568 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15570 // Ahi = psrlqi(a, 32);
15571 // Bhi = psrlqi(b, 32);
15573 // AloBlo = pmuludq(a, b);
15574 // AloBhi = pmuludq(a, Bhi);
15575 // AhiBlo = pmuludq(Ahi, b);
15577 // AloBhi = psllqi(AloBhi, 32);
15578 // AhiBlo = psllqi(AhiBlo, 32);
15579 // return AloBlo + AloBhi + AhiBlo;
15581 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15582 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15584 // Bit cast to 32-bit vectors for MULUDQ
15585 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15586 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15587 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15588 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15589 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15590 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15592 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15593 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15594 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15596 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15597 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15599 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15600 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15603 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15604 assert(Subtarget->isTargetWin64() && "Unexpected target");
15605 EVT VT = Op.getValueType();
15606 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15607 "Unexpected return type for lowering");
15611 switch (Op->getOpcode()) {
15612 default: llvm_unreachable("Unexpected request for libcall!");
15613 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15614 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15615 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15616 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15617 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15618 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15622 SDValue InChain = DAG.getEntryNode();
15624 TargetLowering::ArgListTy Args;
15625 TargetLowering::ArgListEntry Entry;
15626 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15627 EVT ArgVT = Op->getOperand(i).getValueType();
15628 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15629 "Unexpected argument type for lowering");
15630 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15631 Entry.Node = StackPtr;
15632 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15634 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15635 Entry.Ty = PointerType::get(ArgTy,0);
15636 Entry.isSExt = false;
15637 Entry.isZExt = false;
15638 Args.push_back(Entry);
15641 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15644 TargetLowering::CallLoweringInfo CLI(DAG);
15645 CLI.setDebugLoc(dl).setChain(InChain)
15646 .setCallee(getLibcallCallingConv(LC),
15647 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15648 Callee, std::move(Args), 0)
15649 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15651 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15652 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15655 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15656 SelectionDAG &DAG) {
15657 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15658 EVT VT = Op0.getValueType();
15661 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15662 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15664 // PMULxD operations multiply each even value (starting at 0) of LHS with
15665 // the related value of RHS and produce a widen result.
15666 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15667 // => <2 x i64> <ae|cg>
15669 // In other word, to have all the results, we need to perform two PMULxD:
15670 // 1. one with the even values.
15671 // 2. one with the odd values.
15672 // To achieve #2, with need to place the odd values at an even position.
15674 // Place the odd value at an even position (basically, shift all values 1
15675 // step to the left):
15676 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15677 // <a|b|c|d> => <b|undef|d|undef>
15678 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15679 // <e|f|g|h> => <f|undef|h|undef>
15680 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15682 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15684 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15685 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15687 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15688 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15689 // => <2 x i64> <ae|cg>
15690 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15691 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15692 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15693 // => <2 x i64> <bf|dh>
15694 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15695 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15697 // Shuffle it back into the right order.
15698 SDValue Highs, Lows;
15699 if (VT == MVT::v8i32) {
15700 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15701 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15702 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15703 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15705 const int HighMask[] = {1, 5, 3, 7};
15706 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15707 const int LowMask[] = {1, 4, 2, 6};
15708 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15711 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15712 // unsigned multiply.
15713 if (IsSigned && !Subtarget->hasSSE41()) {
15715 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15716 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15717 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15718 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15719 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15721 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15722 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15725 // The first result of MUL_LOHI is actually the low value, followed by the
15727 SDValue Ops[] = {Lows, Highs};
15728 return DAG.getMergeValues(Ops, dl);
15731 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15732 const X86Subtarget *Subtarget) {
15733 MVT VT = Op.getSimpleValueType();
15735 SDValue R = Op.getOperand(0);
15736 SDValue Amt = Op.getOperand(1);
15738 // Optimize shl/srl/sra with constant shift amount.
15739 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15740 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15741 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15743 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15744 (Subtarget->hasInt256() &&
15745 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15746 (Subtarget->hasAVX512() &&
15747 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15748 if (Op.getOpcode() == ISD::SHL)
15749 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15751 if (Op.getOpcode() == ISD::SRL)
15752 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15754 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15755 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15759 if (VT == MVT::v16i8) {
15760 if (Op.getOpcode() == ISD::SHL) {
15761 // Make a large shift.
15762 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15763 MVT::v8i16, R, ShiftAmt,
15765 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15766 // Zero out the rightmost bits.
15767 SmallVector<SDValue, 16> V(16,
15768 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15770 return DAG.getNode(ISD::AND, dl, VT, SHL,
15771 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15773 if (Op.getOpcode() == ISD::SRL) {
15774 // Make a large shift.
15775 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15776 MVT::v8i16, R, ShiftAmt,
15778 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15779 // Zero out the leftmost bits.
15780 SmallVector<SDValue, 16> V(16,
15781 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15783 return DAG.getNode(ISD::AND, dl, VT, SRL,
15784 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15786 if (Op.getOpcode() == ISD::SRA) {
15787 if (ShiftAmt == 7) {
15788 // R s>> 7 === R s< 0
15789 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15790 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15793 // R s>> a === ((R u>> a) ^ m) - m
15794 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15795 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15797 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15798 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15799 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15802 llvm_unreachable("Unknown shift opcode.");
15805 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15806 if (Op.getOpcode() == ISD::SHL) {
15807 // Make a large shift.
15808 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15809 MVT::v16i16, R, ShiftAmt,
15811 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15812 // Zero out the rightmost bits.
15813 SmallVector<SDValue, 32> V(32,
15814 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15816 return DAG.getNode(ISD::AND, dl, VT, SHL,
15817 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15819 if (Op.getOpcode() == ISD::SRL) {
15820 // Make a large shift.
15821 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15822 MVT::v16i16, R, ShiftAmt,
15824 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15825 // Zero out the leftmost bits.
15826 SmallVector<SDValue, 32> V(32,
15827 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15829 return DAG.getNode(ISD::AND, dl, VT, SRL,
15830 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15832 if (Op.getOpcode() == ISD::SRA) {
15833 if (ShiftAmt == 7) {
15834 // R s>> 7 === R s< 0
15835 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15836 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15839 // R s>> a === ((R u>> a) ^ m) - m
15840 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15841 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15843 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15844 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15845 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15848 llvm_unreachable("Unknown shift opcode.");
15853 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15854 if (!Subtarget->is64Bit() &&
15855 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15856 Amt.getOpcode() == ISD::BITCAST &&
15857 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15858 Amt = Amt.getOperand(0);
15859 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15860 VT.getVectorNumElements();
15861 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15862 uint64_t ShiftAmt = 0;
15863 for (unsigned i = 0; i != Ratio; ++i) {
15864 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15868 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15870 // Check remaining shift amounts.
15871 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15872 uint64_t ShAmt = 0;
15873 for (unsigned j = 0; j != Ratio; ++j) {
15874 ConstantSDNode *C =
15875 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15879 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15881 if (ShAmt != ShiftAmt)
15884 switch (Op.getOpcode()) {
15886 llvm_unreachable("Unknown shift opcode!");
15888 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15891 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15894 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15902 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15903 const X86Subtarget* Subtarget) {
15904 MVT VT = Op.getSimpleValueType();
15906 SDValue R = Op.getOperand(0);
15907 SDValue Amt = Op.getOperand(1);
15909 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15910 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15911 (Subtarget->hasInt256() &&
15912 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15913 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15914 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15916 EVT EltVT = VT.getVectorElementType();
15918 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15919 unsigned NumElts = VT.getVectorNumElements();
15921 for (i = 0; i != NumElts; ++i) {
15922 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15926 for (j = i; j != NumElts; ++j) {
15927 SDValue Arg = Amt.getOperand(j);
15928 if (Arg.getOpcode() == ISD::UNDEF) continue;
15929 if (Arg != Amt.getOperand(i))
15932 if (i != NumElts && j == NumElts)
15933 BaseShAmt = Amt.getOperand(i);
15935 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15936 Amt = Amt.getOperand(0);
15937 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15938 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15939 SDValue InVec = Amt.getOperand(0);
15940 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15941 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15943 for (; i != NumElts; ++i) {
15944 SDValue Arg = InVec.getOperand(i);
15945 if (Arg.getOpcode() == ISD::UNDEF) continue;
15949 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15950 if (ConstantSDNode *C =
15951 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15952 unsigned SplatIdx =
15953 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15954 if (C->getZExtValue() == SplatIdx)
15955 BaseShAmt = InVec.getOperand(1);
15958 if (!BaseShAmt.getNode())
15959 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15960 DAG.getIntPtrConstant(0));
15964 if (BaseShAmt.getNode()) {
15965 if (EltVT.bitsGT(MVT::i32))
15966 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15967 else if (EltVT.bitsLT(MVT::i32))
15968 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15970 switch (Op.getOpcode()) {
15972 llvm_unreachable("Unknown shift opcode!");
15974 switch (VT.SimpleTy) {
15975 default: return SDValue();
15984 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15987 switch (VT.SimpleTy) {
15988 default: return SDValue();
15995 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15998 switch (VT.SimpleTy) {
15999 default: return SDValue();
16008 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16014 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16015 if (!Subtarget->is64Bit() &&
16016 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16017 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16018 Amt.getOpcode() == ISD::BITCAST &&
16019 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16020 Amt = Amt.getOperand(0);
16021 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16022 VT.getVectorNumElements();
16023 std::vector<SDValue> Vals(Ratio);
16024 for (unsigned i = 0; i != Ratio; ++i)
16025 Vals[i] = Amt.getOperand(i);
16026 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16027 for (unsigned j = 0; j != Ratio; ++j)
16028 if (Vals[j] != Amt.getOperand(i + j))
16031 switch (Op.getOpcode()) {
16033 llvm_unreachable("Unknown shift opcode!");
16035 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16037 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16039 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16046 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16047 SelectionDAG &DAG) {
16048 MVT VT = Op.getSimpleValueType();
16050 SDValue R = Op.getOperand(0);
16051 SDValue Amt = Op.getOperand(1);
16054 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16055 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16057 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16061 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16065 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16067 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16068 if (Subtarget->hasInt256()) {
16069 if (Op.getOpcode() == ISD::SRL &&
16070 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16071 VT == MVT::v4i64 || VT == MVT::v8i32))
16073 if (Op.getOpcode() == ISD::SHL &&
16074 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16075 VT == MVT::v4i64 || VT == MVT::v8i32))
16077 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16081 // If possible, lower this packed shift into a vector multiply instead of
16082 // expanding it into a sequence of scalar shifts.
16083 // Do this only if the vector shift count is a constant build_vector.
16084 if (Op.getOpcode() == ISD::SHL &&
16085 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16086 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16087 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16088 SmallVector<SDValue, 8> Elts;
16089 EVT SVT = VT.getScalarType();
16090 unsigned SVTBits = SVT.getSizeInBits();
16091 const APInt &One = APInt(SVTBits, 1);
16092 unsigned NumElems = VT.getVectorNumElements();
16094 for (unsigned i=0; i !=NumElems; ++i) {
16095 SDValue Op = Amt->getOperand(i);
16096 if (Op->getOpcode() == ISD::UNDEF) {
16097 Elts.push_back(Op);
16101 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16102 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16103 uint64_t ShAmt = C.getZExtValue();
16104 if (ShAmt >= SVTBits) {
16105 Elts.push_back(DAG.getUNDEF(SVT));
16108 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16110 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16111 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16114 // Lower SHL with variable shift amount.
16115 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16116 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16118 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16119 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16120 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16121 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16124 // If possible, lower this shift as a sequence of two shifts by
16125 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16127 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16129 // Could be rewritten as:
16130 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16132 // The advantage is that the two shifts from the example would be
16133 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16134 // the vector shift into four scalar shifts plus four pairs of vector
16136 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16137 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16138 unsigned TargetOpcode = X86ISD::MOVSS;
16139 bool CanBeSimplified;
16140 // The splat value for the first packed shift (the 'X' from the example).
16141 SDValue Amt1 = Amt->getOperand(0);
16142 // The splat value for the second packed shift (the 'Y' from the example).
16143 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16144 Amt->getOperand(2);
16146 // See if it is possible to replace this node with a sequence of
16147 // two shifts followed by a MOVSS/MOVSD
16148 if (VT == MVT::v4i32) {
16149 // Check if it is legal to use a MOVSS.
16150 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16151 Amt2 == Amt->getOperand(3);
16152 if (!CanBeSimplified) {
16153 // Otherwise, check if we can still simplify this node using a MOVSD.
16154 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16155 Amt->getOperand(2) == Amt->getOperand(3);
16156 TargetOpcode = X86ISD::MOVSD;
16157 Amt2 = Amt->getOperand(2);
16160 // Do similar checks for the case where the machine value type
16162 CanBeSimplified = Amt1 == Amt->getOperand(1);
16163 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16164 CanBeSimplified = Amt2 == Amt->getOperand(i);
16166 if (!CanBeSimplified) {
16167 TargetOpcode = X86ISD::MOVSD;
16168 CanBeSimplified = true;
16169 Amt2 = Amt->getOperand(4);
16170 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16171 CanBeSimplified = Amt1 == Amt->getOperand(i);
16172 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16173 CanBeSimplified = Amt2 == Amt->getOperand(j);
16177 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16178 isa<ConstantSDNode>(Amt2)) {
16179 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16180 EVT CastVT = MVT::v4i32;
16182 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16183 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16185 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16186 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16187 if (TargetOpcode == X86ISD::MOVSD)
16188 CastVT = MVT::v2i64;
16189 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16190 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16191 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16193 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16197 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16198 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16201 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16202 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16204 // Turn 'a' into a mask suitable for VSELECT
16205 SDValue VSelM = DAG.getConstant(0x80, VT);
16206 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16207 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16209 SDValue CM1 = DAG.getConstant(0x0f, VT);
16210 SDValue CM2 = DAG.getConstant(0x3f, VT);
16212 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16213 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16214 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16215 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16216 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16219 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16220 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16221 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16223 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16224 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16225 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16226 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16227 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16230 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16231 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16232 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16234 // return VSELECT(r, r+r, a);
16235 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16236 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16240 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16241 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16242 // solution better.
16243 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16244 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16246 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16247 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16248 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16249 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16250 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16253 // Decompose 256-bit shifts into smaller 128-bit shifts.
16254 if (VT.is256BitVector()) {
16255 unsigned NumElems = VT.getVectorNumElements();
16256 MVT EltVT = VT.getVectorElementType();
16257 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16259 // Extract the two vectors
16260 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16261 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16263 // Recreate the shift amount vectors
16264 SDValue Amt1, Amt2;
16265 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16266 // Constant shift amount
16267 SmallVector<SDValue, 4> Amt1Csts;
16268 SmallVector<SDValue, 4> Amt2Csts;
16269 for (unsigned i = 0; i != NumElems/2; ++i)
16270 Amt1Csts.push_back(Amt->getOperand(i));
16271 for (unsigned i = NumElems/2; i != NumElems; ++i)
16272 Amt2Csts.push_back(Amt->getOperand(i));
16274 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16275 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16277 // Variable shift amount
16278 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16279 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16282 // Issue new vector shifts for the smaller types
16283 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16284 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16286 // Concatenate the result back
16287 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16293 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16294 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16295 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16296 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16297 // has only one use.
16298 SDNode *N = Op.getNode();
16299 SDValue LHS = N->getOperand(0);
16300 SDValue RHS = N->getOperand(1);
16301 unsigned BaseOp = 0;
16304 switch (Op.getOpcode()) {
16305 default: llvm_unreachable("Unknown ovf instruction!");
16307 // A subtract of one will be selected as a INC. Note that INC doesn't
16308 // set CF, so we can't do this for UADDO.
16309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16311 BaseOp = X86ISD::INC;
16312 Cond = X86::COND_O;
16315 BaseOp = X86ISD::ADD;
16316 Cond = X86::COND_O;
16319 BaseOp = X86ISD::ADD;
16320 Cond = X86::COND_B;
16323 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16324 // set CF, so we can't do this for USUBO.
16325 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16327 BaseOp = X86ISD::DEC;
16328 Cond = X86::COND_O;
16331 BaseOp = X86ISD::SUB;
16332 Cond = X86::COND_O;
16335 BaseOp = X86ISD::SUB;
16336 Cond = X86::COND_B;
16339 BaseOp = X86ISD::SMUL;
16340 Cond = X86::COND_O;
16342 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16343 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16345 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16348 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16349 DAG.getConstant(X86::COND_O, MVT::i32),
16350 SDValue(Sum.getNode(), 2));
16352 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16356 // Also sets EFLAGS.
16357 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16358 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16361 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16362 DAG.getConstant(Cond, MVT::i32),
16363 SDValue(Sum.getNode(), 1));
16365 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16368 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16369 SelectionDAG &DAG) const {
16371 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16372 MVT VT = Op.getSimpleValueType();
16374 if (!Subtarget->hasSSE2() || !VT.isVector())
16377 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16378 ExtraVT.getScalarType().getSizeInBits();
16380 switch (VT.SimpleTy) {
16381 default: return SDValue();
16384 if (!Subtarget->hasFp256())
16386 if (!Subtarget->hasInt256()) {
16387 // needs to be split
16388 unsigned NumElems = VT.getVectorNumElements();
16390 // Extract the LHS vectors
16391 SDValue LHS = Op.getOperand(0);
16392 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16393 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16395 MVT EltVT = VT.getVectorElementType();
16396 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16398 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16399 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16400 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16402 SDValue Extra = DAG.getValueType(ExtraVT);
16404 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16405 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16407 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16412 SDValue Op0 = Op.getOperand(0);
16413 SDValue Op00 = Op0.getOperand(0);
16415 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16416 if (Op0.getOpcode() == ISD::BITCAST &&
16417 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16418 // (sext (vzext x)) -> (vsext x)
16419 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16420 if (Tmp1.getNode()) {
16421 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16422 // This folding is only valid when the in-reg type is a vector of i8,
16424 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16425 ExtraEltVT == MVT::i32) {
16426 SDValue Tmp1Op0 = Tmp1.getOperand(0);
16427 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16428 "This optimization is invalid without a VZEXT.");
16429 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16435 // If the above didn't work, then just use Shift-Left + Shift-Right.
16436 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16438 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16444 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16445 SelectionDAG &DAG) {
16447 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16448 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16449 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16450 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16452 // The only fence that needs an instruction is a sequentially-consistent
16453 // cross-thread fence.
16454 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16455 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16456 // no-sse2). There isn't any reason to disable it if the target processor
16458 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16459 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16461 SDValue Chain = Op.getOperand(0);
16462 SDValue Zero = DAG.getConstant(0, MVT::i32);
16464 DAG.getRegister(X86::ESP, MVT::i32), // Base
16465 DAG.getTargetConstant(1, MVT::i8), // Scale
16466 DAG.getRegister(0, MVT::i32), // Index
16467 DAG.getTargetConstant(0, MVT::i32), // Disp
16468 DAG.getRegister(0, MVT::i32), // Segment.
16472 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16473 return SDValue(Res, 0);
16476 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16477 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16480 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16481 SelectionDAG &DAG) {
16482 MVT T = Op.getSimpleValueType();
16486 switch(T.SimpleTy) {
16487 default: llvm_unreachable("Invalid value type!");
16488 case MVT::i8: Reg = X86::AL; size = 1; break;
16489 case MVT::i16: Reg = X86::AX; size = 2; break;
16490 case MVT::i32: Reg = X86::EAX; size = 4; break;
16492 assert(Subtarget->is64Bit() && "Node not type legal!");
16493 Reg = X86::RAX; size = 8;
16496 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16497 Op.getOperand(2), SDValue());
16498 SDValue Ops[] = { cpIn.getValue(0),
16501 DAG.getTargetConstant(size, MVT::i8),
16502 cpIn.getValue(1) };
16503 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16504 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16505 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16509 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16510 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16511 MVT::i32, cpOut.getValue(2));
16512 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16513 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16515 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16516 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16517 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16521 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16522 SelectionDAG &DAG) {
16523 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16524 MVT DstVT = Op.getSimpleValueType();
16526 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16527 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16528 if (DstVT != MVT::f64)
16529 // This conversion needs to be expanded.
16532 SDValue InVec = Op->getOperand(0);
16534 unsigned NumElts = SrcVT.getVectorNumElements();
16535 EVT SVT = SrcVT.getVectorElementType();
16537 // Widen the vector in input in the case of MVT::v2i32.
16538 // Example: from MVT::v2i32 to MVT::v4i32.
16539 SmallVector<SDValue, 16> Elts;
16540 for (unsigned i = 0, e = NumElts; i != e; ++i)
16541 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16542 DAG.getIntPtrConstant(i)));
16544 // Explicitly mark the extra elements as Undef.
16545 SDValue Undef = DAG.getUNDEF(SVT);
16546 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16547 Elts.push_back(Undef);
16549 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16550 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16551 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16552 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16553 DAG.getIntPtrConstant(0));
16556 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16557 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16558 assert((DstVT == MVT::i64 ||
16559 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16560 "Unexpected custom BITCAST");
16561 // i64 <=> MMX conversions are Legal.
16562 if (SrcVT==MVT::i64 && DstVT.isVector())
16564 if (DstVT==MVT::i64 && SrcVT.isVector())
16566 // MMX <=> MMX conversions are Legal.
16567 if (SrcVT.isVector() && DstVT.isVector())
16569 // All other conversions need to be expanded.
16573 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16574 SDNode *Node = Op.getNode();
16576 EVT T = Node->getValueType(0);
16577 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16578 DAG.getConstant(0, T), Node->getOperand(2));
16579 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16580 cast<AtomicSDNode>(Node)->getMemoryVT(),
16581 Node->getOperand(0),
16582 Node->getOperand(1), negOp,
16583 cast<AtomicSDNode>(Node)->getMemOperand(),
16584 cast<AtomicSDNode>(Node)->getOrdering(),
16585 cast<AtomicSDNode>(Node)->getSynchScope());
16588 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16589 SDNode *Node = Op.getNode();
16591 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16593 // Convert seq_cst store -> xchg
16594 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16595 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16596 // (The only way to get a 16-byte store is cmpxchg16b)
16597 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16598 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16599 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16600 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16601 cast<AtomicSDNode>(Node)->getMemoryVT(),
16602 Node->getOperand(0),
16603 Node->getOperand(1), Node->getOperand(2),
16604 cast<AtomicSDNode>(Node)->getMemOperand(),
16605 cast<AtomicSDNode>(Node)->getOrdering(),
16606 cast<AtomicSDNode>(Node)->getSynchScope());
16607 return Swap.getValue(1);
16609 // Other atomic stores have a simple pattern.
16613 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16614 EVT VT = Op.getNode()->getSimpleValueType(0);
16616 // Let legalize expand this if it isn't a legal type yet.
16617 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16620 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16623 bool ExtraOp = false;
16624 switch (Op.getOpcode()) {
16625 default: llvm_unreachable("Invalid code");
16626 case ISD::ADDC: Opc = X86ISD::ADD; break;
16627 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16628 case ISD::SUBC: Opc = X86ISD::SUB; break;
16629 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16633 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16635 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16636 Op.getOperand(1), Op.getOperand(2));
16639 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16640 SelectionDAG &DAG) {
16641 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16643 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16644 // which returns the values as { float, float } (in XMM0) or
16645 // { double, double } (which is returned in XMM0, XMM1).
16647 SDValue Arg = Op.getOperand(0);
16648 EVT ArgVT = Arg.getValueType();
16649 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16651 TargetLowering::ArgListTy Args;
16652 TargetLowering::ArgListEntry Entry;
16656 Entry.isSExt = false;
16657 Entry.isZExt = false;
16658 Args.push_back(Entry);
16660 bool isF64 = ArgVT == MVT::f64;
16661 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16662 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16663 // the results are returned via SRet in memory.
16664 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16665 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16666 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16668 Type *RetTy = isF64
16669 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16670 : (Type*)VectorType::get(ArgTy, 4);
16672 TargetLowering::CallLoweringInfo CLI(DAG);
16673 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16674 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16676 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16679 // Returned in xmm0 and xmm1.
16680 return CallResult.first;
16682 // Returned in bits 0:31 and 32:64 xmm0.
16683 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16684 CallResult.first, DAG.getIntPtrConstant(0));
16685 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16686 CallResult.first, DAG.getIntPtrConstant(1));
16687 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16688 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16691 /// LowerOperation - Provide custom lowering hooks for some operations.
16693 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16694 switch (Op.getOpcode()) {
16695 default: llvm_unreachable("Should not custom lower this!");
16696 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16697 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16698 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16699 return LowerCMP_SWAP(Op, Subtarget, DAG);
16700 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16701 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16702 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16703 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16704 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16705 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16706 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16707 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16708 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16709 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16710 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16711 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16712 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16713 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16714 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16715 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16716 case ISD::SHL_PARTS:
16717 case ISD::SRA_PARTS:
16718 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16719 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16720 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16721 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16722 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16723 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16724 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16725 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16726 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16727 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16728 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16729 case ISD::FABS: return LowerFABS(Op, DAG);
16730 case ISD::FNEG: return LowerFNEG(Op, DAG);
16731 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16732 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16733 case ISD::SETCC: return LowerSETCC(Op, DAG);
16734 case ISD::SELECT: return LowerSELECT(Op, DAG);
16735 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16736 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16737 case ISD::VASTART: return LowerVASTART(Op, DAG);
16738 case ISD::VAARG: return LowerVAARG(Op, DAG);
16739 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16740 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16741 case ISD::INTRINSIC_VOID:
16742 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16743 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16744 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16745 case ISD::FRAME_TO_ARGS_OFFSET:
16746 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16747 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16748 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16749 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16750 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16751 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16752 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16753 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16754 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16755 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16756 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16757 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16758 case ISD::UMUL_LOHI:
16759 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16762 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16768 case ISD::UMULO: return LowerXALUO(Op, DAG);
16769 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16770 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16774 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16775 case ISD::ADD: return LowerADD(Op, DAG);
16776 case ISD::SUB: return LowerSUB(Op, DAG);
16777 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16781 static void ReplaceATOMIC_LOAD(SDNode *Node,
16782 SmallVectorImpl<SDValue> &Results,
16783 SelectionDAG &DAG) {
16785 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16787 // Convert wide load -> cmpxchg8b/cmpxchg16b
16788 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16789 // (The only way to get a 16-byte load is cmpxchg16b)
16790 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16791 SDValue Zero = DAG.getConstant(0, VT);
16792 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16794 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16795 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16796 cast<AtomicSDNode>(Node)->getMemOperand(),
16797 cast<AtomicSDNode>(Node)->getOrdering(),
16798 cast<AtomicSDNode>(Node)->getOrdering(),
16799 cast<AtomicSDNode>(Node)->getSynchScope());
16800 Results.push_back(Swap.getValue(0));
16801 Results.push_back(Swap.getValue(2));
16804 /// ReplaceNodeResults - Replace a node with an illegal result type
16805 /// with a new node built out of custom code.
16806 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16807 SmallVectorImpl<SDValue>&Results,
16808 SelectionDAG &DAG) const {
16810 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16811 switch (N->getOpcode()) {
16813 llvm_unreachable("Do not know how to custom type legalize this operation!");
16814 case ISD::SIGN_EXTEND_INREG:
16819 // We don't want to expand or promote these.
16826 case ISD::UDIVREM: {
16827 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16828 Results.push_back(V);
16831 case ISD::FP_TO_SINT:
16832 case ISD::FP_TO_UINT: {
16833 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16835 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16838 std::pair<SDValue,SDValue> Vals =
16839 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16840 SDValue FIST = Vals.first, StackSlot = Vals.second;
16841 if (FIST.getNode()) {
16842 EVT VT = N->getValueType(0);
16843 // Return a load from the stack slot.
16844 if (StackSlot.getNode())
16845 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16846 MachinePointerInfo(),
16847 false, false, false, 0));
16849 Results.push_back(FIST);
16853 case ISD::UINT_TO_FP: {
16854 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16855 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16856 N->getValueType(0) != MVT::v2f32)
16858 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16860 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16862 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16863 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16864 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16865 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16866 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16867 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16870 case ISD::FP_ROUND: {
16871 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16873 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16874 Results.push_back(V);
16877 case ISD::INTRINSIC_W_CHAIN: {
16878 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16880 default : llvm_unreachable("Do not know how to custom type "
16881 "legalize this intrinsic operation!");
16882 case Intrinsic::x86_rdtsc:
16883 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16885 case Intrinsic::x86_rdtscp:
16886 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16888 case Intrinsic::x86_rdpmc:
16889 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16892 case ISD::READCYCLECOUNTER: {
16893 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16896 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16897 EVT T = N->getValueType(0);
16898 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16899 bool Regs64bit = T == MVT::i128;
16900 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16901 SDValue cpInL, cpInH;
16902 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16903 DAG.getConstant(0, HalfT));
16904 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16905 DAG.getConstant(1, HalfT));
16906 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16907 Regs64bit ? X86::RAX : X86::EAX,
16909 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16910 Regs64bit ? X86::RDX : X86::EDX,
16911 cpInH, cpInL.getValue(1));
16912 SDValue swapInL, swapInH;
16913 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16914 DAG.getConstant(0, HalfT));
16915 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16916 DAG.getConstant(1, HalfT));
16917 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16918 Regs64bit ? X86::RBX : X86::EBX,
16919 swapInL, cpInH.getValue(1));
16920 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16921 Regs64bit ? X86::RCX : X86::ECX,
16922 swapInH, swapInL.getValue(1));
16923 SDValue Ops[] = { swapInH.getValue(0),
16925 swapInH.getValue(1) };
16926 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16927 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16928 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16929 X86ISD::LCMPXCHG8_DAG;
16930 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16931 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16932 Regs64bit ? X86::RAX : X86::EAX,
16933 HalfT, Result.getValue(1));
16934 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16935 Regs64bit ? X86::RDX : X86::EDX,
16936 HalfT, cpOutL.getValue(2));
16937 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16939 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16940 MVT::i32, cpOutH.getValue(2));
16942 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16943 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16944 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16946 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16947 Results.push_back(Success);
16948 Results.push_back(EFLAGS.getValue(1));
16951 case ISD::ATOMIC_SWAP:
16952 case ISD::ATOMIC_LOAD_ADD:
16953 case ISD::ATOMIC_LOAD_SUB:
16954 case ISD::ATOMIC_LOAD_AND:
16955 case ISD::ATOMIC_LOAD_OR:
16956 case ISD::ATOMIC_LOAD_XOR:
16957 case ISD::ATOMIC_LOAD_NAND:
16958 case ISD::ATOMIC_LOAD_MIN:
16959 case ISD::ATOMIC_LOAD_MAX:
16960 case ISD::ATOMIC_LOAD_UMIN:
16961 case ISD::ATOMIC_LOAD_UMAX:
16962 // Delegate to generic TypeLegalization. Situations we can really handle
16963 // should have already been dealt with by X86AtomicExpand.cpp.
16965 case ISD::ATOMIC_LOAD: {
16966 ReplaceATOMIC_LOAD(N, Results, DAG);
16969 case ISD::BITCAST: {
16970 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16971 EVT DstVT = N->getValueType(0);
16972 EVT SrcVT = N->getOperand(0)->getValueType(0);
16974 if (SrcVT != MVT::f64 ||
16975 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16978 unsigned NumElts = DstVT.getVectorNumElements();
16979 EVT SVT = DstVT.getVectorElementType();
16980 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16981 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16982 MVT::v2f64, N->getOperand(0));
16983 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16985 if (ExperimentalVectorWideningLegalization) {
16986 // If we are legalizing vectors by widening, we already have the desired
16987 // legal vector type, just return it.
16988 Results.push_back(ToVecInt);
16992 SmallVector<SDValue, 8> Elts;
16993 for (unsigned i = 0, e = NumElts; i != e; ++i)
16994 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16995 ToVecInt, DAG.getIntPtrConstant(i)));
16997 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17002 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17004 default: return nullptr;
17005 case X86ISD::BSF: return "X86ISD::BSF";
17006 case X86ISD::BSR: return "X86ISD::BSR";
17007 case X86ISD::SHLD: return "X86ISD::SHLD";
17008 case X86ISD::SHRD: return "X86ISD::SHRD";
17009 case X86ISD::FAND: return "X86ISD::FAND";
17010 case X86ISD::FANDN: return "X86ISD::FANDN";
17011 case X86ISD::FOR: return "X86ISD::FOR";
17012 case X86ISD::FXOR: return "X86ISD::FXOR";
17013 case X86ISD::FSRL: return "X86ISD::FSRL";
17014 case X86ISD::FILD: return "X86ISD::FILD";
17015 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17016 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17017 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17018 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17019 case X86ISD::FLD: return "X86ISD::FLD";
17020 case X86ISD::FST: return "X86ISD::FST";
17021 case X86ISD::CALL: return "X86ISD::CALL";
17022 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17023 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17024 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17025 case X86ISD::BT: return "X86ISD::BT";
17026 case X86ISD::CMP: return "X86ISD::CMP";
17027 case X86ISD::COMI: return "X86ISD::COMI";
17028 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17029 case X86ISD::CMPM: return "X86ISD::CMPM";
17030 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17031 case X86ISD::SETCC: return "X86ISD::SETCC";
17032 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17033 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17034 case X86ISD::CMOV: return "X86ISD::CMOV";
17035 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17036 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17037 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17038 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17039 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17040 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17041 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17042 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17043 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17044 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17045 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17046 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17047 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17048 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17049 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17050 case X86ISD::BLENDV: return "X86ISD::BLENDV";
17051 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17052 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17053 case X86ISD::HADD: return "X86ISD::HADD";
17054 case X86ISD::HSUB: return "X86ISD::HSUB";
17055 case X86ISD::FHADD: return "X86ISD::FHADD";
17056 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17057 case X86ISD::UMAX: return "X86ISD::UMAX";
17058 case X86ISD::UMIN: return "X86ISD::UMIN";
17059 case X86ISD::SMAX: return "X86ISD::SMAX";
17060 case X86ISD::SMIN: return "X86ISD::SMIN";
17061 case X86ISD::FMAX: return "X86ISD::FMAX";
17062 case X86ISD::FMIN: return "X86ISD::FMIN";
17063 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17064 case X86ISD::FMINC: return "X86ISD::FMINC";
17065 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17066 case X86ISD::FRCP: return "X86ISD::FRCP";
17067 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17068 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17069 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17070 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17071 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17072 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17073 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17074 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17075 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17076 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17077 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17078 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17079 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17080 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17081 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17082 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17083 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17084 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17085 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17086 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17087 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17088 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17089 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17090 case X86ISD::VSHL: return "X86ISD::VSHL";
17091 case X86ISD::VSRL: return "X86ISD::VSRL";
17092 case X86ISD::VSRA: return "X86ISD::VSRA";
17093 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17094 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17095 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17096 case X86ISD::CMPP: return "X86ISD::CMPP";
17097 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17098 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17099 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17100 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17101 case X86ISD::ADD: return "X86ISD::ADD";
17102 case X86ISD::SUB: return "X86ISD::SUB";
17103 case X86ISD::ADC: return "X86ISD::ADC";
17104 case X86ISD::SBB: return "X86ISD::SBB";
17105 case X86ISD::SMUL: return "X86ISD::SMUL";
17106 case X86ISD::UMUL: return "X86ISD::UMUL";
17107 case X86ISD::INC: return "X86ISD::INC";
17108 case X86ISD::DEC: return "X86ISD::DEC";
17109 case X86ISD::OR: return "X86ISD::OR";
17110 case X86ISD::XOR: return "X86ISD::XOR";
17111 case X86ISD::AND: return "X86ISD::AND";
17112 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17113 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17114 case X86ISD::PTEST: return "X86ISD::PTEST";
17115 case X86ISD::TESTP: return "X86ISD::TESTP";
17116 case X86ISD::TESTM: return "X86ISD::TESTM";
17117 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17118 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17119 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17120 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17121 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17122 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17123 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17124 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17125 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17126 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17127 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17128 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17129 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17130 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17131 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17132 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17133 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17134 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17135 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17136 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17137 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17138 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17139 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17140 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17141 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17142 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
17143 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17144 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17145 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17146 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17147 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17148 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17149 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17150 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17151 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17152 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17153 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17154 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17155 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17156 case X86ISD::SAHF: return "X86ISD::SAHF";
17157 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17158 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17159 case X86ISD::FMADD: return "X86ISD::FMADD";
17160 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17161 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17162 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17163 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17164 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17165 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17166 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17167 case X86ISD::XTEST: return "X86ISD::XTEST";
17171 // isLegalAddressingMode - Return true if the addressing mode represented
17172 // by AM is legal for this target, for a load/store of the specified type.
17173 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17175 // X86 supports extremely general addressing modes.
17176 CodeModel::Model M = getTargetMachine().getCodeModel();
17177 Reloc::Model R = getTargetMachine().getRelocationModel();
17179 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17180 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17185 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17187 // If a reference to this global requires an extra load, we can't fold it.
17188 if (isGlobalStubReference(GVFlags))
17191 // If BaseGV requires a register for the PIC base, we cannot also have a
17192 // BaseReg specified.
17193 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17196 // If lower 4G is not available, then we must use rip-relative addressing.
17197 if ((M != CodeModel::Small || R != Reloc::Static) &&
17198 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17202 switch (AM.Scale) {
17208 // These scales always work.
17213 // These scales are formed with basereg+scalereg. Only accept if there is
17218 default: // Other stuff never works.
17225 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17226 unsigned Bits = Ty->getScalarSizeInBits();
17228 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17229 // particularly cheaper than those without.
17233 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17234 // variable shifts just as cheap as scalar ones.
17235 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17238 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17239 // fully general vector.
17243 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17244 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17246 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17247 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17248 return NumBits1 > NumBits2;
17251 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17252 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17255 if (!isTypeLegal(EVT::getEVT(Ty1)))
17258 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17260 // Assuming the caller doesn't have a zeroext or signext return parameter,
17261 // truncation all the way down to i1 is valid.
17265 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17266 return isInt<32>(Imm);
17269 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17270 // Can also use sub to handle negated immediates.
17271 return isInt<32>(Imm);
17274 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17275 if (!VT1.isInteger() || !VT2.isInteger())
17277 unsigned NumBits1 = VT1.getSizeInBits();
17278 unsigned NumBits2 = VT2.getSizeInBits();
17279 return NumBits1 > NumBits2;
17282 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17283 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17284 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17287 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17288 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17289 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17292 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17293 EVT VT1 = Val.getValueType();
17294 if (isZExtFree(VT1, VT2))
17297 if (Val.getOpcode() != ISD::LOAD)
17300 if (!VT1.isSimple() || !VT1.isInteger() ||
17301 !VT2.isSimple() || !VT2.isInteger())
17304 switch (VT1.getSimpleVT().SimpleTy) {
17309 // X86 has 8, 16, and 32-bit zero-extending loads.
17317 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17318 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17321 VT = VT.getScalarType();
17323 if (!VT.isSimple())
17326 switch (VT.getSimpleVT().SimpleTy) {
17337 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17338 // i16 instructions are longer (0x66 prefix) and potentially slower.
17339 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17342 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17343 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17344 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17345 /// are assumed to be legal.
17347 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17349 if (!VT.isSimple())
17352 MVT SVT = VT.getSimpleVT();
17354 // Very little shuffling can be done for 64-bit vectors right now.
17355 if (VT.getSizeInBits() == 64)
17358 // If this is a single-input shuffle with no 128 bit lane crossings we can
17359 // lower it into pshufb.
17360 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17361 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17362 bool isLegal = true;
17363 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17364 if (M[I] >= (int)SVT.getVectorNumElements() ||
17365 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17374 // FIXME: blends, shifts.
17375 return (SVT.getVectorNumElements() == 2 ||
17376 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17377 isMOVLMask(M, SVT) ||
17378 isMOVHLPSMask(M, SVT) ||
17379 isSHUFPMask(M, SVT) ||
17380 isPSHUFDMask(M, SVT) ||
17381 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17382 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17383 isPALIGNRMask(M, SVT, Subtarget) ||
17384 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17385 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17386 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17387 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17388 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17392 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17394 if (!VT.isSimple())
17397 MVT SVT = VT.getSimpleVT();
17398 unsigned NumElts = SVT.getVectorNumElements();
17399 // FIXME: This collection of masks seems suspect.
17402 if (NumElts == 4 && SVT.is128BitVector()) {
17403 return (isMOVLMask(Mask, SVT) ||
17404 isCommutedMOVLMask(Mask, SVT, true) ||
17405 isSHUFPMask(Mask, SVT) ||
17406 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17411 //===----------------------------------------------------------------------===//
17412 // X86 Scheduler Hooks
17413 //===----------------------------------------------------------------------===//
17415 /// Utility function to emit xbegin specifying the start of an RTM region.
17416 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17417 const TargetInstrInfo *TII) {
17418 DebugLoc DL = MI->getDebugLoc();
17420 const BasicBlock *BB = MBB->getBasicBlock();
17421 MachineFunction::iterator I = MBB;
17424 // For the v = xbegin(), we generate
17435 MachineBasicBlock *thisMBB = MBB;
17436 MachineFunction *MF = MBB->getParent();
17437 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17438 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17439 MF->insert(I, mainMBB);
17440 MF->insert(I, sinkMBB);
17442 // Transfer the remainder of BB and its successor edges to sinkMBB.
17443 sinkMBB->splice(sinkMBB->begin(), MBB,
17444 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17445 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17449 // # fallthrough to mainMBB
17450 // # abortion to sinkMBB
17451 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17452 thisMBB->addSuccessor(mainMBB);
17453 thisMBB->addSuccessor(sinkMBB);
17457 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17458 mainMBB->addSuccessor(sinkMBB);
17461 // EAX is live into the sinkMBB
17462 sinkMBB->addLiveIn(X86::EAX);
17463 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17464 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17467 MI->eraseFromParent();
17471 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17472 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17473 // in the .td file.
17474 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17475 const TargetInstrInfo *TII) {
17477 switch (MI->getOpcode()) {
17478 default: llvm_unreachable("illegal opcode!");
17479 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17480 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17481 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17482 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17483 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17484 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17485 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17486 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17489 DebugLoc dl = MI->getDebugLoc();
17490 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17492 unsigned NumArgs = MI->getNumOperands();
17493 for (unsigned i = 1; i < NumArgs; ++i) {
17494 MachineOperand &Op = MI->getOperand(i);
17495 if (!(Op.isReg() && Op.isImplicit()))
17496 MIB.addOperand(Op);
17498 if (MI->hasOneMemOperand())
17499 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17501 BuildMI(*BB, MI, dl,
17502 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17503 .addReg(X86::XMM0);
17505 MI->eraseFromParent();
17509 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17510 // defs in an instruction pattern
17511 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17512 const TargetInstrInfo *TII) {
17514 switch (MI->getOpcode()) {
17515 default: llvm_unreachable("illegal opcode!");
17516 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17517 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17518 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17519 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17520 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17521 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17522 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17523 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17526 DebugLoc dl = MI->getDebugLoc();
17527 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17529 unsigned NumArgs = MI->getNumOperands(); // remove the results
17530 for (unsigned i = 1; i < NumArgs; ++i) {
17531 MachineOperand &Op = MI->getOperand(i);
17532 if (!(Op.isReg() && Op.isImplicit()))
17533 MIB.addOperand(Op);
17535 if (MI->hasOneMemOperand())
17536 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17538 BuildMI(*BB, MI, dl,
17539 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17542 MI->eraseFromParent();
17546 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17547 const TargetInstrInfo *TII,
17548 const X86Subtarget* Subtarget) {
17549 DebugLoc dl = MI->getDebugLoc();
17551 // Address into RAX/EAX, other two args into ECX, EDX.
17552 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17553 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17554 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17555 for (int i = 0; i < X86::AddrNumOperands; ++i)
17556 MIB.addOperand(MI->getOperand(i));
17558 unsigned ValOps = X86::AddrNumOperands;
17559 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17560 .addReg(MI->getOperand(ValOps).getReg());
17561 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17562 .addReg(MI->getOperand(ValOps+1).getReg());
17564 // The instruction doesn't actually take any operands though.
17565 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17567 MI->eraseFromParent(); // The pseudo is gone now.
17571 MachineBasicBlock *
17572 X86TargetLowering::EmitVAARG64WithCustomInserter(
17574 MachineBasicBlock *MBB) const {
17575 // Emit va_arg instruction on X86-64.
17577 // Operands to this pseudo-instruction:
17578 // 0 ) Output : destination address (reg)
17579 // 1-5) Input : va_list address (addr, i64mem)
17580 // 6 ) ArgSize : Size (in bytes) of vararg type
17581 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17582 // 8 ) Align : Alignment of type
17583 // 9 ) EFLAGS (implicit-def)
17585 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17586 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17588 unsigned DestReg = MI->getOperand(0).getReg();
17589 MachineOperand &Base = MI->getOperand(1);
17590 MachineOperand &Scale = MI->getOperand(2);
17591 MachineOperand &Index = MI->getOperand(3);
17592 MachineOperand &Disp = MI->getOperand(4);
17593 MachineOperand &Segment = MI->getOperand(5);
17594 unsigned ArgSize = MI->getOperand(6).getImm();
17595 unsigned ArgMode = MI->getOperand(7).getImm();
17596 unsigned Align = MI->getOperand(8).getImm();
17598 // Memory Reference
17599 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17600 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17601 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17603 // Machine Information
17604 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17605 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17606 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17607 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17608 DebugLoc DL = MI->getDebugLoc();
17610 // struct va_list {
17613 // i64 overflow_area (address)
17614 // i64 reg_save_area (address)
17616 // sizeof(va_list) = 24
17617 // alignment(va_list) = 8
17619 unsigned TotalNumIntRegs = 6;
17620 unsigned TotalNumXMMRegs = 8;
17621 bool UseGPOffset = (ArgMode == 1);
17622 bool UseFPOffset = (ArgMode == 2);
17623 unsigned MaxOffset = TotalNumIntRegs * 8 +
17624 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17626 /* Align ArgSize to a multiple of 8 */
17627 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17628 bool NeedsAlign = (Align > 8);
17630 MachineBasicBlock *thisMBB = MBB;
17631 MachineBasicBlock *overflowMBB;
17632 MachineBasicBlock *offsetMBB;
17633 MachineBasicBlock *endMBB;
17635 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17636 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17637 unsigned OffsetReg = 0;
17639 if (!UseGPOffset && !UseFPOffset) {
17640 // If we only pull from the overflow region, we don't create a branch.
17641 // We don't need to alter control flow.
17642 OffsetDestReg = 0; // unused
17643 OverflowDestReg = DestReg;
17645 offsetMBB = nullptr;
17646 overflowMBB = thisMBB;
17649 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17650 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17651 // If not, pull from overflow_area. (branch to overflowMBB)
17656 // offsetMBB overflowMBB
17661 // Registers for the PHI in endMBB
17662 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17663 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17665 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17666 MachineFunction *MF = MBB->getParent();
17667 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17668 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17669 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17671 MachineFunction::iterator MBBIter = MBB;
17674 // Insert the new basic blocks
17675 MF->insert(MBBIter, offsetMBB);
17676 MF->insert(MBBIter, overflowMBB);
17677 MF->insert(MBBIter, endMBB);
17679 // Transfer the remainder of MBB and its successor edges to endMBB.
17680 endMBB->splice(endMBB->begin(), thisMBB,
17681 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17682 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17684 // Make offsetMBB and overflowMBB successors of thisMBB
17685 thisMBB->addSuccessor(offsetMBB);
17686 thisMBB->addSuccessor(overflowMBB);
17688 // endMBB is a successor of both offsetMBB and overflowMBB
17689 offsetMBB->addSuccessor(endMBB);
17690 overflowMBB->addSuccessor(endMBB);
17692 // Load the offset value into a register
17693 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17694 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17698 .addDisp(Disp, UseFPOffset ? 4 : 0)
17699 .addOperand(Segment)
17700 .setMemRefs(MMOBegin, MMOEnd);
17702 // Check if there is enough room left to pull this argument.
17703 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17705 .addImm(MaxOffset + 8 - ArgSizeA8);
17707 // Branch to "overflowMBB" if offset >= max
17708 // Fall through to "offsetMBB" otherwise
17709 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17710 .addMBB(overflowMBB);
17713 // In offsetMBB, emit code to use the reg_save_area.
17715 assert(OffsetReg != 0);
17717 // Read the reg_save_area address.
17718 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17719 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17724 .addOperand(Segment)
17725 .setMemRefs(MMOBegin, MMOEnd);
17727 // Zero-extend the offset
17728 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17729 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17732 .addImm(X86::sub_32bit);
17734 // Add the offset to the reg_save_area to get the final address.
17735 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17736 .addReg(OffsetReg64)
17737 .addReg(RegSaveReg);
17739 // Compute the offset for the next argument
17740 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17741 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17743 .addImm(UseFPOffset ? 16 : 8);
17745 // Store it back into the va_list.
17746 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17750 .addDisp(Disp, UseFPOffset ? 4 : 0)
17751 .addOperand(Segment)
17752 .addReg(NextOffsetReg)
17753 .setMemRefs(MMOBegin, MMOEnd);
17756 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17761 // Emit code to use overflow area
17764 // Load the overflow_area address into a register.
17765 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17766 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17771 .addOperand(Segment)
17772 .setMemRefs(MMOBegin, MMOEnd);
17774 // If we need to align it, do so. Otherwise, just copy the address
17775 // to OverflowDestReg.
17777 // Align the overflow address
17778 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17779 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17781 // aligned_addr = (addr + (align-1)) & ~(align-1)
17782 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17783 .addReg(OverflowAddrReg)
17786 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17788 .addImm(~(uint64_t)(Align-1));
17790 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17791 .addReg(OverflowAddrReg);
17794 // Compute the next overflow address after this argument.
17795 // (the overflow address should be kept 8-byte aligned)
17796 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17797 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17798 .addReg(OverflowDestReg)
17799 .addImm(ArgSizeA8);
17801 // Store the new overflow address.
17802 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17807 .addOperand(Segment)
17808 .addReg(NextAddrReg)
17809 .setMemRefs(MMOBegin, MMOEnd);
17811 // If we branched, emit the PHI to the front of endMBB.
17813 BuildMI(*endMBB, endMBB->begin(), DL,
17814 TII->get(X86::PHI), DestReg)
17815 .addReg(OffsetDestReg).addMBB(offsetMBB)
17816 .addReg(OverflowDestReg).addMBB(overflowMBB);
17819 // Erase the pseudo instruction
17820 MI->eraseFromParent();
17825 MachineBasicBlock *
17826 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17828 MachineBasicBlock *MBB) const {
17829 // Emit code to save XMM registers to the stack. The ABI says that the
17830 // number of registers to save is given in %al, so it's theoretically
17831 // possible to do an indirect jump trick to avoid saving all of them,
17832 // however this code takes a simpler approach and just executes all
17833 // of the stores if %al is non-zero. It's less code, and it's probably
17834 // easier on the hardware branch predictor, and stores aren't all that
17835 // expensive anyway.
17837 // Create the new basic blocks. One block contains all the XMM stores,
17838 // and one block is the final destination regardless of whether any
17839 // stores were performed.
17840 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17841 MachineFunction *F = MBB->getParent();
17842 MachineFunction::iterator MBBIter = MBB;
17844 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17845 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17846 F->insert(MBBIter, XMMSaveMBB);
17847 F->insert(MBBIter, EndMBB);
17849 // Transfer the remainder of MBB and its successor edges to EndMBB.
17850 EndMBB->splice(EndMBB->begin(), MBB,
17851 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17852 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17854 // The original block will now fall through to the XMM save block.
17855 MBB->addSuccessor(XMMSaveMBB);
17856 // The XMMSaveMBB will fall through to the end block.
17857 XMMSaveMBB->addSuccessor(EndMBB);
17859 // Now add the instructions.
17860 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17861 DebugLoc DL = MI->getDebugLoc();
17863 unsigned CountReg = MI->getOperand(0).getReg();
17864 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17865 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17867 if (!Subtarget->isTargetWin64()) {
17868 // If %al is 0, branch around the XMM save block.
17869 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17870 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17871 MBB->addSuccessor(EndMBB);
17874 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17875 // that was just emitted, but clearly shouldn't be "saved".
17876 assert((MI->getNumOperands() <= 3 ||
17877 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17878 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17879 && "Expected last argument to be EFLAGS");
17880 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17881 // In the XMM save block, save all the XMM argument registers.
17882 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17883 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17884 MachineMemOperand *MMO =
17885 F->getMachineMemOperand(
17886 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17887 MachineMemOperand::MOStore,
17888 /*Size=*/16, /*Align=*/16);
17889 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17890 .addFrameIndex(RegSaveFrameIndex)
17891 .addImm(/*Scale=*/1)
17892 .addReg(/*IndexReg=*/0)
17893 .addImm(/*Disp=*/Offset)
17894 .addReg(/*Segment=*/0)
17895 .addReg(MI->getOperand(i).getReg())
17896 .addMemOperand(MMO);
17899 MI->eraseFromParent(); // The pseudo instruction is gone now.
17904 // The EFLAGS operand of SelectItr might be missing a kill marker
17905 // because there were multiple uses of EFLAGS, and ISel didn't know
17906 // which to mark. Figure out whether SelectItr should have had a
17907 // kill marker, and set it if it should. Returns the correct kill
17909 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17910 MachineBasicBlock* BB,
17911 const TargetRegisterInfo* TRI) {
17912 // Scan forward through BB for a use/def of EFLAGS.
17913 MachineBasicBlock::iterator miI(std::next(SelectItr));
17914 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17915 const MachineInstr& mi = *miI;
17916 if (mi.readsRegister(X86::EFLAGS))
17918 if (mi.definesRegister(X86::EFLAGS))
17919 break; // Should have kill-flag - update below.
17922 // If we hit the end of the block, check whether EFLAGS is live into a
17924 if (miI == BB->end()) {
17925 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17926 sEnd = BB->succ_end();
17927 sItr != sEnd; ++sItr) {
17928 MachineBasicBlock* succ = *sItr;
17929 if (succ->isLiveIn(X86::EFLAGS))
17934 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17935 // out. SelectMI should have a kill flag on EFLAGS.
17936 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17940 MachineBasicBlock *
17941 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17942 MachineBasicBlock *BB) const {
17943 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
17944 DebugLoc DL = MI->getDebugLoc();
17946 // To "insert" a SELECT_CC instruction, we actually have to insert the
17947 // diamond control-flow pattern. The incoming instruction knows the
17948 // destination vreg to set, the condition code register to branch on, the
17949 // true/false values to select between, and a branch opcode to use.
17950 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17951 MachineFunction::iterator It = BB;
17957 // cmpTY ccX, r1, r2
17959 // fallthrough --> copy0MBB
17960 MachineBasicBlock *thisMBB = BB;
17961 MachineFunction *F = BB->getParent();
17962 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17963 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17964 F->insert(It, copy0MBB);
17965 F->insert(It, sinkMBB);
17967 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17968 // live into the sink and copy blocks.
17969 const TargetRegisterInfo *TRI =
17970 BB->getParent()->getSubtarget().getRegisterInfo();
17971 if (!MI->killsRegister(X86::EFLAGS) &&
17972 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17973 copy0MBB->addLiveIn(X86::EFLAGS);
17974 sinkMBB->addLiveIn(X86::EFLAGS);
17977 // Transfer the remainder of BB and its successor edges to sinkMBB.
17978 sinkMBB->splice(sinkMBB->begin(), BB,
17979 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17980 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17982 // Add the true and fallthrough blocks as its successors.
17983 BB->addSuccessor(copy0MBB);
17984 BB->addSuccessor(sinkMBB);
17986 // Create the conditional branch instruction.
17988 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17989 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17992 // %FalseValue = ...
17993 // # fallthrough to sinkMBB
17994 copy0MBB->addSuccessor(sinkMBB);
17997 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17999 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18000 TII->get(X86::PHI), MI->getOperand(0).getReg())
18001 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18002 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18004 MI->eraseFromParent(); // The pseudo instruction is gone now.
18008 MachineBasicBlock *
18009 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18010 bool Is64Bit) const {
18011 MachineFunction *MF = BB->getParent();
18012 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18013 DebugLoc DL = MI->getDebugLoc();
18014 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18016 assert(MF->shouldSplitStack());
18018 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18019 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18022 // ... [Till the alloca]
18023 // If stacklet is not large enough, jump to mallocMBB
18026 // Allocate by subtracting from RSP
18027 // Jump to continueMBB
18030 // Allocate by call to runtime
18034 // [rest of original BB]
18037 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18038 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18039 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18041 MachineRegisterInfo &MRI = MF->getRegInfo();
18042 const TargetRegisterClass *AddrRegClass =
18043 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18045 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18046 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18047 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18048 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18049 sizeVReg = MI->getOperand(1).getReg(),
18050 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18052 MachineFunction::iterator MBBIter = BB;
18055 MF->insert(MBBIter, bumpMBB);
18056 MF->insert(MBBIter, mallocMBB);
18057 MF->insert(MBBIter, continueMBB);
18059 continueMBB->splice(continueMBB->begin(), BB,
18060 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18061 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18063 // Add code to the main basic block to check if the stack limit has been hit,
18064 // and if so, jump to mallocMBB otherwise to bumpMBB.
18065 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18066 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18067 .addReg(tmpSPVReg).addReg(sizeVReg);
18068 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18069 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18070 .addReg(SPLimitVReg);
18071 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18073 // bumpMBB simply decreases the stack pointer, since we know the current
18074 // stacklet has enough space.
18075 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18076 .addReg(SPLimitVReg);
18077 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18078 .addReg(SPLimitVReg);
18079 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18081 // Calls into a routine in libgcc to allocate more space from the heap.
18082 const uint32_t *RegMask = MF->getTarget()
18083 .getSubtargetImpl()
18084 ->getRegisterInfo()
18085 ->getCallPreservedMask(CallingConv::C);
18087 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18089 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18090 .addExternalSymbol("__morestack_allocate_stack_space")
18091 .addRegMask(RegMask)
18092 .addReg(X86::RDI, RegState::Implicit)
18093 .addReg(X86::RAX, RegState::ImplicitDefine);
18095 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18097 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18098 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18099 .addExternalSymbol("__morestack_allocate_stack_space")
18100 .addRegMask(RegMask)
18101 .addReg(X86::EAX, RegState::ImplicitDefine);
18105 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18108 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18109 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18110 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18112 // Set up the CFG correctly.
18113 BB->addSuccessor(bumpMBB);
18114 BB->addSuccessor(mallocMBB);
18115 mallocMBB->addSuccessor(continueMBB);
18116 bumpMBB->addSuccessor(continueMBB);
18118 // Take care of the PHI nodes.
18119 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18120 MI->getOperand(0).getReg())
18121 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18122 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18124 // Delete the original pseudo instruction.
18125 MI->eraseFromParent();
18128 return continueMBB;
18131 MachineBasicBlock *
18132 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18133 MachineBasicBlock *BB) const {
18134 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18135 DebugLoc DL = MI->getDebugLoc();
18137 assert(!Subtarget->isTargetMacho());
18139 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18140 // non-trivial part is impdef of ESP.
18142 if (Subtarget->isTargetWin64()) {
18143 if (Subtarget->isTargetCygMing()) {
18144 // ___chkstk(Mingw64):
18145 // Clobbers R10, R11, RAX and EFLAGS.
18147 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18148 .addExternalSymbol("___chkstk")
18149 .addReg(X86::RAX, RegState::Implicit)
18150 .addReg(X86::RSP, RegState::Implicit)
18151 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18152 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18153 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18155 // __chkstk(MSVCRT): does not update stack pointer.
18156 // Clobbers R10, R11 and EFLAGS.
18157 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18158 .addExternalSymbol("__chkstk")
18159 .addReg(X86::RAX, RegState::Implicit)
18160 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18161 // RAX has the offset to be subtracted from RSP.
18162 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18167 const char *StackProbeSymbol =
18168 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18170 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18171 .addExternalSymbol(StackProbeSymbol)
18172 .addReg(X86::EAX, RegState::Implicit)
18173 .addReg(X86::ESP, RegState::Implicit)
18174 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18175 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18176 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18179 MI->eraseFromParent(); // The pseudo instruction is gone now.
18183 MachineBasicBlock *
18184 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18185 MachineBasicBlock *BB) const {
18186 // This is pretty easy. We're taking the value that we received from
18187 // our load from the relocation, sticking it in either RDI (x86-64)
18188 // or EAX and doing an indirect call. The return value will then
18189 // be in the normal return register.
18190 MachineFunction *F = BB->getParent();
18191 const X86InstrInfo *TII =
18192 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18193 DebugLoc DL = MI->getDebugLoc();
18195 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18196 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18198 // Get a register mask for the lowered call.
18199 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18200 // proper register mask.
18201 const uint32_t *RegMask = F->getTarget()
18202 .getSubtargetImpl()
18203 ->getRegisterInfo()
18204 ->getCallPreservedMask(CallingConv::C);
18205 if (Subtarget->is64Bit()) {
18206 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18207 TII->get(X86::MOV64rm), X86::RDI)
18209 .addImm(0).addReg(0)
18210 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18211 MI->getOperand(3).getTargetFlags())
18213 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18214 addDirectMem(MIB, X86::RDI);
18215 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18216 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18217 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18218 TII->get(X86::MOV32rm), X86::EAX)
18220 .addImm(0).addReg(0)
18221 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18222 MI->getOperand(3).getTargetFlags())
18224 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18225 addDirectMem(MIB, X86::EAX);
18226 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18228 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18229 TII->get(X86::MOV32rm), X86::EAX)
18230 .addReg(TII->getGlobalBaseReg(F))
18231 .addImm(0).addReg(0)
18232 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18233 MI->getOperand(3).getTargetFlags())
18235 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18236 addDirectMem(MIB, X86::EAX);
18237 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18240 MI->eraseFromParent(); // The pseudo instruction is gone now.
18244 MachineBasicBlock *
18245 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18246 MachineBasicBlock *MBB) const {
18247 DebugLoc DL = MI->getDebugLoc();
18248 MachineFunction *MF = MBB->getParent();
18249 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18250 MachineRegisterInfo &MRI = MF->getRegInfo();
18252 const BasicBlock *BB = MBB->getBasicBlock();
18253 MachineFunction::iterator I = MBB;
18256 // Memory Reference
18257 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18258 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18261 unsigned MemOpndSlot = 0;
18263 unsigned CurOp = 0;
18265 DstReg = MI->getOperand(CurOp++).getReg();
18266 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18267 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18268 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18269 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18271 MemOpndSlot = CurOp;
18273 MVT PVT = getPointerTy();
18274 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18275 "Invalid Pointer Size!");
18277 // For v = setjmp(buf), we generate
18280 // buf[LabelOffset] = restoreMBB
18281 // SjLjSetup restoreMBB
18287 // v = phi(main, restore)
18292 MachineBasicBlock *thisMBB = MBB;
18293 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18294 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18295 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18296 MF->insert(I, mainMBB);
18297 MF->insert(I, sinkMBB);
18298 MF->push_back(restoreMBB);
18300 MachineInstrBuilder MIB;
18302 // Transfer the remainder of BB and its successor edges to sinkMBB.
18303 sinkMBB->splice(sinkMBB->begin(), MBB,
18304 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18305 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18308 unsigned PtrStoreOpc = 0;
18309 unsigned LabelReg = 0;
18310 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18311 Reloc::Model RM = MF->getTarget().getRelocationModel();
18312 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18313 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18315 // Prepare IP either in reg or imm.
18316 if (!UseImmLabel) {
18317 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18318 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18319 LabelReg = MRI.createVirtualRegister(PtrRC);
18320 if (Subtarget->is64Bit()) {
18321 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18325 .addMBB(restoreMBB)
18328 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18329 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18330 .addReg(XII->getGlobalBaseReg(MF))
18333 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18337 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18339 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18340 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18341 if (i == X86::AddrDisp)
18342 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18344 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18347 MIB.addReg(LabelReg);
18349 MIB.addMBB(restoreMBB);
18350 MIB.setMemRefs(MMOBegin, MMOEnd);
18352 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18353 .addMBB(restoreMBB);
18355 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18356 MF->getSubtarget().getRegisterInfo());
18357 MIB.addRegMask(RegInfo->getNoPreservedMask());
18358 thisMBB->addSuccessor(mainMBB);
18359 thisMBB->addSuccessor(restoreMBB);
18363 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18364 mainMBB->addSuccessor(sinkMBB);
18367 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18368 TII->get(X86::PHI), DstReg)
18369 .addReg(mainDstReg).addMBB(mainMBB)
18370 .addReg(restoreDstReg).addMBB(restoreMBB);
18373 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18374 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18375 restoreMBB->addSuccessor(sinkMBB);
18377 MI->eraseFromParent();
18381 MachineBasicBlock *
18382 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18383 MachineBasicBlock *MBB) const {
18384 DebugLoc DL = MI->getDebugLoc();
18385 MachineFunction *MF = MBB->getParent();
18386 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18387 MachineRegisterInfo &MRI = MF->getRegInfo();
18389 // Memory Reference
18390 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18391 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18393 MVT PVT = getPointerTy();
18394 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18395 "Invalid Pointer Size!");
18397 const TargetRegisterClass *RC =
18398 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18399 unsigned Tmp = MRI.createVirtualRegister(RC);
18400 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18401 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18402 MF->getSubtarget().getRegisterInfo());
18403 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18404 unsigned SP = RegInfo->getStackRegister();
18406 MachineInstrBuilder MIB;
18408 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18409 const int64_t SPOffset = 2 * PVT.getStoreSize();
18411 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18412 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18415 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18416 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18417 MIB.addOperand(MI->getOperand(i));
18418 MIB.setMemRefs(MMOBegin, MMOEnd);
18420 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18421 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18422 if (i == X86::AddrDisp)
18423 MIB.addDisp(MI->getOperand(i), LabelOffset);
18425 MIB.addOperand(MI->getOperand(i));
18427 MIB.setMemRefs(MMOBegin, MMOEnd);
18429 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18430 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18431 if (i == X86::AddrDisp)
18432 MIB.addDisp(MI->getOperand(i), SPOffset);
18434 MIB.addOperand(MI->getOperand(i));
18436 MIB.setMemRefs(MMOBegin, MMOEnd);
18438 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18440 MI->eraseFromParent();
18444 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18445 // accumulator loops. Writing back to the accumulator allows the coalescer
18446 // to remove extra copies in the loop.
18447 MachineBasicBlock *
18448 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18449 MachineBasicBlock *MBB) const {
18450 MachineOperand &AddendOp = MI->getOperand(3);
18452 // Bail out early if the addend isn't a register - we can't switch these.
18453 if (!AddendOp.isReg())
18456 MachineFunction &MF = *MBB->getParent();
18457 MachineRegisterInfo &MRI = MF.getRegInfo();
18459 // Check whether the addend is defined by a PHI:
18460 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18461 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18462 if (!AddendDef.isPHI())
18465 // Look for the following pattern:
18467 // %addend = phi [%entry, 0], [%loop, %result]
18469 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18473 // %addend = phi [%entry, 0], [%loop, %result]
18475 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18477 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18478 assert(AddendDef.getOperand(i).isReg());
18479 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18480 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18481 if (&PHISrcInst == MI) {
18482 // Found a matching instruction.
18483 unsigned NewFMAOpc = 0;
18484 switch (MI->getOpcode()) {
18485 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18486 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18487 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18488 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18489 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18490 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18491 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18492 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18493 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18494 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18495 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18496 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18497 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18498 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18499 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18500 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18501 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18502 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18503 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18504 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18505 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18506 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18507 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18508 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18509 default: llvm_unreachable("Unrecognized FMA variant.");
18512 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18513 MachineInstrBuilder MIB =
18514 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18515 .addOperand(MI->getOperand(0))
18516 .addOperand(MI->getOperand(3))
18517 .addOperand(MI->getOperand(2))
18518 .addOperand(MI->getOperand(1));
18519 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18520 MI->eraseFromParent();
18527 MachineBasicBlock *
18528 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18529 MachineBasicBlock *BB) const {
18530 switch (MI->getOpcode()) {
18531 default: llvm_unreachable("Unexpected instr type to insert");
18532 case X86::TAILJMPd64:
18533 case X86::TAILJMPr64:
18534 case X86::TAILJMPm64:
18535 llvm_unreachable("TAILJMP64 would not be touched here.");
18536 case X86::TCRETURNdi64:
18537 case X86::TCRETURNri64:
18538 case X86::TCRETURNmi64:
18540 case X86::WIN_ALLOCA:
18541 return EmitLoweredWinAlloca(MI, BB);
18542 case X86::SEG_ALLOCA_32:
18543 return EmitLoweredSegAlloca(MI, BB, false);
18544 case X86::SEG_ALLOCA_64:
18545 return EmitLoweredSegAlloca(MI, BB, true);
18546 case X86::TLSCall_32:
18547 case X86::TLSCall_64:
18548 return EmitLoweredTLSCall(MI, BB);
18549 case X86::CMOV_GR8:
18550 case X86::CMOV_FR32:
18551 case X86::CMOV_FR64:
18552 case X86::CMOV_V4F32:
18553 case X86::CMOV_V2F64:
18554 case X86::CMOV_V2I64:
18555 case X86::CMOV_V8F32:
18556 case X86::CMOV_V4F64:
18557 case X86::CMOV_V4I64:
18558 case X86::CMOV_V16F32:
18559 case X86::CMOV_V8F64:
18560 case X86::CMOV_V8I64:
18561 case X86::CMOV_GR16:
18562 case X86::CMOV_GR32:
18563 case X86::CMOV_RFP32:
18564 case X86::CMOV_RFP64:
18565 case X86::CMOV_RFP80:
18566 return EmitLoweredSelect(MI, BB);
18568 case X86::FP32_TO_INT16_IN_MEM:
18569 case X86::FP32_TO_INT32_IN_MEM:
18570 case X86::FP32_TO_INT64_IN_MEM:
18571 case X86::FP64_TO_INT16_IN_MEM:
18572 case X86::FP64_TO_INT32_IN_MEM:
18573 case X86::FP64_TO_INT64_IN_MEM:
18574 case X86::FP80_TO_INT16_IN_MEM:
18575 case X86::FP80_TO_INT32_IN_MEM:
18576 case X86::FP80_TO_INT64_IN_MEM: {
18577 MachineFunction *F = BB->getParent();
18578 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18579 DebugLoc DL = MI->getDebugLoc();
18581 // Change the floating point control register to use "round towards zero"
18582 // mode when truncating to an integer value.
18583 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18584 addFrameReference(BuildMI(*BB, MI, DL,
18585 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18587 // Load the old value of the high byte of the control word...
18589 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18590 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18593 // Set the high part to be round to zero...
18594 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18597 // Reload the modified control word now...
18598 addFrameReference(BuildMI(*BB, MI, DL,
18599 TII->get(X86::FLDCW16m)), CWFrameIdx);
18601 // Restore the memory image of control word to original value
18602 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18605 // Get the X86 opcode to use.
18607 switch (MI->getOpcode()) {
18608 default: llvm_unreachable("illegal opcode!");
18609 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18610 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18611 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18612 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18613 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18614 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18615 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18616 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18617 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18621 MachineOperand &Op = MI->getOperand(0);
18623 AM.BaseType = X86AddressMode::RegBase;
18624 AM.Base.Reg = Op.getReg();
18626 AM.BaseType = X86AddressMode::FrameIndexBase;
18627 AM.Base.FrameIndex = Op.getIndex();
18629 Op = MI->getOperand(1);
18631 AM.Scale = Op.getImm();
18632 Op = MI->getOperand(2);
18634 AM.IndexReg = Op.getImm();
18635 Op = MI->getOperand(3);
18636 if (Op.isGlobal()) {
18637 AM.GV = Op.getGlobal();
18639 AM.Disp = Op.getImm();
18641 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18642 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18644 // Reload the original control word now.
18645 addFrameReference(BuildMI(*BB, MI, DL,
18646 TII->get(X86::FLDCW16m)), CWFrameIdx);
18648 MI->eraseFromParent(); // The pseudo instruction is gone now.
18651 // String/text processing lowering.
18652 case X86::PCMPISTRM128REG:
18653 case X86::VPCMPISTRM128REG:
18654 case X86::PCMPISTRM128MEM:
18655 case X86::VPCMPISTRM128MEM:
18656 case X86::PCMPESTRM128REG:
18657 case X86::VPCMPESTRM128REG:
18658 case X86::PCMPESTRM128MEM:
18659 case X86::VPCMPESTRM128MEM:
18660 assert(Subtarget->hasSSE42() &&
18661 "Target must have SSE4.2 or AVX features enabled");
18662 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18664 // String/text processing lowering.
18665 case X86::PCMPISTRIREG:
18666 case X86::VPCMPISTRIREG:
18667 case X86::PCMPISTRIMEM:
18668 case X86::VPCMPISTRIMEM:
18669 case X86::PCMPESTRIREG:
18670 case X86::VPCMPESTRIREG:
18671 case X86::PCMPESTRIMEM:
18672 case X86::VPCMPESTRIMEM:
18673 assert(Subtarget->hasSSE42() &&
18674 "Target must have SSE4.2 or AVX features enabled");
18675 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18677 // Thread synchronization.
18679 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18684 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18686 case X86::VASTART_SAVE_XMM_REGS:
18687 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18689 case X86::VAARG_64:
18690 return EmitVAARG64WithCustomInserter(MI, BB);
18692 case X86::EH_SjLj_SetJmp32:
18693 case X86::EH_SjLj_SetJmp64:
18694 return emitEHSjLjSetJmp(MI, BB);
18696 case X86::EH_SjLj_LongJmp32:
18697 case X86::EH_SjLj_LongJmp64:
18698 return emitEHSjLjLongJmp(MI, BB);
18700 case TargetOpcode::STACKMAP:
18701 case TargetOpcode::PATCHPOINT:
18702 return emitPatchPoint(MI, BB);
18704 case X86::VFMADDPDr213r:
18705 case X86::VFMADDPSr213r:
18706 case X86::VFMADDSDr213r:
18707 case X86::VFMADDSSr213r:
18708 case X86::VFMSUBPDr213r:
18709 case X86::VFMSUBPSr213r:
18710 case X86::VFMSUBSDr213r:
18711 case X86::VFMSUBSSr213r:
18712 case X86::VFNMADDPDr213r:
18713 case X86::VFNMADDPSr213r:
18714 case X86::VFNMADDSDr213r:
18715 case X86::VFNMADDSSr213r:
18716 case X86::VFNMSUBPDr213r:
18717 case X86::VFNMSUBPSr213r:
18718 case X86::VFNMSUBSDr213r:
18719 case X86::VFNMSUBSSr213r:
18720 case X86::VFMADDPDr213rY:
18721 case X86::VFMADDPSr213rY:
18722 case X86::VFMSUBPDr213rY:
18723 case X86::VFMSUBPSr213rY:
18724 case X86::VFNMADDPDr213rY:
18725 case X86::VFNMADDPSr213rY:
18726 case X86::VFNMSUBPDr213rY:
18727 case X86::VFNMSUBPSr213rY:
18728 return emitFMA3Instr(MI, BB);
18732 //===----------------------------------------------------------------------===//
18733 // X86 Optimization Hooks
18734 //===----------------------------------------------------------------------===//
18736 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18739 const SelectionDAG &DAG,
18740 unsigned Depth) const {
18741 unsigned BitWidth = KnownZero.getBitWidth();
18742 unsigned Opc = Op.getOpcode();
18743 assert((Opc >= ISD::BUILTIN_OP_END ||
18744 Opc == ISD::INTRINSIC_WO_CHAIN ||
18745 Opc == ISD::INTRINSIC_W_CHAIN ||
18746 Opc == ISD::INTRINSIC_VOID) &&
18747 "Should use MaskedValueIsZero if you don't know whether Op"
18748 " is a target node!");
18750 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18764 // These nodes' second result is a boolean.
18765 if (Op.getResNo() == 0)
18768 case X86ISD::SETCC:
18769 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18771 case ISD::INTRINSIC_WO_CHAIN: {
18772 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18773 unsigned NumLoBits = 0;
18776 case Intrinsic::x86_sse_movmsk_ps:
18777 case Intrinsic::x86_avx_movmsk_ps_256:
18778 case Intrinsic::x86_sse2_movmsk_pd:
18779 case Intrinsic::x86_avx_movmsk_pd_256:
18780 case Intrinsic::x86_mmx_pmovmskb:
18781 case Intrinsic::x86_sse2_pmovmskb_128:
18782 case Intrinsic::x86_avx2_pmovmskb: {
18783 // High bits of movmskp{s|d}, pmovmskb are known zero.
18785 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18786 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18787 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18788 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18789 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18790 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18791 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18792 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18794 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18803 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18805 const SelectionDAG &,
18806 unsigned Depth) const {
18807 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18808 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18809 return Op.getValueType().getScalarType().getSizeInBits();
18815 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18816 /// node is a GlobalAddress + offset.
18817 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18818 const GlobalValue* &GA,
18819 int64_t &Offset) const {
18820 if (N->getOpcode() == X86ISD::Wrapper) {
18821 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18822 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18823 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18827 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18830 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18831 /// same as extracting the high 128-bit part of 256-bit vector and then
18832 /// inserting the result into the low part of a new 256-bit vector
18833 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18834 EVT VT = SVOp->getValueType(0);
18835 unsigned NumElems = VT.getVectorNumElements();
18837 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18838 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18839 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18840 SVOp->getMaskElt(j) >= 0)
18846 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18847 /// same as extracting the low 128-bit part of 256-bit vector and then
18848 /// inserting the result into the high part of a new 256-bit vector
18849 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18850 EVT VT = SVOp->getValueType(0);
18851 unsigned NumElems = VT.getVectorNumElements();
18853 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18854 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18855 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18856 SVOp->getMaskElt(j) >= 0)
18862 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18863 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18864 TargetLowering::DAGCombinerInfo &DCI,
18865 const X86Subtarget* Subtarget) {
18867 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18868 SDValue V1 = SVOp->getOperand(0);
18869 SDValue V2 = SVOp->getOperand(1);
18870 EVT VT = SVOp->getValueType(0);
18871 unsigned NumElems = VT.getVectorNumElements();
18873 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18874 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18878 // V UNDEF BUILD_VECTOR UNDEF
18880 // CONCAT_VECTOR CONCAT_VECTOR
18883 // RESULT: V + zero extended
18885 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18886 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18887 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18890 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18893 // To match the shuffle mask, the first half of the mask should
18894 // be exactly the first vector, and all the rest a splat with the
18895 // first element of the second one.
18896 for (unsigned i = 0; i != NumElems/2; ++i)
18897 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18898 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18901 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18902 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18903 if (Ld->hasNUsesOfValue(1, 0)) {
18904 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18905 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18907 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18909 Ld->getPointerInfo(),
18910 Ld->getAlignment(),
18911 false/*isVolatile*/, true/*ReadMem*/,
18912 false/*WriteMem*/);
18914 // Make sure the newly-created LOAD is in the same position as Ld in
18915 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18916 // and update uses of Ld's output chain to use the TokenFactor.
18917 if (Ld->hasAnyUseOfValue(1)) {
18918 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18919 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18920 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18921 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18922 SDValue(ResNode.getNode(), 1));
18925 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18929 // Emit a zeroed vector and insert the desired subvector on its
18931 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18932 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18933 return DCI.CombineTo(N, InsV);
18936 //===--------------------------------------------------------------------===//
18937 // Combine some shuffles into subvector extracts and inserts:
18940 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18941 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18942 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18943 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18944 return DCI.CombineTo(N, InsV);
18947 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18948 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18949 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18950 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18951 return DCI.CombineTo(N, InsV);
18957 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18960 /// This is the leaf of the recursive combinine below. When we have found some
18961 /// chain of single-use x86 shuffle instructions and accumulated the combined
18962 /// shuffle mask represented by them, this will try to pattern match that mask
18963 /// into either a single instruction if there is a special purpose instruction
18964 /// for this operation, or into a PSHUFB instruction which is a fully general
18965 /// instruction but should only be used to replace chains over a certain depth.
18966 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18967 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
18968 TargetLowering::DAGCombinerInfo &DCI,
18969 const X86Subtarget *Subtarget) {
18970 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18972 // Find the operand that enters the chain. Note that multiple uses are OK
18973 // here, we're not going to remove the operand we find.
18974 SDValue Input = Op.getOperand(0);
18975 while (Input.getOpcode() == ISD::BITCAST)
18976 Input = Input.getOperand(0);
18978 MVT VT = Input.getSimpleValueType();
18979 MVT RootVT = Root.getSimpleValueType();
18982 // Just remove no-op shuffle masks.
18983 if (Mask.size() == 1) {
18984 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18989 // Use the float domain if the operand type is a floating point type.
18990 bool FloatDomain = VT.isFloatingPoint();
18992 // If we don't have access to VEX encodings, the generic PSHUF instructions
18993 // are preferable to some of the specialized forms despite requiring one more
18994 // byte to encode because they can implicitly copy.
18996 // IF we *do* have VEX encodings, than we can use shorter, more specific
18997 // shuffle instructions freely as they can copy due to the extra register
18999 if (Subtarget->hasAVX()) {
19000 // We have both floating point and integer variants of shuffles that dup
19001 // either the low or high half of the vector.
19002 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19003 bool Lo = Mask.equals(0, 0);
19004 unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19005 : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19006 if (Depth == 1 && Root->getOpcode() == Shuffle)
19007 return false; // Nothing to do!
19008 MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19009 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19010 DCI.AddToWorklist(Op.getNode());
19011 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19012 DCI.AddToWorklist(Op.getNode());
19013 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19018 // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19020 // For the integer domain we have specialized instructions for duplicating
19021 // any element size from the low or high half.
19022 if (!FloatDomain &&
19023 (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19024 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19025 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19026 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19027 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19029 bool Lo = Mask[0] == 0;
19030 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19031 if (Depth == 1 && Root->getOpcode() == Shuffle)
19032 return false; // Nothing to do!
19034 switch (Mask.size()) {
19035 case 4: ShuffleVT = MVT::v4i32; break;
19036 case 8: ShuffleVT = MVT::v8i16; break;
19037 case 16: ShuffleVT = MVT::v16i8; break;
19039 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19040 DCI.AddToWorklist(Op.getNode());
19041 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19042 DCI.AddToWorklist(Op.getNode());
19043 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19049 // Don't try to re-form single instruction chains under any circumstances now
19050 // that we've done encoding canonicalization for them.
19054 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19055 // can replace them with a single PSHUFB instruction profitably. Intel's
19056 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19057 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19058 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19059 SmallVector<SDValue, 16> PSHUFBMask;
19060 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19061 int Ratio = 16 / Mask.size();
19062 for (unsigned i = 0; i < 16; ++i) {
19063 int M = Ratio * Mask[i / Ratio] + i % Ratio;
19064 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19066 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19067 DCI.AddToWorklist(Op.getNode());
19068 SDValue PSHUFBMaskOp =
19069 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19070 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19071 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19072 DCI.AddToWorklist(Op.getNode());
19073 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19078 // Failed to find any combines.
19082 /// \brief Fully generic combining of x86 shuffle instructions.
19084 /// This should be the last combine run over the x86 shuffle instructions. Once
19085 /// they have been fully optimized, this will recursively consdier all chains
19086 /// of single-use shuffle instructions, build a generic model of the cumulative
19087 /// shuffle operation, and check for simpler instructions which implement this
19088 /// operation. We use this primarily for two purposes:
19090 /// 1) Collapse generic shuffles to specialized single instructions when
19091 /// equivalent. In most cases, this is just an encoding size win, but
19092 /// sometimes we will collapse multiple generic shuffles into a single
19093 /// special-purpose shuffle.
19094 /// 2) Look for sequences of shuffle instructions with 3 or more total
19095 /// instructions, and replace them with the slightly more expensive SSSE3
19096 /// PSHUFB instruction if available. We do this as the last combining step
19097 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19098 /// a suitable short sequence of other instructions. The PHUFB will either
19099 /// use a register or have to read from memory and so is slightly (but only
19100 /// slightly) more expensive than the other shuffle instructions.
19102 /// Because this is inherently a quadratic operation (for each shuffle in
19103 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19104 /// This should never be an issue in practice as the shuffle lowering doesn't
19105 /// produce sequences of more than 8 instructions.
19107 /// FIXME: We will currently miss some cases where the redundant shuffling
19108 /// would simplify under the threshold for PSHUFB formation because of
19109 /// combine-ordering. To fix this, we should do the redundant instruction
19110 /// combining in this recursive walk.
19111 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19112 ArrayRef<int> IncomingMask, int Depth,
19113 bool HasPSHUFB, SelectionDAG &DAG,
19114 TargetLowering::DAGCombinerInfo &DCI,
19115 const X86Subtarget *Subtarget) {
19116 // Bound the depth of our recursive combine because this is ultimately
19117 // quadratic in nature.
19121 // Directly rip through bitcasts to find the underlying operand.
19122 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19123 Op = Op.getOperand(0);
19125 MVT VT = Op.getSimpleValueType();
19126 if (!VT.isVector())
19127 return false; // Bail if we hit a non-vector.
19128 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19129 // version should be added.
19130 if (VT.getSizeInBits() != 128)
19133 assert(Root.getSimpleValueType().isVector() &&
19134 "Shuffles operate on vector types!");
19135 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19136 "Can only combine shuffles of the same vector register size.");
19138 if (!isTargetShuffle(Op.getOpcode()))
19140 SmallVector<int, 16> OpMask;
19142 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19143 // We only can combine unary shuffles which we can decode the mask for.
19144 if (!HaveMask || !IsUnary)
19147 assert(VT.getVectorNumElements() == OpMask.size() &&
19148 "Different mask size from vector size!");
19150 SmallVector<int, 16> Mask;
19151 Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
19153 // Merge this shuffle operation's mask into our accumulated mask. This is
19154 // a bit tricky as the shuffle may have a different size from the root.
19155 if (OpMask.size() == IncomingMask.size()) {
19156 for (int M : IncomingMask)
19157 Mask.push_back(OpMask[M]);
19158 } else if (OpMask.size() < IncomingMask.size()) {
19159 assert(IncomingMask.size() % OpMask.size() == 0 &&
19160 "The smaller number of elements must divide the larger.");
19161 int Ratio = IncomingMask.size() / OpMask.size();
19162 for (int M : IncomingMask)
19163 Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19165 assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19166 assert(OpMask.size() % IncomingMask.size() == 0 &&
19167 "The smaller number of elements must divide the larger.");
19168 int Ratio = OpMask.size() / IncomingMask.size();
19169 for (int i = 0, e = OpMask.size(); i < e; ++i)
19170 Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19173 // See if we can recurse into the operand to combine more things.
19174 switch (Op.getOpcode()) {
19175 case X86ISD::PSHUFB:
19177 case X86ISD::PSHUFD:
19178 case X86ISD::PSHUFHW:
19179 case X86ISD::PSHUFLW:
19180 if (Op.getOperand(0).hasOneUse() &&
19181 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19182 HasPSHUFB, DAG, DCI, Subtarget))
19186 case X86ISD::UNPCKL:
19187 case X86ISD::UNPCKH:
19188 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19189 // We can't check for single use, we have to check that this shuffle is the only user.
19190 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19191 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19192 HasPSHUFB, DAG, DCI, Subtarget))
19197 // Minor canonicalization of the accumulated shuffle mask to make it easier
19198 // to match below. All this does is detect masks with squential pairs of
19199 // elements, and shrink them to the half-width mask. It does this in a loop
19200 // so it will reduce the size of the mask to the minimal width mask which
19201 // performs an equivalent shuffle.
19202 while (Mask.size() > 1) {
19203 SmallVector<int, 16> NewMask;
19204 for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19205 if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19209 NewMask.push_back(Mask[2*i] / 2);
19211 if (NewMask.empty())
19213 Mask.swap(NewMask);
19216 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19220 /// \brief Get the PSHUF-style mask from PSHUF node.
19222 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19223 /// PSHUF-style masks that can be reused with such instructions.
19224 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19225 SmallVector<int, 4> Mask;
19227 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19231 switch (N.getOpcode()) {
19232 case X86ISD::PSHUFD:
19234 case X86ISD::PSHUFLW:
19237 case X86ISD::PSHUFHW:
19238 Mask.erase(Mask.begin(), Mask.begin() + 4);
19239 for (int &M : Mask)
19243 llvm_unreachable("No valid shuffle instruction found!");
19247 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19249 /// We walk up the chain and look for a combinable shuffle, skipping over
19250 /// shuffles that we could hoist this shuffle's transformation past without
19251 /// altering anything.
19252 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19254 TargetLowering::DAGCombinerInfo &DCI) {
19255 assert(N.getOpcode() == X86ISD::PSHUFD &&
19256 "Called with something other than an x86 128-bit half shuffle!");
19259 // Walk up a single-use chain looking for a combinable shuffle.
19260 SDValue V = N.getOperand(0);
19261 for (; V.hasOneUse(); V = V.getOperand(0)) {
19262 switch (V.getOpcode()) {
19264 return false; // Nothing combined!
19267 // Skip bitcasts as we always know the type for the target specific
19271 case X86ISD::PSHUFD:
19272 // Found another dword shuffle.
19275 case X86ISD::PSHUFLW:
19276 // Check that the low words (being shuffled) are the identity in the
19277 // dword shuffle, and the high words are self-contained.
19278 if (Mask[0] != 0 || Mask[1] != 1 ||
19279 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19284 case X86ISD::PSHUFHW:
19285 // Check that the high words (being shuffled) are the identity in the
19286 // dword shuffle, and the low words are self-contained.
19287 if (Mask[2] != 2 || Mask[3] != 3 ||
19288 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19293 case X86ISD::UNPCKL:
19294 case X86ISD::UNPCKH:
19295 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19296 // shuffle into a preceding word shuffle.
19297 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19300 // Search for a half-shuffle which we can combine with.
19301 unsigned CombineOp =
19302 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19303 if (V.getOperand(0) != V.getOperand(1) ||
19304 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19306 V = V.getOperand(0);
19308 switch (V.getOpcode()) {
19310 return false; // Nothing to combine.
19312 case X86ISD::PSHUFLW:
19313 case X86ISD::PSHUFHW:
19314 if (V.getOpcode() == CombineOp)
19319 V = V.getOperand(0);
19323 } while (V.hasOneUse());
19326 // Break out of the loop if we break out of the switch.
19330 if (!V.hasOneUse())
19331 // We fell out of the loop without finding a viable combining instruction.
19334 // Record the old value to use in RAUW-ing.
19337 // Merge this node's mask and our incoming mask.
19338 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19339 for (int &M : Mask)
19341 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19342 getV4X86ShuffleImm8ForMask(Mask, DAG));
19344 // It is possible that one of the combinable shuffles was completely absorbed
19345 // by the other, just replace it and revisit all users in that case.
19346 if (Old.getNode() == V.getNode()) {
19347 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19351 // Replace N with its operand as we're going to combine that shuffle away.
19352 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19354 // Replace the combinable shuffle with the combined one, updating all users
19355 // so that we re-evaluate the chain here.
19356 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19360 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19362 /// We walk up the chain, skipping shuffles of the other half and looking
19363 /// through shuffles which switch halves trying to find a shuffle of the same
19364 /// pair of dwords.
19365 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19367 TargetLowering::DAGCombinerInfo &DCI) {
19369 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19370 "Called with something other than an x86 128-bit half shuffle!");
19372 unsigned CombineOpcode = N.getOpcode();
19374 // Walk up a single-use chain looking for a combinable shuffle.
19375 SDValue V = N.getOperand(0);
19376 for (; V.hasOneUse(); V = V.getOperand(0)) {
19377 switch (V.getOpcode()) {
19379 return false; // Nothing combined!
19382 // Skip bitcasts as we always know the type for the target specific
19386 case X86ISD::PSHUFLW:
19387 case X86ISD::PSHUFHW:
19388 if (V.getOpcode() == CombineOpcode)
19391 // Other-half shuffles are no-ops.
19394 case X86ISD::PSHUFD: {
19395 // We can only handle pshufd if the half we are combining either stays in
19396 // its half, or switches to the other half. Bail if one of these isn't
19398 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19399 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19400 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19401 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19404 // Map the mask through the pshufd and keep walking up the chain.
19405 for (int i = 0; i < 4; ++i)
19406 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19408 // Switch halves if the pshufd does.
19410 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19414 // Break out of the loop if we break out of the switch.
19418 if (!V.hasOneUse())
19419 // We fell out of the loop without finding a viable combining instruction.
19422 // Record the old value to use in RAUW-ing.
19425 // Merge this node's mask and our incoming mask (adjusted to account for all
19426 // the pshufd instructions encountered).
19427 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19428 for (int &M : Mask)
19430 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19431 getV4X86ShuffleImm8ForMask(Mask, DAG));
19433 // Replace N with its operand as we're going to combine that shuffle away.
19434 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19436 // Replace the combinable shuffle with the combined one, updating all users
19437 // so that we re-evaluate the chain here.
19438 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19442 /// \brief Try to combine x86 target specific shuffles.
19443 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19444 TargetLowering::DAGCombinerInfo &DCI,
19445 const X86Subtarget *Subtarget) {
19447 MVT VT = N.getSimpleValueType();
19448 SmallVector<int, 4> Mask;
19450 switch (N.getOpcode()) {
19451 case X86ISD::PSHUFD:
19452 case X86ISD::PSHUFLW:
19453 case X86ISD::PSHUFHW:
19454 Mask = getPSHUFShuffleMask(N);
19455 assert(Mask.size() == 4);
19461 // Nuke no-op shuffles that show up after combining.
19462 if (isNoopShuffleMask(Mask))
19463 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19465 // Look for simplifications involving one or two shuffle instructions.
19466 SDValue V = N.getOperand(0);
19467 switch (N.getOpcode()) {
19470 case X86ISD::PSHUFLW:
19471 case X86ISD::PSHUFHW:
19472 assert(VT == MVT::v8i16);
19475 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19476 return SDValue(); // We combined away this shuffle, so we're done.
19478 // See if this reduces to a PSHUFD which is no more expensive and can
19479 // combine with more operations.
19480 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19481 areAdjacentMasksSequential(Mask)) {
19482 int DMask[] = {-1, -1, -1, -1};
19483 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19484 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19485 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19486 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19487 DCI.AddToWorklist(V.getNode());
19488 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19489 getV4X86ShuffleImm8ForMask(DMask, DAG));
19490 DCI.AddToWorklist(V.getNode());
19491 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19494 // Look for shuffle patterns which can be implemented as a single unpack.
19495 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19496 // only works when we have a PSHUFD followed by two half-shuffles.
19497 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19498 (V.getOpcode() == X86ISD::PSHUFLW ||
19499 V.getOpcode() == X86ISD::PSHUFHW) &&
19500 V.getOpcode() != N.getOpcode() &&
19502 SDValue D = V.getOperand(0);
19503 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19504 D = D.getOperand(0);
19505 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19506 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19507 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19508 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19509 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19511 for (int i = 0; i < 4; ++i) {
19512 WordMask[i + NOffset] = Mask[i] + NOffset;
19513 WordMask[i + VOffset] = VMask[i] + VOffset;
19515 // Map the word mask through the DWord mask.
19517 for (int i = 0; i < 8; ++i)
19518 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19519 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19520 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19521 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19522 std::begin(UnpackLoMask)) ||
19523 std::equal(std::begin(MappedMask), std::end(MappedMask),
19524 std::begin(UnpackHiMask))) {
19525 // We can replace all three shuffles with an unpack.
19526 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19527 DCI.AddToWorklist(V.getNode());
19528 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19530 DL, MVT::v8i16, V, V);
19537 case X86ISD::PSHUFD:
19538 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19539 return SDValue(); // We combined away this shuffle.
19547 /// PerformShuffleCombine - Performs several different shuffle combines.
19548 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19549 TargetLowering::DAGCombinerInfo &DCI,
19550 const X86Subtarget *Subtarget) {
19552 SDValue N0 = N->getOperand(0);
19553 SDValue N1 = N->getOperand(1);
19554 EVT VT = N->getValueType(0);
19556 // Don't create instructions with illegal types after legalize types has run.
19557 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19558 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19561 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19562 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19563 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19564 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19566 // During Type Legalization, when promoting illegal vector types,
19567 // the backend might introduce new shuffle dag nodes and bitcasts.
19569 // This code performs the following transformation:
19570 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19571 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19573 // We do this only if both the bitcast and the BINOP dag nodes have
19574 // one use. Also, perform this transformation only if the new binary
19575 // operation is legal. This is to avoid introducing dag nodes that
19576 // potentially need to be further expanded (or custom lowered) into a
19577 // less optimal sequence of dag nodes.
19578 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19579 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19580 N0.getOpcode() == ISD::BITCAST) {
19581 SDValue BC0 = N0.getOperand(0);
19582 EVT SVT = BC0.getValueType();
19583 unsigned Opcode = BC0.getOpcode();
19584 unsigned NumElts = VT.getVectorNumElements();
19586 if (BC0.hasOneUse() && SVT.isVector() &&
19587 SVT.getVectorNumElements() * 2 == NumElts &&
19588 TLI.isOperationLegal(Opcode, VT)) {
19589 bool CanFold = false;
19601 unsigned SVTNumElts = SVT.getVectorNumElements();
19602 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19603 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19604 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19605 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19606 CanFold = SVOp->getMaskElt(i) < 0;
19609 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19610 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19611 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19612 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19617 // Only handle 128 wide vector from here on.
19618 if (!VT.is128BitVector())
19621 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19622 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19623 // consecutive, non-overlapping, and in the right order.
19624 SmallVector<SDValue, 16> Elts;
19625 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19626 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19628 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19632 if (isTargetShuffle(N->getOpcode())) {
19634 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19635 if (Shuffle.getNode())
19638 // Try recursively combining arbitrary sequences of x86 shuffle
19639 // instructions into higher-order shuffles. We do this after combining
19640 // specific PSHUF instruction sequences into their minimal form so that we
19641 // can evaluate how many specialized shuffle instructions are involved in
19642 // a particular chain.
19643 SmallVector<int, 1> NonceMask; // Just a placeholder.
19644 NonceMask.push_back(0);
19645 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19646 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19648 return SDValue(); // This routine will use CombineTo to replace N.
19654 /// PerformTruncateCombine - Converts truncate operation to
19655 /// a sequence of vector shuffle operations.
19656 /// It is possible when we truncate 256-bit vector to 128-bit vector
19657 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19658 TargetLowering::DAGCombinerInfo &DCI,
19659 const X86Subtarget *Subtarget) {
19663 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19664 /// specific shuffle of a load can be folded into a single element load.
19665 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19666 /// shuffles have been customed lowered so we need to handle those here.
19667 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19668 TargetLowering::DAGCombinerInfo &DCI) {
19669 if (DCI.isBeforeLegalizeOps())
19672 SDValue InVec = N->getOperand(0);
19673 SDValue EltNo = N->getOperand(1);
19675 if (!isa<ConstantSDNode>(EltNo))
19678 EVT VT = InVec.getValueType();
19680 bool HasShuffleIntoBitcast = false;
19681 if (InVec.getOpcode() == ISD::BITCAST) {
19682 // Don't duplicate a load with other uses.
19683 if (!InVec.hasOneUse())
19685 EVT BCVT = InVec.getOperand(0).getValueType();
19686 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19688 InVec = InVec.getOperand(0);
19689 HasShuffleIntoBitcast = true;
19692 if (!isTargetShuffle(InVec.getOpcode()))
19695 // Don't duplicate a load with other uses.
19696 if (!InVec.hasOneUse())
19699 SmallVector<int, 16> ShuffleMask;
19701 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19705 // Select the input vector, guarding against out of range extract vector.
19706 unsigned NumElems = VT.getVectorNumElements();
19707 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19708 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19709 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19710 : InVec.getOperand(1);
19712 // If inputs to shuffle are the same for both ops, then allow 2 uses
19713 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19715 if (LdNode.getOpcode() == ISD::BITCAST) {
19716 // Don't duplicate a load with other uses.
19717 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19720 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19721 LdNode = LdNode.getOperand(0);
19724 if (!ISD::isNormalLoad(LdNode.getNode()))
19727 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19729 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19732 if (HasShuffleIntoBitcast) {
19733 // If there's a bitcast before the shuffle, check if the load type and
19734 // alignment is valid.
19735 unsigned Align = LN0->getAlignment();
19736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19737 unsigned NewAlign = TLI.getDataLayout()->
19738 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19740 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19744 // All checks match so transform back to vector_shuffle so that DAG combiner
19745 // can finish the job
19748 // Create shuffle node taking into account the case that its a unary shuffle
19749 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19750 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19751 InVec.getOperand(0), Shuffle,
19753 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19754 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19758 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19759 /// generation and convert it from being a bunch of shuffles and extracts
19760 /// to a simple store and scalar loads to extract the elements.
19761 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19762 TargetLowering::DAGCombinerInfo &DCI) {
19763 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19764 if (NewOp.getNode())
19767 SDValue InputVector = N->getOperand(0);
19769 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19770 // from mmx to v2i32 has a single usage.
19771 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19772 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19773 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19774 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19775 N->getValueType(0),
19776 InputVector.getNode()->getOperand(0));
19778 // Only operate on vectors of 4 elements, where the alternative shuffling
19779 // gets to be more expensive.
19780 if (InputVector.getValueType() != MVT::v4i32)
19783 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19784 // single use which is a sign-extend or zero-extend, and all elements are
19786 SmallVector<SDNode *, 4> Uses;
19787 unsigned ExtractedElements = 0;
19788 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19789 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19790 if (UI.getUse().getResNo() != InputVector.getResNo())
19793 SDNode *Extract = *UI;
19794 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19797 if (Extract->getValueType(0) != MVT::i32)
19799 if (!Extract->hasOneUse())
19801 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19802 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19804 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19807 // Record which element was extracted.
19808 ExtractedElements |=
19809 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19811 Uses.push_back(Extract);
19814 // If not all the elements were used, this may not be worthwhile.
19815 if (ExtractedElements != 15)
19818 // Ok, we've now decided to do the transformation.
19819 SDLoc dl(InputVector);
19821 // Store the value to a temporary stack slot.
19822 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19823 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19824 MachinePointerInfo(), false, false, 0);
19826 // Replace each use (extract) with a load of the appropriate element.
19827 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19828 UE = Uses.end(); UI != UE; ++UI) {
19829 SDNode *Extract = *UI;
19831 // cOMpute the element's address.
19832 SDValue Idx = Extract->getOperand(1);
19834 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19835 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19837 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19839 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19840 StackPtr, OffsetVal);
19842 // Load the scalar.
19843 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19844 ScalarAddr, MachinePointerInfo(),
19845 false, false, false, 0);
19847 // Replace the exact with the load.
19848 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19851 // The replacement was made in place; don't return anything.
19855 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19856 static std::pair<unsigned, bool>
19857 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19858 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19859 if (!VT.isVector())
19860 return std::make_pair(0, false);
19862 bool NeedSplit = false;
19863 switch (VT.getSimpleVT().SimpleTy) {
19864 default: return std::make_pair(0, false);
19868 if (!Subtarget->hasAVX2())
19870 if (!Subtarget->hasAVX())
19871 return std::make_pair(0, false);
19876 if (!Subtarget->hasSSE2())
19877 return std::make_pair(0, false);
19880 // SSE2 has only a small subset of the operations.
19881 bool hasUnsigned = Subtarget->hasSSE41() ||
19882 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19883 bool hasSigned = Subtarget->hasSSE41() ||
19884 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19886 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19889 // Check for x CC y ? x : y.
19890 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19891 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19896 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19899 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19902 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19905 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19907 // Check for x CC y ? y : x -- a min/max with reversed arms.
19908 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19909 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19914 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19917 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19920 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19923 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19927 return std::make_pair(Opc, NeedSplit);
19931 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19932 const X86Subtarget *Subtarget) {
19934 SDValue Cond = N->getOperand(0);
19935 SDValue LHS = N->getOperand(1);
19936 SDValue RHS = N->getOperand(2);
19938 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19939 SDValue CondSrc = Cond->getOperand(0);
19940 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19941 Cond = CondSrc->getOperand(0);
19944 MVT VT = N->getSimpleValueType(0);
19945 MVT EltVT = VT.getVectorElementType();
19946 unsigned NumElems = VT.getVectorNumElements();
19947 // There is no blend with immediate in AVX-512.
19948 if (VT.is512BitVector())
19951 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19953 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19956 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19959 unsigned MaskValue = 0;
19960 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19963 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19964 for (unsigned i = 0; i < NumElems; ++i) {
19965 // Be sure we emit undef where we can.
19966 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19967 ShuffleMask[i] = -1;
19969 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19972 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19975 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19977 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19978 TargetLowering::DAGCombinerInfo &DCI,
19979 const X86Subtarget *Subtarget) {
19981 SDValue Cond = N->getOperand(0);
19982 // Get the LHS/RHS of the select.
19983 SDValue LHS = N->getOperand(1);
19984 SDValue RHS = N->getOperand(2);
19985 EVT VT = LHS.getValueType();
19986 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19988 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19989 // instructions match the semantics of the common C idiom x<y?x:y but not
19990 // x<=y?x:y, because of how they handle negative zero (which can be
19991 // ignored in unsafe-math mode).
19992 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19993 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19994 (Subtarget->hasSSE2() ||
19995 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19996 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19998 unsigned Opcode = 0;
19999 // Check for x CC y ? x : y.
20000 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20001 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20005 // Converting this to a min would handle NaNs incorrectly, and swapping
20006 // the operands would cause it to handle comparisons between positive
20007 // and negative zero incorrectly.
20008 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20009 if (!DAG.getTarget().Options.UnsafeFPMath &&
20010 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20012 std::swap(LHS, RHS);
20014 Opcode = X86ISD::FMIN;
20017 // Converting this to a min would handle comparisons between positive
20018 // and negative zero incorrectly.
20019 if (!DAG.getTarget().Options.UnsafeFPMath &&
20020 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20022 Opcode = X86ISD::FMIN;
20025 // Converting this to a min would handle both negative zeros and NaNs
20026 // incorrectly, but we can swap the operands to fix both.
20027 std::swap(LHS, RHS);
20031 Opcode = X86ISD::FMIN;
20035 // Converting this to a max would handle comparisons between positive
20036 // and negative zero incorrectly.
20037 if (!DAG.getTarget().Options.UnsafeFPMath &&
20038 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20040 Opcode = X86ISD::FMAX;
20043 // Converting this to a max would handle NaNs incorrectly, and swapping
20044 // the operands would cause it to handle comparisons between positive
20045 // and negative zero incorrectly.
20046 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20047 if (!DAG.getTarget().Options.UnsafeFPMath &&
20048 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20050 std::swap(LHS, RHS);
20052 Opcode = X86ISD::FMAX;
20055 // Converting this to a max would handle both negative zeros and NaNs
20056 // incorrectly, but we can swap the operands to fix both.
20057 std::swap(LHS, RHS);
20061 Opcode = X86ISD::FMAX;
20064 // Check for x CC y ? y : x -- a min/max with reversed arms.
20065 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20066 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20070 // Converting this to a min would handle comparisons between positive
20071 // and negative zero incorrectly, and swapping the operands would
20072 // cause it to handle NaNs incorrectly.
20073 if (!DAG.getTarget().Options.UnsafeFPMath &&
20074 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20075 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20077 std::swap(LHS, RHS);
20079 Opcode = X86ISD::FMIN;
20082 // Converting this to a min would handle NaNs incorrectly.
20083 if (!DAG.getTarget().Options.UnsafeFPMath &&
20084 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20086 Opcode = X86ISD::FMIN;
20089 // Converting this to a min would handle both negative zeros and NaNs
20090 // incorrectly, but we can swap the operands to fix both.
20091 std::swap(LHS, RHS);
20095 Opcode = X86ISD::FMIN;
20099 // Converting this to a max would handle NaNs incorrectly.
20100 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20102 Opcode = X86ISD::FMAX;
20105 // Converting this to a max would handle comparisons between positive
20106 // and negative zero incorrectly, and swapping the operands would
20107 // cause it to handle NaNs incorrectly.
20108 if (!DAG.getTarget().Options.UnsafeFPMath &&
20109 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20110 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20112 std::swap(LHS, RHS);
20114 Opcode = X86ISD::FMAX;
20117 // Converting this to a max would handle both negative zeros and NaNs
20118 // incorrectly, but we can swap the operands to fix both.
20119 std::swap(LHS, RHS);
20123 Opcode = X86ISD::FMAX;
20129 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20132 EVT CondVT = Cond.getValueType();
20133 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20134 CondVT.getVectorElementType() == MVT::i1) {
20135 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20136 // lowering on AVX-512. In this case we convert it to
20137 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20138 // The same situation for all 128 and 256-bit vectors of i8 and i16
20139 EVT OpVT = LHS.getValueType();
20140 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20141 (OpVT.getVectorElementType() == MVT::i8 ||
20142 OpVT.getVectorElementType() == MVT::i16)) {
20143 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20144 DCI.AddToWorklist(Cond.getNode());
20145 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20148 // If this is a select between two integer constants, try to do some
20150 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20151 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20152 // Don't do this for crazy integer types.
20153 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20154 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20155 // so that TrueC (the true value) is larger than FalseC.
20156 bool NeedsCondInvert = false;
20158 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20159 // Efficiently invertible.
20160 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20161 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20162 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20163 NeedsCondInvert = true;
20164 std::swap(TrueC, FalseC);
20167 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20168 if (FalseC->getAPIntValue() == 0 &&
20169 TrueC->getAPIntValue().isPowerOf2()) {
20170 if (NeedsCondInvert) // Invert the condition if needed.
20171 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20172 DAG.getConstant(1, Cond.getValueType()));
20174 // Zero extend the condition if needed.
20175 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20177 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20178 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20179 DAG.getConstant(ShAmt, MVT::i8));
20182 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20183 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20184 if (NeedsCondInvert) // Invert the condition if needed.
20185 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20186 DAG.getConstant(1, Cond.getValueType()));
20188 // Zero extend the condition if needed.
20189 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20190 FalseC->getValueType(0), Cond);
20191 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20192 SDValue(FalseC, 0));
20195 // Optimize cases that will turn into an LEA instruction. This requires
20196 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20197 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20198 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20199 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20201 bool isFastMultiplier = false;
20203 switch ((unsigned char)Diff) {
20205 case 1: // result = add base, cond
20206 case 2: // result = lea base( , cond*2)
20207 case 3: // result = lea base(cond, cond*2)
20208 case 4: // result = lea base( , cond*4)
20209 case 5: // result = lea base(cond, cond*4)
20210 case 8: // result = lea base( , cond*8)
20211 case 9: // result = lea base(cond, cond*8)
20212 isFastMultiplier = true;
20217 if (isFastMultiplier) {
20218 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20219 if (NeedsCondInvert) // Invert the condition if needed.
20220 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20221 DAG.getConstant(1, Cond.getValueType()));
20223 // Zero extend the condition if needed.
20224 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20226 // Scale the condition by the difference.
20228 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20229 DAG.getConstant(Diff, Cond.getValueType()));
20231 // Add the base if non-zero.
20232 if (FalseC->getAPIntValue() != 0)
20233 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20234 SDValue(FalseC, 0));
20241 // Canonicalize max and min:
20242 // (x > y) ? x : y -> (x >= y) ? x : y
20243 // (x < y) ? x : y -> (x <= y) ? x : y
20244 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20245 // the need for an extra compare
20246 // against zero. e.g.
20247 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20249 // testl %edi, %edi
20251 // cmovgl %edi, %eax
20255 // cmovsl %eax, %edi
20256 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20257 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20258 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20259 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20264 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20265 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20266 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20267 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20272 // Early exit check
20273 if (!TLI.isTypeLegal(VT))
20276 // Match VSELECTs into subs with unsigned saturation.
20277 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20278 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20279 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20280 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20281 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20283 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20284 // left side invert the predicate to simplify logic below.
20286 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20288 CC = ISD::getSetCCInverse(CC, true);
20289 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20293 if (Other.getNode() && Other->getNumOperands() == 2 &&
20294 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20295 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20296 SDValue CondRHS = Cond->getOperand(1);
20298 // Look for a general sub with unsigned saturation first.
20299 // x >= y ? x-y : 0 --> subus x, y
20300 // x > y ? x-y : 0 --> subus x, y
20301 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20302 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20303 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20305 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20306 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20307 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20308 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20309 // If the RHS is a constant we have to reverse the const
20310 // canonicalization.
20311 // x > C-1 ? x+-C : 0 --> subus x, C
20312 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20313 CondRHSConst->getAPIntValue() ==
20314 (-OpRHSConst->getAPIntValue() - 1))
20315 return DAG.getNode(
20316 X86ISD::SUBUS, DL, VT, OpLHS,
20317 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20319 // Another special case: If C was a sign bit, the sub has been
20320 // canonicalized into a xor.
20321 // FIXME: Would it be better to use computeKnownBits to determine
20322 // whether it's safe to decanonicalize the xor?
20323 // x s< 0 ? x^C : 0 --> subus x, C
20324 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20325 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20326 OpRHSConst->getAPIntValue().isSignBit())
20327 // Note that we have to rebuild the RHS constant here to ensure we
20328 // don't rely on particular values of undef lanes.
20329 return DAG.getNode(
20330 X86ISD::SUBUS, DL, VT, OpLHS,
20331 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20336 // Try to match a min/max vector operation.
20337 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20338 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20339 unsigned Opc = ret.first;
20340 bool NeedSplit = ret.second;
20342 if (Opc && NeedSplit) {
20343 unsigned NumElems = VT.getVectorNumElements();
20344 // Extract the LHS vectors
20345 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20346 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20348 // Extract the RHS vectors
20349 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20350 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20352 // Create min/max for each subvector
20353 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20354 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20356 // Merge the result
20357 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20359 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20362 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20363 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20364 // Check if SETCC has already been promoted
20365 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20366 // Check that condition value type matches vselect operand type
20369 assert(Cond.getValueType().isVector() &&
20370 "vector select expects a vector selector!");
20372 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20373 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20375 if (!TValIsAllOnes && !FValIsAllZeros) {
20376 // Try invert the condition if true value is not all 1s and false value
20378 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20379 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20381 if (TValIsAllZeros || FValIsAllOnes) {
20382 SDValue CC = Cond.getOperand(2);
20383 ISD::CondCode NewCC =
20384 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20385 Cond.getOperand(0).getValueType().isInteger());
20386 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20387 std::swap(LHS, RHS);
20388 TValIsAllOnes = FValIsAllOnes;
20389 FValIsAllZeros = TValIsAllZeros;
20393 if (TValIsAllOnes || FValIsAllZeros) {
20396 if (TValIsAllOnes && FValIsAllZeros)
20398 else if (TValIsAllOnes)
20399 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20400 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20401 else if (FValIsAllZeros)
20402 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20403 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20405 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20409 // Try to fold this VSELECT into a MOVSS/MOVSD
20410 if (N->getOpcode() == ISD::VSELECT &&
20411 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20412 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20413 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20414 bool CanFold = false;
20415 unsigned NumElems = Cond.getNumOperands();
20419 if (isZero(Cond.getOperand(0))) {
20422 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20423 // fold (vselect <0,-1> -> (movsd A, B)
20424 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20425 CanFold = isAllOnes(Cond.getOperand(i));
20426 } else if (isAllOnes(Cond.getOperand(0))) {
20430 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20431 // fold (vselect <-1,0> -> (movsd B, A)
20432 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20433 CanFold = isZero(Cond.getOperand(i));
20437 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20438 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20439 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20442 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20443 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20444 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20445 // (v2i64 (bitcast B)))))
20447 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20448 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20449 // (v2f64 (bitcast B)))))
20451 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20452 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20453 // (v2i64 (bitcast A)))))
20455 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20456 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20457 // (v2f64 (bitcast A)))))
20459 CanFold = (isZero(Cond.getOperand(0)) &&
20460 isZero(Cond.getOperand(1)) &&
20461 isAllOnes(Cond.getOperand(2)) &&
20462 isAllOnes(Cond.getOperand(3)));
20464 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20465 isAllOnes(Cond.getOperand(1)) &&
20466 isZero(Cond.getOperand(2)) &&
20467 isZero(Cond.getOperand(3))) {
20469 std::swap(LHS, RHS);
20473 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20474 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20475 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20476 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20478 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20484 // If we know that this node is legal then we know that it is going to be
20485 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20486 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20487 // to simplify previous instructions.
20488 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20489 !DCI.isBeforeLegalize() &&
20490 // We explicitly check against v8i16 and v16i16 because, although
20491 // they're marked as Custom, they might only be legal when Cond is a
20492 // build_vector of constants. This will be taken care in a later
20494 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20495 VT != MVT::v8i16)) {
20496 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20498 // Don't optimize vector selects that map to mask-registers.
20502 // Check all uses of that condition operand to check whether it will be
20503 // consumed by non-BLEND instructions, which may depend on all bits are set
20505 for (SDNode::use_iterator I = Cond->use_begin(),
20506 E = Cond->use_end(); I != E; ++I)
20507 if (I->getOpcode() != ISD::VSELECT)
20508 // TODO: Add other opcodes eventually lowered into BLEND.
20511 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20512 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20514 APInt KnownZero, KnownOne;
20515 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20516 DCI.isBeforeLegalizeOps());
20517 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20518 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20519 DCI.CommitTargetLoweringOpt(TLO);
20522 // We should generate an X86ISD::BLENDI from a vselect if its argument
20523 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20524 // constants. This specific pattern gets generated when we split a
20525 // selector for a 512 bit vector in a machine without AVX512 (but with
20526 // 256-bit vectors), during legalization:
20528 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20530 // Iff we find this pattern and the build_vectors are built from
20531 // constants, we translate the vselect into a shuffle_vector that we
20532 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20533 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20534 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20535 if (Shuffle.getNode())
20542 // Check whether a boolean test is testing a boolean value generated by
20543 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20546 // Simplify the following patterns:
20547 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20548 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20549 // to (Op EFLAGS Cond)
20551 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20552 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20553 // to (Op EFLAGS !Cond)
20555 // where Op could be BRCOND or CMOV.
20557 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20558 // Quit if not CMP and SUB with its value result used.
20559 if (Cmp.getOpcode() != X86ISD::CMP &&
20560 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20563 // Quit if not used as a boolean value.
20564 if (CC != X86::COND_E && CC != X86::COND_NE)
20567 // Check CMP operands. One of them should be 0 or 1 and the other should be
20568 // an SetCC or extended from it.
20569 SDValue Op1 = Cmp.getOperand(0);
20570 SDValue Op2 = Cmp.getOperand(1);
20573 const ConstantSDNode* C = nullptr;
20574 bool needOppositeCond = (CC == X86::COND_E);
20575 bool checkAgainstTrue = false; // Is it a comparison against 1?
20577 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20579 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20581 else // Quit if all operands are not constants.
20584 if (C->getZExtValue() == 1) {
20585 needOppositeCond = !needOppositeCond;
20586 checkAgainstTrue = true;
20587 } else if (C->getZExtValue() != 0)
20588 // Quit if the constant is neither 0 or 1.
20591 bool truncatedToBoolWithAnd = false;
20592 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20593 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20594 SetCC.getOpcode() == ISD::TRUNCATE ||
20595 SetCC.getOpcode() == ISD::AND) {
20596 if (SetCC.getOpcode() == ISD::AND) {
20598 ConstantSDNode *CS;
20599 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20600 CS->getZExtValue() == 1)
20602 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20603 CS->getZExtValue() == 1)
20607 SetCC = SetCC.getOperand(OpIdx);
20608 truncatedToBoolWithAnd = true;
20610 SetCC = SetCC.getOperand(0);
20613 switch (SetCC.getOpcode()) {
20614 case X86ISD::SETCC_CARRY:
20615 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20616 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20617 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20618 // truncated to i1 using 'and'.
20619 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20621 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20622 "Invalid use of SETCC_CARRY!");
20624 case X86ISD::SETCC:
20625 // Set the condition code or opposite one if necessary.
20626 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20627 if (needOppositeCond)
20628 CC = X86::GetOppositeBranchCondition(CC);
20629 return SetCC.getOperand(1);
20630 case X86ISD::CMOV: {
20631 // Check whether false/true value has canonical one, i.e. 0 or 1.
20632 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20633 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20634 // Quit if true value is not a constant.
20637 // Quit if false value is not a constant.
20639 SDValue Op = SetCC.getOperand(0);
20640 // Skip 'zext' or 'trunc' node.
20641 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20642 Op.getOpcode() == ISD::TRUNCATE)
20643 Op = Op.getOperand(0);
20644 // A special case for rdrand/rdseed, where 0 is set if false cond is
20646 if ((Op.getOpcode() != X86ISD::RDRAND &&
20647 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20650 // Quit if false value is not the constant 0 or 1.
20651 bool FValIsFalse = true;
20652 if (FVal && FVal->getZExtValue() != 0) {
20653 if (FVal->getZExtValue() != 1)
20655 // If FVal is 1, opposite cond is needed.
20656 needOppositeCond = !needOppositeCond;
20657 FValIsFalse = false;
20659 // Quit if TVal is not the constant opposite of FVal.
20660 if (FValIsFalse && TVal->getZExtValue() != 1)
20662 if (!FValIsFalse && TVal->getZExtValue() != 0)
20664 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20665 if (needOppositeCond)
20666 CC = X86::GetOppositeBranchCondition(CC);
20667 return SetCC.getOperand(3);
20674 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20675 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20676 TargetLowering::DAGCombinerInfo &DCI,
20677 const X86Subtarget *Subtarget) {
20680 // If the flag operand isn't dead, don't touch this CMOV.
20681 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20684 SDValue FalseOp = N->getOperand(0);
20685 SDValue TrueOp = N->getOperand(1);
20686 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20687 SDValue Cond = N->getOperand(3);
20689 if (CC == X86::COND_E || CC == X86::COND_NE) {
20690 switch (Cond.getOpcode()) {
20694 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20695 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20696 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20702 Flags = checkBoolTestSetCCCombine(Cond, CC);
20703 if (Flags.getNode() &&
20704 // Extra check as FCMOV only supports a subset of X86 cond.
20705 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20706 SDValue Ops[] = { FalseOp, TrueOp,
20707 DAG.getConstant(CC, MVT::i8), Flags };
20708 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20711 // If this is a select between two integer constants, try to do some
20712 // optimizations. Note that the operands are ordered the opposite of SELECT
20714 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20715 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20716 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20717 // larger than FalseC (the false value).
20718 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20719 CC = X86::GetOppositeBranchCondition(CC);
20720 std::swap(TrueC, FalseC);
20721 std::swap(TrueOp, FalseOp);
20724 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20725 // This is efficient for any integer data type (including i8/i16) and
20727 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20728 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20729 DAG.getConstant(CC, MVT::i8), Cond);
20731 // Zero extend the condition if needed.
20732 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20734 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20735 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20736 DAG.getConstant(ShAmt, MVT::i8));
20737 if (N->getNumValues() == 2) // Dead flag value?
20738 return DCI.CombineTo(N, Cond, SDValue());
20742 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20743 // for any integer data type, including i8/i16.
20744 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20745 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20746 DAG.getConstant(CC, MVT::i8), Cond);
20748 // Zero extend the condition if needed.
20749 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20750 FalseC->getValueType(0), Cond);
20751 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20752 SDValue(FalseC, 0));
20754 if (N->getNumValues() == 2) // Dead flag value?
20755 return DCI.CombineTo(N, Cond, SDValue());
20759 // Optimize cases that will turn into an LEA instruction. This requires
20760 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20761 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20762 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20763 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20765 bool isFastMultiplier = false;
20767 switch ((unsigned char)Diff) {
20769 case 1: // result = add base, cond
20770 case 2: // result = lea base( , cond*2)
20771 case 3: // result = lea base(cond, cond*2)
20772 case 4: // result = lea base( , cond*4)
20773 case 5: // result = lea base(cond, cond*4)
20774 case 8: // result = lea base( , cond*8)
20775 case 9: // result = lea base(cond, cond*8)
20776 isFastMultiplier = true;
20781 if (isFastMultiplier) {
20782 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20783 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20784 DAG.getConstant(CC, MVT::i8), Cond);
20785 // Zero extend the condition if needed.
20786 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20788 // Scale the condition by the difference.
20790 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20791 DAG.getConstant(Diff, Cond.getValueType()));
20793 // Add the base if non-zero.
20794 if (FalseC->getAPIntValue() != 0)
20795 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20796 SDValue(FalseC, 0));
20797 if (N->getNumValues() == 2) // Dead flag value?
20798 return DCI.CombineTo(N, Cond, SDValue());
20805 // Handle these cases:
20806 // (select (x != c), e, c) -> select (x != c), e, x),
20807 // (select (x == c), c, e) -> select (x == c), x, e)
20808 // where the c is an integer constant, and the "select" is the combination
20809 // of CMOV and CMP.
20811 // The rationale for this change is that the conditional-move from a constant
20812 // needs two instructions, however, conditional-move from a register needs
20813 // only one instruction.
20815 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20816 // some instruction-combining opportunities. This opt needs to be
20817 // postponed as late as possible.
20819 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20820 // the DCI.xxxx conditions are provided to postpone the optimization as
20821 // late as possible.
20823 ConstantSDNode *CmpAgainst = nullptr;
20824 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20825 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20826 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20828 if (CC == X86::COND_NE &&
20829 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20830 CC = X86::GetOppositeBranchCondition(CC);
20831 std::swap(TrueOp, FalseOp);
20834 if (CC == X86::COND_E &&
20835 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20836 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20837 DAG.getConstant(CC, MVT::i8), Cond };
20838 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20846 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20847 const X86Subtarget *Subtarget) {
20848 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20850 default: return SDValue();
20851 // SSE/AVX/AVX2 blend intrinsics.
20852 case Intrinsic::x86_avx2_pblendvb:
20853 case Intrinsic::x86_avx2_pblendw:
20854 case Intrinsic::x86_avx2_pblendd_128:
20855 case Intrinsic::x86_avx2_pblendd_256:
20856 // Don't try to simplify this intrinsic if we don't have AVX2.
20857 if (!Subtarget->hasAVX2())
20860 case Intrinsic::x86_avx_blend_pd_256:
20861 case Intrinsic::x86_avx_blend_ps_256:
20862 case Intrinsic::x86_avx_blendv_pd_256:
20863 case Intrinsic::x86_avx_blendv_ps_256:
20864 // Don't try to simplify this intrinsic if we don't have AVX.
20865 if (!Subtarget->hasAVX())
20868 case Intrinsic::x86_sse41_pblendw:
20869 case Intrinsic::x86_sse41_blendpd:
20870 case Intrinsic::x86_sse41_blendps:
20871 case Intrinsic::x86_sse41_blendvps:
20872 case Intrinsic::x86_sse41_blendvpd:
20873 case Intrinsic::x86_sse41_pblendvb: {
20874 SDValue Op0 = N->getOperand(1);
20875 SDValue Op1 = N->getOperand(2);
20876 SDValue Mask = N->getOperand(3);
20878 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20879 if (!Subtarget->hasSSE41())
20882 // fold (blend A, A, Mask) -> A
20885 // fold (blend A, B, allZeros) -> A
20886 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20888 // fold (blend A, B, allOnes) -> B
20889 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20892 // Simplify the case where the mask is a constant i32 value.
20893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20894 if (C->isNullValue())
20896 if (C->isAllOnesValue())
20903 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20904 case Intrinsic::x86_sse2_psrai_w:
20905 case Intrinsic::x86_sse2_psrai_d:
20906 case Intrinsic::x86_avx2_psrai_w:
20907 case Intrinsic::x86_avx2_psrai_d:
20908 case Intrinsic::x86_sse2_psra_w:
20909 case Intrinsic::x86_sse2_psra_d:
20910 case Intrinsic::x86_avx2_psra_w:
20911 case Intrinsic::x86_avx2_psra_d: {
20912 SDValue Op0 = N->getOperand(1);
20913 SDValue Op1 = N->getOperand(2);
20914 EVT VT = Op0.getValueType();
20915 assert(VT.isVector() && "Expected a vector type!");
20917 if (isa<BuildVectorSDNode>(Op1))
20918 Op1 = Op1.getOperand(0);
20920 if (!isa<ConstantSDNode>(Op1))
20923 EVT SVT = VT.getVectorElementType();
20924 unsigned SVTBits = SVT.getSizeInBits();
20926 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20927 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20928 uint64_t ShAmt = C.getZExtValue();
20930 // Don't try to convert this shift into a ISD::SRA if the shift
20931 // count is bigger than or equal to the element size.
20932 if (ShAmt >= SVTBits)
20935 // Trivial case: if the shift count is zero, then fold this
20936 // into the first operand.
20940 // Replace this packed shift intrinsic with a target independent
20942 SDValue Splat = DAG.getConstant(C, VT);
20943 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20948 /// PerformMulCombine - Optimize a single multiply with constant into two
20949 /// in order to implement it with two cheaper instructions, e.g.
20950 /// LEA + SHL, LEA + LEA.
20951 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20952 TargetLowering::DAGCombinerInfo &DCI) {
20953 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20956 EVT VT = N->getValueType(0);
20957 if (VT != MVT::i64)
20960 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20963 uint64_t MulAmt = C->getZExtValue();
20964 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20967 uint64_t MulAmt1 = 0;
20968 uint64_t MulAmt2 = 0;
20969 if ((MulAmt % 9) == 0) {
20971 MulAmt2 = MulAmt / 9;
20972 } else if ((MulAmt % 5) == 0) {
20974 MulAmt2 = MulAmt / 5;
20975 } else if ((MulAmt % 3) == 0) {
20977 MulAmt2 = MulAmt / 3;
20980 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20983 if (isPowerOf2_64(MulAmt2) &&
20984 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20985 // If second multiplifer is pow2, issue it first. We want the multiply by
20986 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20988 std::swap(MulAmt1, MulAmt2);
20991 if (isPowerOf2_64(MulAmt1))
20992 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20993 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20995 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20996 DAG.getConstant(MulAmt1, VT));
20998 if (isPowerOf2_64(MulAmt2))
20999 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21000 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21002 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21003 DAG.getConstant(MulAmt2, VT));
21005 // Do not add new nodes to DAG combiner worklist.
21006 DCI.CombineTo(N, NewMul, false);
21011 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21012 SDValue N0 = N->getOperand(0);
21013 SDValue N1 = N->getOperand(1);
21014 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21015 EVT VT = N0.getValueType();
21017 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21018 // since the result of setcc_c is all zero's or all ones.
21019 if (VT.isInteger() && !VT.isVector() &&
21020 N1C && N0.getOpcode() == ISD::AND &&
21021 N0.getOperand(1).getOpcode() == ISD::Constant) {
21022 SDValue N00 = N0.getOperand(0);
21023 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21024 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21025 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21026 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21027 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21028 APInt ShAmt = N1C->getAPIntValue();
21029 Mask = Mask.shl(ShAmt);
21031 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21032 N00, DAG.getConstant(Mask, VT));
21036 // Hardware support for vector shifts is sparse which makes us scalarize the
21037 // vector operations in many cases. Also, on sandybridge ADD is faster than
21039 // (shl V, 1) -> add V,V
21040 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21041 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21042 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21043 // We shift all of the values by one. In many cases we do not have
21044 // hardware support for this operation. This is better expressed as an ADD
21046 if (N1SplatC->getZExtValue() == 1)
21047 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21053 /// \brief Returns a vector of 0s if the node in input is a vector logical
21054 /// shift by a constant amount which is known to be bigger than or equal
21055 /// to the vector element size in bits.
21056 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21057 const X86Subtarget *Subtarget) {
21058 EVT VT = N->getValueType(0);
21060 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21061 (!Subtarget->hasInt256() ||
21062 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21065 SDValue Amt = N->getOperand(1);
21067 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21068 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21069 APInt ShiftAmt = AmtSplat->getAPIntValue();
21070 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21072 // SSE2/AVX2 logical shifts always return a vector of 0s
21073 // if the shift amount is bigger than or equal to
21074 // the element size. The constant shift amount will be
21075 // encoded as a 8-bit immediate.
21076 if (ShiftAmt.trunc(8).uge(MaxAmount))
21077 return getZeroVector(VT, Subtarget, DAG, DL);
21083 /// PerformShiftCombine - Combine shifts.
21084 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21085 TargetLowering::DAGCombinerInfo &DCI,
21086 const X86Subtarget *Subtarget) {
21087 if (N->getOpcode() == ISD::SHL) {
21088 SDValue V = PerformSHLCombine(N, DAG);
21089 if (V.getNode()) return V;
21092 if (N->getOpcode() != ISD::SRA) {
21093 // Try to fold this logical shift into a zero vector.
21094 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21095 if (V.getNode()) return V;
21101 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21102 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21103 // and friends. Likewise for OR -> CMPNEQSS.
21104 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21105 TargetLowering::DAGCombinerInfo &DCI,
21106 const X86Subtarget *Subtarget) {
21109 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21110 // we're requiring SSE2 for both.
21111 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21112 SDValue N0 = N->getOperand(0);
21113 SDValue N1 = N->getOperand(1);
21114 SDValue CMP0 = N0->getOperand(1);
21115 SDValue CMP1 = N1->getOperand(1);
21118 // The SETCCs should both refer to the same CMP.
21119 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21122 SDValue CMP00 = CMP0->getOperand(0);
21123 SDValue CMP01 = CMP0->getOperand(1);
21124 EVT VT = CMP00.getValueType();
21126 if (VT == MVT::f32 || VT == MVT::f64) {
21127 bool ExpectingFlags = false;
21128 // Check for any users that want flags:
21129 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21130 !ExpectingFlags && UI != UE; ++UI)
21131 switch (UI->getOpcode()) {
21136 ExpectingFlags = true;
21138 case ISD::CopyToReg:
21139 case ISD::SIGN_EXTEND:
21140 case ISD::ZERO_EXTEND:
21141 case ISD::ANY_EXTEND:
21145 if (!ExpectingFlags) {
21146 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21147 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21149 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21150 X86::CondCode tmp = cc0;
21155 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21156 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21157 // FIXME: need symbolic constants for these magic numbers.
21158 // See X86ATTInstPrinter.cpp:printSSECC().
21159 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21160 if (Subtarget->hasAVX512()) {
21161 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21162 CMP01, DAG.getConstant(x86cc, MVT::i8));
21163 if (N->getValueType(0) != MVT::i1)
21164 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21168 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21169 CMP00.getValueType(), CMP00, CMP01,
21170 DAG.getConstant(x86cc, MVT::i8));
21172 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21173 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21175 if (is64BitFP && !Subtarget->is64Bit()) {
21176 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21177 // 64-bit integer, since that's not a legal type. Since
21178 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21179 // bits, but can do this little dance to extract the lowest 32 bits
21180 // and work with those going forward.
21181 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21183 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21185 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21186 Vector32, DAG.getIntPtrConstant(0));
21190 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21191 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21192 DAG.getConstant(1, IntVT));
21193 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21194 return OneBitOfTruth;
21202 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21203 /// so it can be folded inside ANDNP.
21204 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21205 EVT VT = N->getValueType(0);
21207 // Match direct AllOnes for 128 and 256-bit vectors
21208 if (ISD::isBuildVectorAllOnes(N))
21211 // Look through a bit convert.
21212 if (N->getOpcode() == ISD::BITCAST)
21213 N = N->getOperand(0).getNode();
21215 // Sometimes the operand may come from a insert_subvector building a 256-bit
21217 if (VT.is256BitVector() &&
21218 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21219 SDValue V1 = N->getOperand(0);
21220 SDValue V2 = N->getOperand(1);
21222 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21223 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21224 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21225 ISD::isBuildVectorAllOnes(V2.getNode()))
21232 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21233 // register. In most cases we actually compare or select YMM-sized registers
21234 // and mixing the two types creates horrible code. This method optimizes
21235 // some of the transition sequences.
21236 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21237 TargetLowering::DAGCombinerInfo &DCI,
21238 const X86Subtarget *Subtarget) {
21239 EVT VT = N->getValueType(0);
21240 if (!VT.is256BitVector())
21243 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21244 N->getOpcode() == ISD::ZERO_EXTEND ||
21245 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21247 SDValue Narrow = N->getOperand(0);
21248 EVT NarrowVT = Narrow->getValueType(0);
21249 if (!NarrowVT.is128BitVector())
21252 if (Narrow->getOpcode() != ISD::XOR &&
21253 Narrow->getOpcode() != ISD::AND &&
21254 Narrow->getOpcode() != ISD::OR)
21257 SDValue N0 = Narrow->getOperand(0);
21258 SDValue N1 = Narrow->getOperand(1);
21261 // The Left side has to be a trunc.
21262 if (N0.getOpcode() != ISD::TRUNCATE)
21265 // The type of the truncated inputs.
21266 EVT WideVT = N0->getOperand(0)->getValueType(0);
21270 // The right side has to be a 'trunc' or a constant vector.
21271 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21272 ConstantSDNode *RHSConstSplat = nullptr;
21273 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21274 RHSConstSplat = RHSBV->getConstantSplatNode();
21275 if (!RHSTrunc && !RHSConstSplat)
21278 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21280 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21283 // Set N0 and N1 to hold the inputs to the new wide operation.
21284 N0 = N0->getOperand(0);
21285 if (RHSConstSplat) {
21286 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21287 SDValue(RHSConstSplat, 0));
21288 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21289 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21290 } else if (RHSTrunc) {
21291 N1 = N1->getOperand(0);
21294 // Generate the wide operation.
21295 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21296 unsigned Opcode = N->getOpcode();
21298 case ISD::ANY_EXTEND:
21300 case ISD::ZERO_EXTEND: {
21301 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21302 APInt Mask = APInt::getAllOnesValue(InBits);
21303 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21304 return DAG.getNode(ISD::AND, DL, VT,
21305 Op, DAG.getConstant(Mask, VT));
21307 case ISD::SIGN_EXTEND:
21308 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21309 Op, DAG.getValueType(NarrowVT));
21311 llvm_unreachable("Unexpected opcode");
21315 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21316 TargetLowering::DAGCombinerInfo &DCI,
21317 const X86Subtarget *Subtarget) {
21318 EVT VT = N->getValueType(0);
21319 if (DCI.isBeforeLegalizeOps())
21322 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21326 // Create BEXTR instructions
21327 // BEXTR is ((X >> imm) & (2**size-1))
21328 if (VT == MVT::i32 || VT == MVT::i64) {
21329 SDValue N0 = N->getOperand(0);
21330 SDValue N1 = N->getOperand(1);
21333 // Check for BEXTR.
21334 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21335 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21336 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21337 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21338 if (MaskNode && ShiftNode) {
21339 uint64_t Mask = MaskNode->getZExtValue();
21340 uint64_t Shift = ShiftNode->getZExtValue();
21341 if (isMask_64(Mask)) {
21342 uint64_t MaskSize = CountPopulation_64(Mask);
21343 if (Shift + MaskSize <= VT.getSizeInBits())
21344 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21345 DAG.getConstant(Shift | (MaskSize << 8), VT));
21353 // Want to form ANDNP nodes:
21354 // 1) In the hopes of then easily combining them with OR and AND nodes
21355 // to form PBLEND/PSIGN.
21356 // 2) To match ANDN packed intrinsics
21357 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21360 SDValue N0 = N->getOperand(0);
21361 SDValue N1 = N->getOperand(1);
21364 // Check LHS for vnot
21365 if (N0.getOpcode() == ISD::XOR &&
21366 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21367 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21368 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21370 // Check RHS for vnot
21371 if (N1.getOpcode() == ISD::XOR &&
21372 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21373 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21374 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21379 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21380 TargetLowering::DAGCombinerInfo &DCI,
21381 const X86Subtarget *Subtarget) {
21382 if (DCI.isBeforeLegalizeOps())
21385 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21389 SDValue N0 = N->getOperand(0);
21390 SDValue N1 = N->getOperand(1);
21391 EVT VT = N->getValueType(0);
21393 // look for psign/blend
21394 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21395 if (!Subtarget->hasSSSE3() ||
21396 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21399 // Canonicalize pandn to RHS
21400 if (N0.getOpcode() == X86ISD::ANDNP)
21402 // or (and (m, y), (pandn m, x))
21403 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21404 SDValue Mask = N1.getOperand(0);
21405 SDValue X = N1.getOperand(1);
21407 if (N0.getOperand(0) == Mask)
21408 Y = N0.getOperand(1);
21409 if (N0.getOperand(1) == Mask)
21410 Y = N0.getOperand(0);
21412 // Check to see if the mask appeared in both the AND and ANDNP and
21416 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21417 // Look through mask bitcast.
21418 if (Mask.getOpcode() == ISD::BITCAST)
21419 Mask = Mask.getOperand(0);
21420 if (X.getOpcode() == ISD::BITCAST)
21421 X = X.getOperand(0);
21422 if (Y.getOpcode() == ISD::BITCAST)
21423 Y = Y.getOperand(0);
21425 EVT MaskVT = Mask.getValueType();
21427 // Validate that the Mask operand is a vector sra node.
21428 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21429 // there is no psrai.b
21430 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21431 unsigned SraAmt = ~0;
21432 if (Mask.getOpcode() == ISD::SRA) {
21433 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21434 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21435 SraAmt = AmtConst->getZExtValue();
21436 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21437 SDValue SraC = Mask.getOperand(1);
21438 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21440 if ((SraAmt + 1) != EltBits)
21445 // Now we know we at least have a plendvb with the mask val. See if
21446 // we can form a psignb/w/d.
21447 // psign = x.type == y.type == mask.type && y = sub(0, x);
21448 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21449 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21450 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21451 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21452 "Unsupported VT for PSIGN");
21453 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21454 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21456 // PBLENDVB only available on SSE 4.1
21457 if (!Subtarget->hasSSE41())
21460 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21462 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21463 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21464 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21465 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21466 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21470 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21473 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21474 MachineFunction &MF = DAG.getMachineFunction();
21475 bool OptForSize = MF.getFunction()->getAttributes().
21476 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21478 // SHLD/SHRD instructions have lower register pressure, but on some
21479 // platforms they have higher latency than the equivalent
21480 // series of shifts/or that would otherwise be generated.
21481 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21482 // have higher latencies and we are not optimizing for size.
21483 if (!OptForSize && Subtarget->isSHLDSlow())
21486 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21488 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21490 if (!N0.hasOneUse() || !N1.hasOneUse())
21493 SDValue ShAmt0 = N0.getOperand(1);
21494 if (ShAmt0.getValueType() != MVT::i8)
21496 SDValue ShAmt1 = N1.getOperand(1);
21497 if (ShAmt1.getValueType() != MVT::i8)
21499 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21500 ShAmt0 = ShAmt0.getOperand(0);
21501 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21502 ShAmt1 = ShAmt1.getOperand(0);
21505 unsigned Opc = X86ISD::SHLD;
21506 SDValue Op0 = N0.getOperand(0);
21507 SDValue Op1 = N1.getOperand(0);
21508 if (ShAmt0.getOpcode() == ISD::SUB) {
21509 Opc = X86ISD::SHRD;
21510 std::swap(Op0, Op1);
21511 std::swap(ShAmt0, ShAmt1);
21514 unsigned Bits = VT.getSizeInBits();
21515 if (ShAmt1.getOpcode() == ISD::SUB) {
21516 SDValue Sum = ShAmt1.getOperand(0);
21517 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21518 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21519 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21520 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21521 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21522 return DAG.getNode(Opc, DL, VT,
21524 DAG.getNode(ISD::TRUNCATE, DL,
21527 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21528 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21530 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21531 return DAG.getNode(Opc, DL, VT,
21532 N0.getOperand(0), N1.getOperand(0),
21533 DAG.getNode(ISD::TRUNCATE, DL,
21540 // Generate NEG and CMOV for integer abs.
21541 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21542 EVT VT = N->getValueType(0);
21544 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21545 // 8-bit integer abs to NEG and CMOV.
21546 if (VT.isInteger() && VT.getSizeInBits() == 8)
21549 SDValue N0 = N->getOperand(0);
21550 SDValue N1 = N->getOperand(1);
21553 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21554 // and change it to SUB and CMOV.
21555 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21556 N0.getOpcode() == ISD::ADD &&
21557 N0.getOperand(1) == N1 &&
21558 N1.getOpcode() == ISD::SRA &&
21559 N1.getOperand(0) == N0.getOperand(0))
21560 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21561 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21562 // Generate SUB & CMOV.
21563 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21564 DAG.getConstant(0, VT), N0.getOperand(0));
21566 SDValue Ops[] = { N0.getOperand(0), Neg,
21567 DAG.getConstant(X86::COND_GE, MVT::i8),
21568 SDValue(Neg.getNode(), 1) };
21569 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21574 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21575 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21576 TargetLowering::DAGCombinerInfo &DCI,
21577 const X86Subtarget *Subtarget) {
21578 if (DCI.isBeforeLegalizeOps())
21581 if (Subtarget->hasCMov()) {
21582 SDValue RV = performIntegerAbsCombine(N, DAG);
21590 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21591 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21592 TargetLowering::DAGCombinerInfo &DCI,
21593 const X86Subtarget *Subtarget) {
21594 LoadSDNode *Ld = cast<LoadSDNode>(N);
21595 EVT RegVT = Ld->getValueType(0);
21596 EVT MemVT = Ld->getMemoryVT();
21598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21600 // On Sandybridge unaligned 256bit loads are inefficient.
21601 ISD::LoadExtType Ext = Ld->getExtensionType();
21602 unsigned Alignment = Ld->getAlignment();
21603 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21604 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21605 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21606 unsigned NumElems = RegVT.getVectorNumElements();
21610 SDValue Ptr = Ld->getBasePtr();
21611 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21613 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21615 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21616 Ld->getPointerInfo(), Ld->isVolatile(),
21617 Ld->isNonTemporal(), Ld->isInvariant(),
21619 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21620 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21621 Ld->getPointerInfo(), Ld->isVolatile(),
21622 Ld->isNonTemporal(), Ld->isInvariant(),
21623 std::min(16U, Alignment));
21624 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21626 Load2.getValue(1));
21628 SDValue NewVec = DAG.getUNDEF(RegVT);
21629 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21630 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21631 return DCI.CombineTo(N, NewVec, TF, true);
21637 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21638 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21639 const X86Subtarget *Subtarget) {
21640 StoreSDNode *St = cast<StoreSDNode>(N);
21641 EVT VT = St->getValue().getValueType();
21642 EVT StVT = St->getMemoryVT();
21644 SDValue StoredVal = St->getOperand(1);
21645 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21647 // If we are saving a concatenation of two XMM registers, perform two stores.
21648 // On Sandy Bridge, 256-bit memory operations are executed by two
21649 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21650 // memory operation.
21651 unsigned Alignment = St->getAlignment();
21652 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21653 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21654 StVT == VT && !IsAligned) {
21655 unsigned NumElems = VT.getVectorNumElements();
21659 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21660 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21662 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21663 SDValue Ptr0 = St->getBasePtr();
21664 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21666 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21667 St->getPointerInfo(), St->isVolatile(),
21668 St->isNonTemporal(), Alignment);
21669 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21670 St->getPointerInfo(), St->isVolatile(),
21671 St->isNonTemporal(),
21672 std::min(16U, Alignment));
21673 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21676 // Optimize trunc store (of multiple scalars) to shuffle and store.
21677 // First, pack all of the elements in one place. Next, store to memory
21678 // in fewer chunks.
21679 if (St->isTruncatingStore() && VT.isVector()) {
21680 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21681 unsigned NumElems = VT.getVectorNumElements();
21682 assert(StVT != VT && "Cannot truncate to the same type");
21683 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21684 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21686 // From, To sizes and ElemCount must be pow of two
21687 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21688 // We are going to use the original vector elt for storing.
21689 // Accumulated smaller vector elements must be a multiple of the store size.
21690 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21692 unsigned SizeRatio = FromSz / ToSz;
21694 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21696 // Create a type on which we perform the shuffle
21697 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21698 StVT.getScalarType(), NumElems*SizeRatio);
21700 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21702 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21703 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21704 for (unsigned i = 0; i != NumElems; ++i)
21705 ShuffleVec[i] = i * SizeRatio;
21707 // Can't shuffle using an illegal type.
21708 if (!TLI.isTypeLegal(WideVecVT))
21711 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21712 DAG.getUNDEF(WideVecVT),
21714 // At this point all of the data is stored at the bottom of the
21715 // register. We now need to save it to mem.
21717 // Find the largest store unit
21718 MVT StoreType = MVT::i8;
21719 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21720 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21721 MVT Tp = (MVT::SimpleValueType)tp;
21722 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21726 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21727 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21728 (64 <= NumElems * ToSz))
21729 StoreType = MVT::f64;
21731 // Bitcast the original vector into a vector of store-size units
21732 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21733 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21734 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21735 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21736 SmallVector<SDValue, 8> Chains;
21737 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21738 TLI.getPointerTy());
21739 SDValue Ptr = St->getBasePtr();
21741 // Perform one or more big stores into memory.
21742 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21743 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21744 StoreType, ShuffWide,
21745 DAG.getIntPtrConstant(i));
21746 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21747 St->getPointerInfo(), St->isVolatile(),
21748 St->isNonTemporal(), St->getAlignment());
21749 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21750 Chains.push_back(Ch);
21753 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21756 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21757 // the FP state in cases where an emms may be missing.
21758 // A preferable solution to the general problem is to figure out the right
21759 // places to insert EMMS. This qualifies as a quick hack.
21761 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21762 if (VT.getSizeInBits() != 64)
21765 const Function *F = DAG.getMachineFunction().getFunction();
21766 bool NoImplicitFloatOps = F->getAttributes().
21767 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21768 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21769 && Subtarget->hasSSE2();
21770 if ((VT.isVector() ||
21771 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21772 isa<LoadSDNode>(St->getValue()) &&
21773 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21774 St->getChain().hasOneUse() && !St->isVolatile()) {
21775 SDNode* LdVal = St->getValue().getNode();
21776 LoadSDNode *Ld = nullptr;
21777 int TokenFactorIndex = -1;
21778 SmallVector<SDValue, 8> Ops;
21779 SDNode* ChainVal = St->getChain().getNode();
21780 // Must be a store of a load. We currently handle two cases: the load
21781 // is a direct child, and it's under an intervening TokenFactor. It is
21782 // possible to dig deeper under nested TokenFactors.
21783 if (ChainVal == LdVal)
21784 Ld = cast<LoadSDNode>(St->getChain());
21785 else if (St->getValue().hasOneUse() &&
21786 ChainVal->getOpcode() == ISD::TokenFactor) {
21787 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21788 if (ChainVal->getOperand(i).getNode() == LdVal) {
21789 TokenFactorIndex = i;
21790 Ld = cast<LoadSDNode>(St->getValue());
21792 Ops.push_back(ChainVal->getOperand(i));
21796 if (!Ld || !ISD::isNormalLoad(Ld))
21799 // If this is not the MMX case, i.e. we are just turning i64 load/store
21800 // into f64 load/store, avoid the transformation if there are multiple
21801 // uses of the loaded value.
21802 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21807 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21808 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21810 if (Subtarget->is64Bit() || F64IsLegal) {
21811 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21812 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21813 Ld->getPointerInfo(), Ld->isVolatile(),
21814 Ld->isNonTemporal(), Ld->isInvariant(),
21815 Ld->getAlignment());
21816 SDValue NewChain = NewLd.getValue(1);
21817 if (TokenFactorIndex != -1) {
21818 Ops.push_back(NewChain);
21819 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21821 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21822 St->getPointerInfo(),
21823 St->isVolatile(), St->isNonTemporal(),
21824 St->getAlignment());
21827 // Otherwise, lower to two pairs of 32-bit loads / stores.
21828 SDValue LoAddr = Ld->getBasePtr();
21829 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21830 DAG.getConstant(4, MVT::i32));
21832 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21833 Ld->getPointerInfo(),
21834 Ld->isVolatile(), Ld->isNonTemporal(),
21835 Ld->isInvariant(), Ld->getAlignment());
21836 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21837 Ld->getPointerInfo().getWithOffset(4),
21838 Ld->isVolatile(), Ld->isNonTemporal(),
21840 MinAlign(Ld->getAlignment(), 4));
21842 SDValue NewChain = LoLd.getValue(1);
21843 if (TokenFactorIndex != -1) {
21844 Ops.push_back(LoLd);
21845 Ops.push_back(HiLd);
21846 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21849 LoAddr = St->getBasePtr();
21850 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21851 DAG.getConstant(4, MVT::i32));
21853 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21854 St->getPointerInfo(),
21855 St->isVolatile(), St->isNonTemporal(),
21856 St->getAlignment());
21857 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21858 St->getPointerInfo().getWithOffset(4),
21860 St->isNonTemporal(),
21861 MinAlign(St->getAlignment(), 4));
21862 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21867 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21868 /// and return the operands for the horizontal operation in LHS and RHS. A
21869 /// horizontal operation performs the binary operation on successive elements
21870 /// of its first operand, then on successive elements of its second operand,
21871 /// returning the resulting values in a vector. For example, if
21872 /// A = < float a0, float a1, float a2, float a3 >
21874 /// B = < float b0, float b1, float b2, float b3 >
21875 /// then the result of doing a horizontal operation on A and B is
21876 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21877 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21878 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21879 /// set to A, RHS to B, and the routine returns 'true'.
21880 /// Note that the binary operation should have the property that if one of the
21881 /// operands is UNDEF then the result is UNDEF.
21882 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21883 // Look for the following pattern: if
21884 // A = < float a0, float a1, float a2, float a3 >
21885 // B = < float b0, float b1, float b2, float b3 >
21887 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21888 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21889 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21890 // which is A horizontal-op B.
21892 // At least one of the operands should be a vector shuffle.
21893 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21894 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21897 MVT VT = LHS.getSimpleValueType();
21899 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21900 "Unsupported vector type for horizontal add/sub");
21902 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21903 // operate independently on 128-bit lanes.
21904 unsigned NumElts = VT.getVectorNumElements();
21905 unsigned NumLanes = VT.getSizeInBits()/128;
21906 unsigned NumLaneElts = NumElts / NumLanes;
21907 assert((NumLaneElts % 2 == 0) &&
21908 "Vector type should have an even number of elements in each lane");
21909 unsigned HalfLaneElts = NumLaneElts/2;
21911 // View LHS in the form
21912 // LHS = VECTOR_SHUFFLE A, B, LMask
21913 // If LHS is not a shuffle then pretend it is the shuffle
21914 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21915 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21918 SmallVector<int, 16> LMask(NumElts);
21919 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21920 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21921 A = LHS.getOperand(0);
21922 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21923 B = LHS.getOperand(1);
21924 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21925 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21927 if (LHS.getOpcode() != ISD::UNDEF)
21929 for (unsigned i = 0; i != NumElts; ++i)
21933 // Likewise, view RHS in the form
21934 // RHS = VECTOR_SHUFFLE C, D, RMask
21936 SmallVector<int, 16> RMask(NumElts);
21937 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21938 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21939 C = RHS.getOperand(0);
21940 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21941 D = RHS.getOperand(1);
21942 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21943 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21945 if (RHS.getOpcode() != ISD::UNDEF)
21947 for (unsigned i = 0; i != NumElts; ++i)
21951 // Check that the shuffles are both shuffling the same vectors.
21952 if (!(A == C && B == D) && !(A == D && B == C))
21955 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21956 if (!A.getNode() && !B.getNode())
21959 // If A and B occur in reverse order in RHS, then "swap" them (which means
21960 // rewriting the mask).
21962 CommuteVectorShuffleMask(RMask, NumElts);
21964 // At this point LHS and RHS are equivalent to
21965 // LHS = VECTOR_SHUFFLE A, B, LMask
21966 // RHS = VECTOR_SHUFFLE A, B, RMask
21967 // Check that the masks correspond to performing a horizontal operation.
21968 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21969 for (unsigned i = 0; i != NumLaneElts; ++i) {
21970 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21972 // Ignore any UNDEF components.
21973 if (LIdx < 0 || RIdx < 0 ||
21974 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21975 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21978 // Check that successive elements are being operated on. If not, this is
21979 // not a horizontal operation.
21980 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21981 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21982 if (!(LIdx == Index && RIdx == Index + 1) &&
21983 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21988 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21989 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21993 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21994 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21995 const X86Subtarget *Subtarget) {
21996 EVT VT = N->getValueType(0);
21997 SDValue LHS = N->getOperand(0);
21998 SDValue RHS = N->getOperand(1);
22000 // Try to synthesize horizontal adds from adds of shuffles.
22001 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22002 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22003 isHorizontalBinOp(LHS, RHS, true))
22004 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22008 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22009 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22010 const X86Subtarget *Subtarget) {
22011 EVT VT = N->getValueType(0);
22012 SDValue LHS = N->getOperand(0);
22013 SDValue RHS = N->getOperand(1);
22015 // Try to synthesize horizontal subs from subs of shuffles.
22016 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22017 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22018 isHorizontalBinOp(LHS, RHS, false))
22019 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22023 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22024 /// X86ISD::FXOR nodes.
22025 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22026 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22027 // F[X]OR(0.0, x) -> x
22028 // F[X]OR(x, 0.0) -> x
22029 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22030 if (C->getValueAPF().isPosZero())
22031 return N->getOperand(1);
22032 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22033 if (C->getValueAPF().isPosZero())
22034 return N->getOperand(0);
22038 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22039 /// X86ISD::FMAX nodes.
22040 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22041 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22043 // Only perform optimizations if UnsafeMath is used.
22044 if (!DAG.getTarget().Options.UnsafeFPMath)
22047 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22048 // into FMINC and FMAXC, which are Commutative operations.
22049 unsigned NewOp = 0;
22050 switch (N->getOpcode()) {
22051 default: llvm_unreachable("unknown opcode");
22052 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22053 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22056 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22057 N->getOperand(0), N->getOperand(1));
22060 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22061 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22062 // FAND(0.0, x) -> 0.0
22063 // FAND(x, 0.0) -> 0.0
22064 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22065 if (C->getValueAPF().isPosZero())
22066 return N->getOperand(0);
22067 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22068 if (C->getValueAPF().isPosZero())
22069 return N->getOperand(1);
22073 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22074 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22075 // FANDN(x, 0.0) -> 0.0
22076 // FANDN(0.0, x) -> x
22077 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22078 if (C->getValueAPF().isPosZero())
22079 return N->getOperand(1);
22080 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22081 if (C->getValueAPF().isPosZero())
22082 return N->getOperand(1);
22086 static SDValue PerformBTCombine(SDNode *N,
22088 TargetLowering::DAGCombinerInfo &DCI) {
22089 // BT ignores high bits in the bit index operand.
22090 SDValue Op1 = N->getOperand(1);
22091 if (Op1.hasOneUse()) {
22092 unsigned BitWidth = Op1.getValueSizeInBits();
22093 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22094 APInt KnownZero, KnownOne;
22095 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22096 !DCI.isBeforeLegalizeOps());
22097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22098 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22099 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22100 DCI.CommitTargetLoweringOpt(TLO);
22105 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22106 SDValue Op = N->getOperand(0);
22107 if (Op.getOpcode() == ISD::BITCAST)
22108 Op = Op.getOperand(0);
22109 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22110 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22111 VT.getVectorElementType().getSizeInBits() ==
22112 OpVT.getVectorElementType().getSizeInBits()) {
22113 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22118 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22119 const X86Subtarget *Subtarget) {
22120 EVT VT = N->getValueType(0);
22121 if (!VT.isVector())
22124 SDValue N0 = N->getOperand(0);
22125 SDValue N1 = N->getOperand(1);
22126 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22129 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22130 // both SSE and AVX2 since there is no sign-extended shift right
22131 // operation on a vector with 64-bit elements.
22132 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22133 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22134 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22135 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22136 SDValue N00 = N0.getOperand(0);
22138 // EXTLOAD has a better solution on AVX2,
22139 // it may be replaced with X86ISD::VSEXT node.
22140 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22141 if (!ISD::isNormalLoad(N00.getNode()))
22144 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22145 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22147 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22153 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22154 TargetLowering::DAGCombinerInfo &DCI,
22155 const X86Subtarget *Subtarget) {
22156 if (!DCI.isBeforeLegalizeOps())
22159 if (!Subtarget->hasFp256())
22162 EVT VT = N->getValueType(0);
22163 if (VT.isVector() && VT.getSizeInBits() == 256) {
22164 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22172 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22173 const X86Subtarget* Subtarget) {
22175 EVT VT = N->getValueType(0);
22177 // Let legalize expand this if it isn't a legal type yet.
22178 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22181 EVT ScalarVT = VT.getScalarType();
22182 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22183 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22186 SDValue A = N->getOperand(0);
22187 SDValue B = N->getOperand(1);
22188 SDValue C = N->getOperand(2);
22190 bool NegA = (A.getOpcode() == ISD::FNEG);
22191 bool NegB = (B.getOpcode() == ISD::FNEG);
22192 bool NegC = (C.getOpcode() == ISD::FNEG);
22194 // Negative multiplication when NegA xor NegB
22195 bool NegMul = (NegA != NegB);
22197 A = A.getOperand(0);
22199 B = B.getOperand(0);
22201 C = C.getOperand(0);
22205 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22207 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22209 return DAG.getNode(Opcode, dl, VT, A, B, C);
22212 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22213 TargetLowering::DAGCombinerInfo &DCI,
22214 const X86Subtarget *Subtarget) {
22215 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22216 // (and (i32 x86isd::setcc_carry), 1)
22217 // This eliminates the zext. This transformation is necessary because
22218 // ISD::SETCC is always legalized to i8.
22220 SDValue N0 = N->getOperand(0);
22221 EVT VT = N->getValueType(0);
22223 if (N0.getOpcode() == ISD::AND &&
22225 N0.getOperand(0).hasOneUse()) {
22226 SDValue N00 = N0.getOperand(0);
22227 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22229 if (!C || C->getZExtValue() != 1)
22231 return DAG.getNode(ISD::AND, dl, VT,
22232 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22233 N00.getOperand(0), N00.getOperand(1)),
22234 DAG.getConstant(1, VT));
22238 if (N0.getOpcode() == ISD::TRUNCATE &&
22240 N0.getOperand(0).hasOneUse()) {
22241 SDValue N00 = N0.getOperand(0);
22242 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22243 return DAG.getNode(ISD::AND, dl, VT,
22244 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22245 N00.getOperand(0), N00.getOperand(1)),
22246 DAG.getConstant(1, VT));
22249 if (VT.is256BitVector()) {
22250 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22258 // Optimize x == -y --> x+y == 0
22259 // x != -y --> x+y != 0
22260 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22261 const X86Subtarget* Subtarget) {
22262 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22263 SDValue LHS = N->getOperand(0);
22264 SDValue RHS = N->getOperand(1);
22265 EVT VT = N->getValueType(0);
22268 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22269 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22270 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22271 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22272 LHS.getValueType(), RHS, LHS.getOperand(1));
22273 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22274 addV, DAG.getConstant(0, addV.getValueType()), CC);
22276 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22278 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22279 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22280 RHS.getValueType(), LHS, RHS.getOperand(1));
22281 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22282 addV, DAG.getConstant(0, addV.getValueType()), CC);
22285 if (VT.getScalarType() == MVT::i1) {
22286 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22287 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22288 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22289 if (!IsSEXT0 && !IsVZero0)
22291 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22292 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22293 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22295 if (!IsSEXT1 && !IsVZero1)
22298 if (IsSEXT0 && IsVZero1) {
22299 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22300 if (CC == ISD::SETEQ)
22301 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22302 return LHS.getOperand(0);
22304 if (IsSEXT1 && IsVZero0) {
22305 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22306 if (CC == ISD::SETEQ)
22307 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22308 return RHS.getOperand(0);
22315 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22316 const X86Subtarget *Subtarget) {
22318 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22319 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22320 "X86insertps is only defined for v4x32");
22322 SDValue Ld = N->getOperand(1);
22323 if (MayFoldLoad(Ld)) {
22324 // Extract the countS bits from the immediate so we can get the proper
22325 // address when narrowing the vector load to a specific element.
22326 // When the second source op is a memory address, interps doesn't use
22327 // countS and just gets an f32 from that address.
22328 unsigned DestIndex =
22329 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22330 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22334 // Create this as a scalar to vector to match the instruction pattern.
22335 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22336 // countS bits are ignored when loading from memory on insertps, which
22337 // means we don't need to explicitly set them to 0.
22338 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22339 LoadScalarToVector, N->getOperand(2));
22342 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22343 // as "sbb reg,reg", since it can be extended without zext and produces
22344 // an all-ones bit which is more useful than 0/1 in some cases.
22345 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22348 return DAG.getNode(ISD::AND, DL, VT,
22349 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22350 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22351 DAG.getConstant(1, VT));
22352 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22353 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22354 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22355 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22358 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22359 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22360 TargetLowering::DAGCombinerInfo &DCI,
22361 const X86Subtarget *Subtarget) {
22363 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22364 SDValue EFLAGS = N->getOperand(1);
22366 if (CC == X86::COND_A) {
22367 // Try to convert COND_A into COND_B in an attempt to facilitate
22368 // materializing "setb reg".
22370 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22371 // cannot take an immediate as its first operand.
22373 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22374 EFLAGS.getValueType().isInteger() &&
22375 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22376 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22377 EFLAGS.getNode()->getVTList(),
22378 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22379 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22380 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22384 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22385 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22387 if (CC == X86::COND_B)
22388 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22392 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22393 if (Flags.getNode()) {
22394 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22395 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22401 // Optimize branch condition evaluation.
22403 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22404 TargetLowering::DAGCombinerInfo &DCI,
22405 const X86Subtarget *Subtarget) {
22407 SDValue Chain = N->getOperand(0);
22408 SDValue Dest = N->getOperand(1);
22409 SDValue EFLAGS = N->getOperand(3);
22410 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22414 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22415 if (Flags.getNode()) {
22416 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22417 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22424 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22425 SelectionDAG &DAG) {
22426 // Take advantage of vector comparisons producing 0 or -1 in each lane to
22427 // optimize away operation when it's from a constant.
22429 // The general transformation is:
22430 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22431 // AND(VECTOR_CMP(x,y), constant2)
22432 // constant2 = UNARYOP(constant)
22434 // Early exit if this isn't a vector operation, the operand of the
22435 // unary operation isn't a bitwise AND, or if the sizes of the operations
22436 // aren't the same.
22437 EVT VT = N->getValueType(0);
22438 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22439 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22440 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22443 // Now check that the other operand of the AND is a constant. We could
22444 // make the transformation for non-constant splats as well, but it's unclear
22445 // that would be a benefit as it would not eliminate any operations, just
22446 // perform one more step in scalar code before moving to the vector unit.
22447 if (BuildVectorSDNode *BV =
22448 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22449 // Bail out if the vector isn't a constant.
22450 if (!BV->isConstant())
22453 // Everything checks out. Build up the new and improved node.
22455 EVT IntVT = BV->getValueType(0);
22456 // Create a new constant of the appropriate type for the transformed
22458 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22459 // The AND node needs bitcasts to/from an integer vector type around it.
22460 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22461 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22462 N->getOperand(0)->getOperand(0), MaskConst);
22463 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22470 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22471 const X86TargetLowering *XTLI) {
22472 // First try to optimize away the conversion entirely when it's
22473 // conditionally from a constant. Vectors only.
22474 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22475 if (Res != SDValue())
22478 // Now move on to more general possibilities.
22479 SDValue Op0 = N->getOperand(0);
22480 EVT InVT = Op0->getValueType(0);
22482 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22483 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22485 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22486 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22487 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22490 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22491 // a 32-bit target where SSE doesn't support i64->FP operations.
22492 if (Op0.getOpcode() == ISD::LOAD) {
22493 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22494 EVT VT = Ld->getValueType(0);
22495 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22496 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22497 !XTLI->getSubtarget()->is64Bit() &&
22499 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22500 Ld->getChain(), Op0, DAG);
22501 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22508 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22509 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22510 X86TargetLowering::DAGCombinerInfo &DCI) {
22511 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22512 // the result is either zero or one (depending on the input carry bit).
22513 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22514 if (X86::isZeroNode(N->getOperand(0)) &&
22515 X86::isZeroNode(N->getOperand(1)) &&
22516 // We don't have a good way to replace an EFLAGS use, so only do this when
22518 SDValue(N, 1).use_empty()) {
22520 EVT VT = N->getValueType(0);
22521 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22522 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22523 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22524 DAG.getConstant(X86::COND_B,MVT::i8),
22526 DAG.getConstant(1, VT));
22527 return DCI.CombineTo(N, Res1, CarryOut);
22533 // fold (add Y, (sete X, 0)) -> adc 0, Y
22534 // (add Y, (setne X, 0)) -> sbb -1, Y
22535 // (sub (sete X, 0), Y) -> sbb 0, Y
22536 // (sub (setne X, 0), Y) -> adc -1, Y
22537 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22540 // Look through ZExts.
22541 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22542 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22545 SDValue SetCC = Ext.getOperand(0);
22546 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22549 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22550 if (CC != X86::COND_E && CC != X86::COND_NE)
22553 SDValue Cmp = SetCC.getOperand(1);
22554 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22555 !X86::isZeroNode(Cmp.getOperand(1)) ||
22556 !Cmp.getOperand(0).getValueType().isInteger())
22559 SDValue CmpOp0 = Cmp.getOperand(0);
22560 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22561 DAG.getConstant(1, CmpOp0.getValueType()));
22563 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22564 if (CC == X86::COND_NE)
22565 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22566 DL, OtherVal.getValueType(), OtherVal,
22567 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22568 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22569 DL, OtherVal.getValueType(), OtherVal,
22570 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22573 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22574 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22575 const X86Subtarget *Subtarget) {
22576 EVT VT = N->getValueType(0);
22577 SDValue Op0 = N->getOperand(0);
22578 SDValue Op1 = N->getOperand(1);
22580 // Try to synthesize horizontal adds from adds of shuffles.
22581 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22582 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22583 isHorizontalBinOp(Op0, Op1, true))
22584 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22586 return OptimizeConditionalInDecrement(N, DAG);
22589 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22590 const X86Subtarget *Subtarget) {
22591 SDValue Op0 = N->getOperand(0);
22592 SDValue Op1 = N->getOperand(1);
22594 // X86 can't encode an immediate LHS of a sub. See if we can push the
22595 // negation into a preceding instruction.
22596 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22597 // If the RHS of the sub is a XOR with one use and a constant, invert the
22598 // immediate. Then add one to the LHS of the sub so we can turn
22599 // X-Y -> X+~Y+1, saving one register.
22600 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22601 isa<ConstantSDNode>(Op1.getOperand(1))) {
22602 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22603 EVT VT = Op0.getValueType();
22604 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22606 DAG.getConstant(~XorC, VT));
22607 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22608 DAG.getConstant(C->getAPIntValue()+1, VT));
22612 // Try to synthesize horizontal adds from adds of shuffles.
22613 EVT VT = N->getValueType(0);
22614 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22615 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22616 isHorizontalBinOp(Op0, Op1, true))
22617 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22619 return OptimizeConditionalInDecrement(N, DAG);
22622 /// performVZEXTCombine - Performs build vector combines
22623 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22624 TargetLowering::DAGCombinerInfo &DCI,
22625 const X86Subtarget *Subtarget) {
22626 // (vzext (bitcast (vzext (x)) -> (vzext x)
22627 SDValue In = N->getOperand(0);
22628 while (In.getOpcode() == ISD::BITCAST)
22629 In = In.getOperand(0);
22631 if (In.getOpcode() != X86ISD::VZEXT)
22634 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22638 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22639 DAGCombinerInfo &DCI) const {
22640 SelectionDAG &DAG = DCI.DAG;
22641 switch (N->getOpcode()) {
22643 case ISD::EXTRACT_VECTOR_ELT:
22644 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22646 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22647 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22648 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22649 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22650 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22651 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22654 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22655 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22656 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22657 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22658 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22659 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22660 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22661 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22662 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22664 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22666 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22667 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22668 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22669 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22670 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22671 case ISD::ANY_EXTEND:
22672 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22673 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22674 case ISD::SIGN_EXTEND_INREG:
22675 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22676 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22677 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22678 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22679 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22680 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22681 case X86ISD::SHUFP: // Handle all target specific shuffles
22682 case X86ISD::PALIGNR:
22683 case X86ISD::UNPCKH:
22684 case X86ISD::UNPCKL:
22685 case X86ISD::MOVHLPS:
22686 case X86ISD::MOVLHPS:
22687 case X86ISD::PSHUFB:
22688 case X86ISD::PSHUFD:
22689 case X86ISD::PSHUFHW:
22690 case X86ISD::PSHUFLW:
22691 case X86ISD::MOVSS:
22692 case X86ISD::MOVSD:
22693 case X86ISD::VPERMILP:
22694 case X86ISD::VPERM2X128:
22695 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22696 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22697 case ISD::INTRINSIC_WO_CHAIN:
22698 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22699 case X86ISD::INSERTPS:
22700 return PerformINSERTPSCombine(N, DAG, Subtarget);
22701 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22707 /// isTypeDesirableForOp - Return true if the target has native support for
22708 /// the specified value type and it is 'desirable' to use the type for the
22709 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22710 /// instruction encodings are longer and some i16 instructions are slow.
22711 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22712 if (!isTypeLegal(VT))
22714 if (VT != MVT::i16)
22721 case ISD::SIGN_EXTEND:
22722 case ISD::ZERO_EXTEND:
22723 case ISD::ANY_EXTEND:
22736 /// IsDesirableToPromoteOp - This method query the target whether it is
22737 /// beneficial for dag combiner to promote the specified node. If true, it
22738 /// should return the desired promotion type by reference.
22739 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22740 EVT VT = Op.getValueType();
22741 if (VT != MVT::i16)
22744 bool Promote = false;
22745 bool Commute = false;
22746 switch (Op.getOpcode()) {
22749 LoadSDNode *LD = cast<LoadSDNode>(Op);
22750 // If the non-extending load has a single use and it's not live out, then it
22751 // might be folded.
22752 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22753 Op.hasOneUse()*/) {
22754 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22755 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22756 // The only case where we'd want to promote LOAD (rather then it being
22757 // promoted as an operand is when it's only use is liveout.
22758 if (UI->getOpcode() != ISD::CopyToReg)
22765 case ISD::SIGN_EXTEND:
22766 case ISD::ZERO_EXTEND:
22767 case ISD::ANY_EXTEND:
22772 SDValue N0 = Op.getOperand(0);
22773 // Look out for (store (shl (load), x)).
22774 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22787 SDValue N0 = Op.getOperand(0);
22788 SDValue N1 = Op.getOperand(1);
22789 if (!Commute && MayFoldLoad(N1))
22791 // Avoid disabling potential load folding opportunities.
22792 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22794 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22804 //===----------------------------------------------------------------------===//
22805 // X86 Inline Assembly Support
22806 //===----------------------------------------------------------------------===//
22809 // Helper to match a string separated by whitespace.
22810 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22811 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22813 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22814 StringRef piece(*args[i]);
22815 if (!s.startswith(piece)) // Check if the piece matches.
22818 s = s.substr(piece.size());
22819 StringRef::size_type pos = s.find_first_not_of(" \t");
22820 if (pos == 0) // We matched a prefix.
22828 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22831 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22833 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22834 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22835 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22836 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22838 if (AsmPieces.size() == 3)
22840 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22847 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22848 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22850 std::string AsmStr = IA->getAsmString();
22852 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22853 if (!Ty || Ty->getBitWidth() % 16 != 0)
22856 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22857 SmallVector<StringRef, 4> AsmPieces;
22858 SplitString(AsmStr, AsmPieces, ";\n");
22860 switch (AsmPieces.size()) {
22861 default: return false;
22863 // FIXME: this should verify that we are targeting a 486 or better. If not,
22864 // we will turn this bswap into something that will be lowered to logical
22865 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22866 // lower so don't worry about this.
22868 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22869 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22870 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22871 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22872 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22873 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22874 // No need to check constraints, nothing other than the equivalent of
22875 // "=r,0" would be valid here.
22876 return IntrinsicLowering::LowerToByteSwap(CI);
22879 // rorw $$8, ${0:w} --> llvm.bswap.i16
22880 if (CI->getType()->isIntegerTy(16) &&
22881 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22882 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22883 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22885 const std::string &ConstraintsStr = IA->getConstraintString();
22886 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22887 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22888 if (clobbersFlagRegisters(AsmPieces))
22889 return IntrinsicLowering::LowerToByteSwap(CI);
22893 if (CI->getType()->isIntegerTy(32) &&
22894 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22895 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22896 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22897 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22899 const std::string &ConstraintsStr = IA->getConstraintString();
22900 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22901 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22902 if (clobbersFlagRegisters(AsmPieces))
22903 return IntrinsicLowering::LowerToByteSwap(CI);
22906 if (CI->getType()->isIntegerTy(64)) {
22907 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22908 if (Constraints.size() >= 2 &&
22909 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22910 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22911 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22912 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22913 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22914 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22915 return IntrinsicLowering::LowerToByteSwap(CI);
22923 /// getConstraintType - Given a constraint letter, return the type of
22924 /// constraint it is for this target.
22925 X86TargetLowering::ConstraintType
22926 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22927 if (Constraint.size() == 1) {
22928 switch (Constraint[0]) {
22939 return C_RegisterClass;
22963 return TargetLowering::getConstraintType(Constraint);
22966 /// Examine constraint type and operand type and determine a weight value.
22967 /// This object must already have been set up with the operand type
22968 /// and the current alternative constraint selected.
22969 TargetLowering::ConstraintWeight
22970 X86TargetLowering::getSingleConstraintMatchWeight(
22971 AsmOperandInfo &info, const char *constraint) const {
22972 ConstraintWeight weight = CW_Invalid;
22973 Value *CallOperandVal = info.CallOperandVal;
22974 // If we don't have a value, we can't do a match,
22975 // but allow it at the lowest weight.
22976 if (!CallOperandVal)
22978 Type *type = CallOperandVal->getType();
22979 // Look at the constraint type.
22980 switch (*constraint) {
22982 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22993 if (CallOperandVal->getType()->isIntegerTy())
22994 weight = CW_SpecificReg;
22999 if (type->isFloatingPointTy())
23000 weight = CW_SpecificReg;
23003 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23004 weight = CW_SpecificReg;
23008 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23009 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23010 weight = CW_Register;
23013 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23014 if (C->getZExtValue() <= 31)
23015 weight = CW_Constant;
23019 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23020 if (C->getZExtValue() <= 63)
23021 weight = CW_Constant;
23025 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23026 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23027 weight = CW_Constant;
23031 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23032 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23033 weight = CW_Constant;
23037 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23038 if (C->getZExtValue() <= 3)
23039 weight = CW_Constant;
23043 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23044 if (C->getZExtValue() <= 0xff)
23045 weight = CW_Constant;
23050 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23051 weight = CW_Constant;
23055 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23056 if ((C->getSExtValue() >= -0x80000000LL) &&
23057 (C->getSExtValue() <= 0x7fffffffLL))
23058 weight = CW_Constant;
23062 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23063 if (C->getZExtValue() <= 0xffffffff)
23064 weight = CW_Constant;
23071 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23072 /// with another that has more specific requirements based on the type of the
23073 /// corresponding operand.
23074 const char *X86TargetLowering::
23075 LowerXConstraint(EVT ConstraintVT) const {
23076 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23077 // 'f' like normal targets.
23078 if (ConstraintVT.isFloatingPoint()) {
23079 if (Subtarget->hasSSE2())
23081 if (Subtarget->hasSSE1())
23085 return TargetLowering::LowerXConstraint(ConstraintVT);
23088 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23089 /// vector. If it is invalid, don't add anything to Ops.
23090 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23091 std::string &Constraint,
23092 std::vector<SDValue>&Ops,
23093 SelectionDAG &DAG) const {
23096 // Only support length 1 constraints for now.
23097 if (Constraint.length() > 1) return;
23099 char ConstraintLetter = Constraint[0];
23100 switch (ConstraintLetter) {
23103 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23104 if (C->getZExtValue() <= 31) {
23105 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23111 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23112 if (C->getZExtValue() <= 63) {
23113 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23120 if (isInt<8>(C->getSExtValue())) {
23121 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23127 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23128 if (C->getZExtValue() <= 255) {
23129 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23135 // 32-bit signed value
23136 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23137 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23138 C->getSExtValue())) {
23139 // Widen to 64 bits here to get it sign extended.
23140 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23143 // FIXME gcc accepts some relocatable values here too, but only in certain
23144 // memory models; it's complicated.
23149 // 32-bit unsigned value
23150 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23151 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23152 C->getZExtValue())) {
23153 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23157 // FIXME gcc accepts some relocatable values here too, but only in certain
23158 // memory models; it's complicated.
23162 // Literal immediates are always ok.
23163 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23164 // Widen to 64 bits here to get it sign extended.
23165 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23169 // In any sort of PIC mode addresses need to be computed at runtime by
23170 // adding in a register or some sort of table lookup. These can't
23171 // be used as immediates.
23172 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23175 // If we are in non-pic codegen mode, we allow the address of a global (with
23176 // an optional displacement) to be used with 'i'.
23177 GlobalAddressSDNode *GA = nullptr;
23178 int64_t Offset = 0;
23180 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23182 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23183 Offset += GA->getOffset();
23185 } else if (Op.getOpcode() == ISD::ADD) {
23186 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23187 Offset += C->getZExtValue();
23188 Op = Op.getOperand(0);
23191 } else if (Op.getOpcode() == ISD::SUB) {
23192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23193 Offset += -C->getZExtValue();
23194 Op = Op.getOperand(0);
23199 // Otherwise, this isn't something we can handle, reject it.
23203 const GlobalValue *GV = GA->getGlobal();
23204 // If we require an extra load to get this address, as in PIC mode, we
23205 // can't accept it.
23206 if (isGlobalStubReference(
23207 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23210 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23211 GA->getValueType(0), Offset);
23216 if (Result.getNode()) {
23217 Ops.push_back(Result);
23220 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23223 std::pair<unsigned, const TargetRegisterClass*>
23224 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23226 // First, see if this is a constraint that directly corresponds to an LLVM
23228 if (Constraint.size() == 1) {
23229 // GCC Constraint Letters
23230 switch (Constraint[0]) {
23232 // TODO: Slight differences here in allocation order and leaving
23233 // RIP in the class. Do they matter any more here than they do
23234 // in the normal allocation?
23235 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23236 if (Subtarget->is64Bit()) {
23237 if (VT == MVT::i32 || VT == MVT::f32)
23238 return std::make_pair(0U, &X86::GR32RegClass);
23239 if (VT == MVT::i16)
23240 return std::make_pair(0U, &X86::GR16RegClass);
23241 if (VT == MVT::i8 || VT == MVT::i1)
23242 return std::make_pair(0U, &X86::GR8RegClass);
23243 if (VT == MVT::i64 || VT == MVT::f64)
23244 return std::make_pair(0U, &X86::GR64RegClass);
23247 // 32-bit fallthrough
23248 case 'Q': // Q_REGS
23249 if (VT == MVT::i32 || VT == MVT::f32)
23250 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23251 if (VT == MVT::i16)
23252 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23253 if (VT == MVT::i8 || VT == MVT::i1)
23254 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23255 if (VT == MVT::i64)
23256 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23258 case 'r': // GENERAL_REGS
23259 case 'l': // INDEX_REGS
23260 if (VT == MVT::i8 || VT == MVT::i1)
23261 return std::make_pair(0U, &X86::GR8RegClass);
23262 if (VT == MVT::i16)
23263 return std::make_pair(0U, &X86::GR16RegClass);
23264 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23265 return std::make_pair(0U, &X86::GR32RegClass);
23266 return std::make_pair(0U, &X86::GR64RegClass);
23267 case 'R': // LEGACY_REGS
23268 if (VT == MVT::i8 || VT == MVT::i1)
23269 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23270 if (VT == MVT::i16)
23271 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23272 if (VT == MVT::i32 || !Subtarget->is64Bit())
23273 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23274 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23275 case 'f': // FP Stack registers.
23276 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23277 // value to the correct fpstack register class.
23278 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23279 return std::make_pair(0U, &X86::RFP32RegClass);
23280 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23281 return std::make_pair(0U, &X86::RFP64RegClass);
23282 return std::make_pair(0U, &X86::RFP80RegClass);
23283 case 'y': // MMX_REGS if MMX allowed.
23284 if (!Subtarget->hasMMX()) break;
23285 return std::make_pair(0U, &X86::VR64RegClass);
23286 case 'Y': // SSE_REGS if SSE2 allowed
23287 if (!Subtarget->hasSSE2()) break;
23289 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23290 if (!Subtarget->hasSSE1()) break;
23292 switch (VT.SimpleTy) {
23294 // Scalar SSE types.
23297 return std::make_pair(0U, &X86::FR32RegClass);
23300 return std::make_pair(0U, &X86::FR64RegClass);
23308 return std::make_pair(0U, &X86::VR128RegClass);
23316 return std::make_pair(0U, &X86::VR256RegClass);
23321 return std::make_pair(0U, &X86::VR512RegClass);
23327 // Use the default implementation in TargetLowering to convert the register
23328 // constraint into a member of a register class.
23329 std::pair<unsigned, const TargetRegisterClass*> Res;
23330 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23332 // Not found as a standard register?
23334 // Map st(0) -> st(7) -> ST0
23335 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23336 tolower(Constraint[1]) == 's' &&
23337 tolower(Constraint[2]) == 't' &&
23338 Constraint[3] == '(' &&
23339 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23340 Constraint[5] == ')' &&
23341 Constraint[6] == '}') {
23343 Res.first = X86::FP0+Constraint[4]-'0';
23344 Res.second = &X86::RFP80RegClass;
23348 // GCC allows "st(0)" to be called just plain "st".
23349 if (StringRef("{st}").equals_lower(Constraint)) {
23350 Res.first = X86::FP0;
23351 Res.second = &X86::RFP80RegClass;
23356 if (StringRef("{flags}").equals_lower(Constraint)) {
23357 Res.first = X86::EFLAGS;
23358 Res.second = &X86::CCRRegClass;
23362 // 'A' means EAX + EDX.
23363 if (Constraint == "A") {
23364 Res.first = X86::EAX;
23365 Res.second = &X86::GR32_ADRegClass;
23371 // Otherwise, check to see if this is a register class of the wrong value
23372 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23373 // turn into {ax},{dx}.
23374 if (Res.second->hasType(VT))
23375 return Res; // Correct type already, nothing to do.
23377 // All of the single-register GCC register classes map their values onto
23378 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23379 // really want an 8-bit or 32-bit register, map to the appropriate register
23380 // class and return the appropriate register.
23381 if (Res.second == &X86::GR16RegClass) {
23382 if (VT == MVT::i8 || VT == MVT::i1) {
23383 unsigned DestReg = 0;
23384 switch (Res.first) {
23386 case X86::AX: DestReg = X86::AL; break;
23387 case X86::DX: DestReg = X86::DL; break;
23388 case X86::CX: DestReg = X86::CL; break;
23389 case X86::BX: DestReg = X86::BL; break;
23392 Res.first = DestReg;
23393 Res.second = &X86::GR8RegClass;
23395 } else if (VT == MVT::i32 || VT == MVT::f32) {
23396 unsigned DestReg = 0;
23397 switch (Res.first) {
23399 case X86::AX: DestReg = X86::EAX; break;
23400 case X86::DX: DestReg = X86::EDX; break;
23401 case X86::CX: DestReg = X86::ECX; break;
23402 case X86::BX: DestReg = X86::EBX; break;
23403 case X86::SI: DestReg = X86::ESI; break;
23404 case X86::DI: DestReg = X86::EDI; break;
23405 case X86::BP: DestReg = X86::EBP; break;
23406 case X86::SP: DestReg = X86::ESP; break;
23409 Res.first = DestReg;
23410 Res.second = &X86::GR32RegClass;
23412 } else if (VT == MVT::i64 || VT == MVT::f64) {
23413 unsigned DestReg = 0;
23414 switch (Res.first) {
23416 case X86::AX: DestReg = X86::RAX; break;
23417 case X86::DX: DestReg = X86::RDX; break;
23418 case X86::CX: DestReg = X86::RCX; break;
23419 case X86::BX: DestReg = X86::RBX; break;
23420 case X86::SI: DestReg = X86::RSI; break;
23421 case X86::DI: DestReg = X86::RDI; break;
23422 case X86::BP: DestReg = X86::RBP; break;
23423 case X86::SP: DestReg = X86::RSP; break;
23426 Res.first = DestReg;
23427 Res.second = &X86::GR64RegClass;
23430 } else if (Res.second == &X86::FR32RegClass ||
23431 Res.second == &X86::FR64RegClass ||
23432 Res.second == &X86::VR128RegClass ||
23433 Res.second == &X86::VR256RegClass ||
23434 Res.second == &X86::FR32XRegClass ||
23435 Res.second == &X86::FR64XRegClass ||
23436 Res.second == &X86::VR128XRegClass ||
23437 Res.second == &X86::VR256XRegClass ||
23438 Res.second == &X86::VR512RegClass) {
23439 // Handle references to XMM physical registers that got mapped into the
23440 // wrong class. This can happen with constraints like {xmm0} where the
23441 // target independent register mapper will just pick the first match it can
23442 // find, ignoring the required type.
23444 if (VT == MVT::f32 || VT == MVT::i32)
23445 Res.second = &X86::FR32RegClass;
23446 else if (VT == MVT::f64 || VT == MVT::i64)
23447 Res.second = &X86::FR64RegClass;
23448 else if (X86::VR128RegClass.hasType(VT))
23449 Res.second = &X86::VR128RegClass;
23450 else if (X86::VR256RegClass.hasType(VT))
23451 Res.second = &X86::VR256RegClass;
23452 else if (X86::VR512RegClass.hasType(VT))
23453 Res.second = &X86::VR512RegClass;
23459 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23461 // Scaling factors are not free at all.
23462 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23463 // will take 2 allocations in the out of order engine instead of 1
23464 // for plain addressing mode, i.e. inst (reg1).
23466 // vaddps (%rsi,%drx), %ymm0, %ymm1
23467 // Requires two allocations (one for the load, one for the computation)
23469 // vaddps (%rsi), %ymm0, %ymm1
23470 // Requires just 1 allocation, i.e., freeing allocations for other operations
23471 // and having less micro operations to execute.
23473 // For some X86 architectures, this is even worse because for instance for
23474 // stores, the complex addressing mode forces the instruction to use the
23475 // "load" ports instead of the dedicated "store" port.
23476 // E.g., on Haswell:
23477 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23478 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23479 if (isLegalAddressingMode(AM, Ty))
23480 // Scale represents reg2 * scale, thus account for 1
23481 // as soon as we use a second register.
23482 return AM.Scale != 0;
23486 bool X86TargetLowering::isTargetFTOL() const {
23487 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();