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 static_cast<const X86RegisterInfo*>(TM.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::allowsUnalignedMemoryAccesses(EVT VT,
1782 *Fast = Subtarget->isUnalignedMemAccessFast();
1786 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1787 /// current function. The returned value is a member of the
1788 /// MachineJumpTableInfo::JTEntryKind enum.
1789 unsigned X86TargetLowering::getJumpTableEncoding() const {
1790 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1793 Subtarget->isPICStyleGOT())
1794 return MachineJumpTableInfo::EK_Custom32;
1796 // Otherwise, use the normal jump table encoding heuristics.
1797 return TargetLowering::getJumpTableEncoding();
1801 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1802 const MachineBasicBlock *MBB,
1803 unsigned uid,MCContext &Ctx) const{
1804 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1805 Subtarget->isPICStyleGOT());
1806 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1809 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1812 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1815 SelectionDAG &DAG) const {
1816 if (!Subtarget->is64Bit())
1817 // This doesn't have SDLoc associated with it, but is not really the
1818 // same as a Register.
1819 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1823 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1824 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828 MCContext &Ctx) const {
1829 // X86-64 uses RIP relative addressing based on the jump table label.
1830 if (Subtarget->isPICStyleRIPRel())
1831 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833 // Otherwise, the reference is relative to the PIC base.
1834 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1837 // FIXME: Why this routine is here? Move to RegInfo!
1838 std::pair<const TargetRegisterClass*, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1840 const TargetRegisterClass *RRC = nullptr;
1842 switch (VT.SimpleTy) {
1844 return TargetLowering::findRepresentativeClass(VT);
1845 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846 RRC = Subtarget->is64Bit() ?
1847 (const TargetRegisterClass*)&X86::GR64RegClass :
1848 (const TargetRegisterClass*)&X86::GR32RegClass;
1851 RRC = &X86::VR64RegClass;
1853 case MVT::f32: case MVT::f64:
1854 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1855 case MVT::v4f32: case MVT::v2f64:
1856 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858 RRC = &X86::VR128RegClass;
1861 return std::make_pair(RRC, Cost);
1864 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1865 unsigned &Offset) const {
1866 if (!Subtarget->isTargetLinux())
1869 if (Subtarget->is64Bit()) {
1870 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1884 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1885 unsigned DestAS) const {
1886 assert(SrcAS != DestAS && "Expected different address spaces!");
1888 return SrcAS < 256 && DestAS < 256;
1891 //===----------------------------------------------------------------------===//
1892 // Return Value Calling Convention Implementation
1893 //===----------------------------------------------------------------------===//
1895 #include "X86GenCallingConv.inc"
1898 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1899 MachineFunction &MF, bool isVarArg,
1900 const SmallVectorImpl<ISD::OutputArg> &Outs,
1901 LLVMContext &Context) const {
1902 SmallVector<CCValAssign, 16> RVLocs;
1903 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1905 return CCInfo.CheckReturn(Outs, RetCC_X86);
1908 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1909 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1914 X86TargetLowering::LowerReturn(SDValue Chain,
1915 CallingConv::ID CallConv, bool isVarArg,
1916 const SmallVectorImpl<ISD::OutputArg> &Outs,
1917 const SmallVectorImpl<SDValue> &OutVals,
1918 SDLoc dl, SelectionDAG &DAG) const {
1919 MachineFunction &MF = DAG.getMachineFunction();
1920 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1922 SmallVector<CCValAssign, 16> RVLocs;
1923 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1924 RVLocs, *DAG.getContext());
1925 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1928 SmallVector<SDValue, 6> RetOps;
1929 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1930 // Operand #1 = Bytes To Pop
1931 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1934 // Copy the result values into the output registers.
1935 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1936 CCValAssign &VA = RVLocs[i];
1937 assert(VA.isRegLoc() && "Can only return in registers!");
1938 SDValue ValToCopy = OutVals[i];
1939 EVT ValVT = ValToCopy.getValueType();
1941 // Promote values to the appropriate types
1942 if (VA.getLocInfo() == CCValAssign::SExt)
1943 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944 else if (VA.getLocInfo() == CCValAssign::ZExt)
1945 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946 else if (VA.getLocInfo() == CCValAssign::AExt)
1947 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1948 else if (VA.getLocInfo() == CCValAssign::BCvt)
1949 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1952 "Unexpected FP-extend for return value.");
1954 // If this is x86-64, and we disabled SSE, we can't return FP values,
1955 // or SSE or MMX vectors.
1956 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1957 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1958 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1959 report_fatal_error("SSE register return with SSE disabled");
1961 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1962 // llvm-gcc has never done it right and no one has noticed, so this
1963 // should be OK for now.
1964 if (ValVT == MVT::f64 &&
1965 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1966 report_fatal_error("SSE2 register return with SSE2 disabled");
1968 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1969 // the RET instruction and handled by the FP Stackifier.
1970 if (VA.getLocReg() == X86::ST0 ||
1971 VA.getLocReg() == X86::ST1) {
1972 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1973 // change the value to the FP stack register class.
1974 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1975 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1976 RetOps.push_back(ValToCopy);
1977 // Don't emit a copytoreg.
1981 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1982 // which is returned in RAX / RDX.
1983 if (Subtarget->is64Bit()) {
1984 if (ValVT == MVT::x86mmx) {
1985 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1986 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1987 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989 // If we don't have SSE2 available, convert to v4f32 so the generated
1990 // register is legal.
1991 if (!Subtarget->hasSSE2())
1992 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1997 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1998 Flag = Chain.getValue(1);
1999 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2002 // The x86-64 ABIs require that for returning structs by value we copy
2003 // the sret argument into %rax/%eax (depending on ABI) for the return.
2004 // Win32 requires us to put the sret argument to %eax as well.
2005 // We saved the argument into a virtual register in the entry block,
2006 // so now we copy the value out and into %rax/%eax.
2007 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2008 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2009 MachineFunction &MF = DAG.getMachineFunction();
2010 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2011 unsigned Reg = FuncInfo->getSRetReturnReg();
2013 "SRetReturnReg should have been set in LowerFormalArguments().");
2014 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2017 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2018 X86::RAX : X86::EAX;
2019 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2020 Flag = Chain.getValue(1);
2022 // RAX/EAX now acts like a return value.
2023 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2026 RetOps[0] = Chain; // Update chain.
2028 // Add the flag if we have it.
2030 RetOps.push_back(Flag);
2032 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2035 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2036 if (N->getNumValues() != 1)
2038 if (!N->hasNUsesOfValue(1, 0))
2041 SDValue TCChain = Chain;
2042 SDNode *Copy = *N->use_begin();
2043 if (Copy->getOpcode() == ISD::CopyToReg) {
2044 // If the copy has a glue operand, we conservatively assume it isn't safe to
2045 // perform a tail call.
2046 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2048 TCChain = Copy->getOperand(0);
2049 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2052 bool HasRet = false;
2053 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055 if (UI->getOpcode() != X86ISD::RET_FLAG)
2068 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2069 ISD::NodeType ExtendKind) const {
2071 // TODO: Is this also valid on 32-bit?
2072 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2073 ReturnMVT = MVT::i8;
2075 ReturnMVT = MVT::i32;
2077 MVT MinVT = getRegisterType(ReturnMVT);
2078 return VT.bitsLT(MinVT) ? MinVT : VT;
2081 /// LowerCallResult - Lower the result values of a call into the
2082 /// appropriate copies out of appropriate physical registers.
2085 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2086 CallingConv::ID CallConv, bool isVarArg,
2087 const SmallVectorImpl<ISD::InputArg> &Ins,
2088 SDLoc dl, SelectionDAG &DAG,
2089 SmallVectorImpl<SDValue> &InVals) const {
2091 // Assign locations to each value returned by this call.
2092 SmallVector<CCValAssign, 16> RVLocs;
2093 bool Is64Bit = Subtarget->is64Bit();
2094 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2095 DAG.getTarget(), RVLocs, *DAG.getContext());
2096 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2098 // Copy all of the result registers out of their specified physreg.
2099 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2100 CCValAssign &VA = RVLocs[i];
2101 EVT CopyVT = VA.getValVT();
2103 // If this is x86-64, and we disabled SSE, we can't return FP values
2104 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2105 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2106 report_fatal_error("SSE register return with SSE disabled");
2111 // If this is a call to a function that returns an fp value on the floating
2112 // point stack, we must guarantee the value is popped from the stack, so
2113 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2114 // if the return value is not used. We use the FpPOP_RETVAL instruction
2116 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2117 // If we prefer to use the value in xmm registers, copy it out as f80 and
2118 // use a truncate to move it from fp stack reg to xmm reg.
2119 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2120 SDValue Ops[] = { Chain, InFlag };
2121 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2122 MVT::Other, MVT::Glue, Ops), 1);
2123 Val = Chain.getValue(0);
2125 // Round the f80 to the right size, which also moves it to the appropriate
2127 if (CopyVT != VA.getValVT())
2128 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2129 // This truncation won't change the value.
2130 DAG.getIntPtrConstant(1));
2132 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2133 CopyVT, InFlag).getValue(1);
2134 Val = Chain.getValue(0);
2136 InFlag = Chain.getValue(2);
2137 InVals.push_back(Val);
2143 //===----------------------------------------------------------------------===//
2144 // C & StdCall & Fast Calling Convention implementation
2145 //===----------------------------------------------------------------------===//
2146 // StdCall calling convention seems to be standard for many Windows' API
2147 // routines and around. It differs from C calling convention just a little:
2148 // callee should clean up the stack, not caller. Symbols should be also
2149 // decorated in some fancy way :) It doesn't support any vector arguments.
2150 // For info on fast calling convention see Fast Calling Convention (tail call)
2151 // implementation LowerX86_32FastCCCallTo.
2153 /// CallIsStructReturn - Determines whether a call uses struct return
2155 enum StructReturnType {
2160 static StructReturnType
2161 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2163 return NotStructReturn;
2165 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2166 if (!Flags.isSRet())
2167 return NotStructReturn;
2168 if (Flags.isInReg())
2169 return RegStructReturn;
2170 return StackStructReturn;
2173 /// ArgsAreStructReturn - Determines whether a function uses struct
2174 /// return semantics.
2175 static StructReturnType
2176 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2178 return NotStructReturn;
2180 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2181 if (!Flags.isSRet())
2182 return NotStructReturn;
2183 if (Flags.isInReg())
2184 return RegStructReturn;
2185 return StackStructReturn;
2188 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2189 /// by "Src" to address "Dst" with size and alignment information specified by
2190 /// the specific parameter attribute. The copy will be passed as a byval
2191 /// function parameter.
2193 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2194 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2196 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2198 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2199 /*isVolatile*/false, /*AlwaysInline=*/true,
2200 MachinePointerInfo(), MachinePointerInfo());
2203 /// IsTailCallConvention - Return true if the calling convention is one that
2204 /// supports tail call optimization.
2205 static bool IsTailCallConvention(CallingConv::ID CC) {
2206 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2207 CC == CallingConv::HiPE);
2210 /// \brief Return true if the calling convention is a C calling convention.
2211 static bool IsCCallConvention(CallingConv::ID CC) {
2212 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2213 CC == CallingConv::X86_64_SysV);
2216 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2217 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2221 CallingConv::ID CalleeCC = CS.getCallingConv();
2222 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2228 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2229 /// a tailcall target by changing its ABI.
2230 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2231 bool GuaranteedTailCallOpt) {
2232 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2236 X86TargetLowering::LowerMemArgument(SDValue Chain,
2237 CallingConv::ID CallConv,
2238 const SmallVectorImpl<ISD::InputArg> &Ins,
2239 SDLoc dl, SelectionDAG &DAG,
2240 const CCValAssign &VA,
2241 MachineFrameInfo *MFI,
2243 // Create the nodes corresponding to a load from this parameter slot.
2244 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2245 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2246 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2247 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2250 // If value is passed by pointer we have address passed instead of the value
2252 if (VA.getLocInfo() == CCValAssign::Indirect)
2253 ValVT = VA.getLocVT();
2255 ValVT = VA.getValVT();
2257 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2258 // changed with more analysis.
2259 // In case of tail call optimization mark all arguments mutable. Since they
2260 // could be overwritten by lowering of arguments in case of a tail call.
2261 if (Flags.isByVal()) {
2262 unsigned Bytes = Flags.getByValSize();
2263 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2264 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2265 return DAG.getFrameIndex(FI, getPointerTy());
2267 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2268 VA.getLocMemOffset(), isImmutable);
2269 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2270 return DAG.getLoad(ValVT, dl, Chain, FIN,
2271 MachinePointerInfo::getFixedStack(FI),
2272 false, false, false, 0);
2277 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2278 CallingConv::ID CallConv,
2280 const SmallVectorImpl<ISD::InputArg> &Ins,
2283 SmallVectorImpl<SDValue> &InVals)
2285 MachineFunction &MF = DAG.getMachineFunction();
2286 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2288 const Function* Fn = MF.getFunction();
2289 if (Fn->hasExternalLinkage() &&
2290 Subtarget->isTargetCygMing() &&
2291 Fn->getName() == "main")
2292 FuncInfo->setForceFramePointer(true);
2294 MachineFrameInfo *MFI = MF.getFrameInfo();
2295 bool Is64Bit = Subtarget->is64Bit();
2296 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2298 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2299 "Var args not supported with calling convention fastcc, ghc or hipe");
2301 // Assign locations to all of the incoming arguments.
2302 SmallVector<CCValAssign, 16> ArgLocs;
2303 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2304 ArgLocs, *DAG.getContext());
2306 // Allocate shadow area for Win64
2308 CCInfo.AllocateStack(32, 8);
2310 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2312 unsigned LastVal = ~0U;
2314 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2315 CCValAssign &VA = ArgLocs[i];
2316 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2318 assert(VA.getValNo() != LastVal &&
2319 "Don't support value assigned to multiple locs yet");
2321 LastVal = VA.getValNo();
2323 if (VA.isRegLoc()) {
2324 EVT RegVT = VA.getLocVT();
2325 const TargetRegisterClass *RC;
2326 if (RegVT == MVT::i32)
2327 RC = &X86::GR32RegClass;
2328 else if (Is64Bit && RegVT == MVT::i64)
2329 RC = &X86::GR64RegClass;
2330 else if (RegVT == MVT::f32)
2331 RC = &X86::FR32RegClass;
2332 else if (RegVT == MVT::f64)
2333 RC = &X86::FR64RegClass;
2334 else if (RegVT.is512BitVector())
2335 RC = &X86::VR512RegClass;
2336 else if (RegVT.is256BitVector())
2337 RC = &X86::VR256RegClass;
2338 else if (RegVT.is128BitVector())
2339 RC = &X86::VR128RegClass;
2340 else if (RegVT == MVT::x86mmx)
2341 RC = &X86::VR64RegClass;
2342 else if (RegVT == MVT::i1)
2343 RC = &X86::VK1RegClass;
2344 else if (RegVT == MVT::v8i1)
2345 RC = &X86::VK8RegClass;
2346 else if (RegVT == MVT::v16i1)
2347 RC = &X86::VK16RegClass;
2348 else if (RegVT == MVT::v32i1)
2349 RC = &X86::VK32RegClass;
2350 else if (RegVT == MVT::v64i1)
2351 RC = &X86::VK64RegClass;
2353 llvm_unreachable("Unknown argument type!");
2355 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2356 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2358 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2359 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2361 if (VA.getLocInfo() == CCValAssign::SExt)
2362 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2363 DAG.getValueType(VA.getValVT()));
2364 else if (VA.getLocInfo() == CCValAssign::ZExt)
2365 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2366 DAG.getValueType(VA.getValVT()));
2367 else if (VA.getLocInfo() == CCValAssign::BCvt)
2368 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2370 if (VA.isExtInLoc()) {
2371 // Handle MMX values passed in XMM regs.
2372 if (RegVT.isVector())
2373 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2375 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2378 assert(VA.isMemLoc());
2379 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2382 // If value is passed via pointer - do a load.
2383 if (VA.getLocInfo() == CCValAssign::Indirect)
2384 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2385 MachinePointerInfo(), false, false, false, 0);
2387 InVals.push_back(ArgValue);
2390 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2391 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2392 // The x86-64 ABIs require that for returning structs by value we copy
2393 // the sret argument into %rax/%eax (depending on ABI) for the return.
2394 // Win32 requires us to put the sret argument to %eax as well.
2395 // Save the argument into a virtual register so that we can access it
2396 // from the return points.
2397 if (Ins[i].Flags.isSRet()) {
2398 unsigned Reg = FuncInfo->getSRetReturnReg();
2400 MVT PtrTy = getPointerTy();
2401 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2402 FuncInfo->setSRetReturnReg(Reg);
2404 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2405 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2411 unsigned StackSize = CCInfo.getNextStackOffset();
2412 // Align stack specially for tail calls.
2413 if (FuncIsMadeTailCallSafe(CallConv,
2414 MF.getTarget().Options.GuaranteedTailCallOpt))
2415 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2417 // If the function takes variable number of arguments, make a frame index for
2418 // the start of the first vararg value... for expansion of llvm.va_start.
2420 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2421 CallConv != CallingConv::X86_ThisCall)) {
2422 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2425 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2427 // FIXME: We should really autogenerate these arrays
2428 static const MCPhysReg GPR64ArgRegsWin64[] = {
2429 X86::RCX, X86::RDX, X86::R8, X86::R9
2431 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2432 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2434 static const MCPhysReg XMMArgRegs64Bit[] = {
2435 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2436 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2438 const MCPhysReg *GPR64ArgRegs;
2439 unsigned NumXMMRegs = 0;
2442 // The XMM registers which might contain var arg parameters are shadowed
2443 // in their paired GPR. So we only need to save the GPR to their home
2445 TotalNumIntRegs = 4;
2446 GPR64ArgRegs = GPR64ArgRegsWin64;
2448 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2449 GPR64ArgRegs = GPR64ArgRegs64Bit;
2451 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2454 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2457 bool NoImplicitFloatOps = Fn->getAttributes().
2458 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2459 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2460 "SSE register cannot be used when SSE is disabled!");
2461 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2462 NoImplicitFloatOps) &&
2463 "SSE register cannot be used when SSE is disabled!");
2464 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2465 !Subtarget->hasSSE1())
2466 // Kernel mode asks for SSE to be disabled, so don't push them
2468 TotalNumXMMRegs = 0;
2471 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2472 // Get to the caller-allocated home save location. Add 8 to account
2473 // for the return address.
2474 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2475 FuncInfo->setRegSaveFrameIndex(
2476 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2477 // Fixup to set vararg frame on shadow area (4 x i64).
2479 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2481 // For X86-64, if there are vararg parameters that are passed via
2482 // registers, then we must store them to their spots on the stack so
2483 // they may be loaded by deferencing the result of va_next.
2484 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2485 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2486 FuncInfo->setRegSaveFrameIndex(
2487 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2491 // Store the integer parameter registers.
2492 SmallVector<SDValue, 8> MemOps;
2493 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2495 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2496 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2497 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2498 DAG.getIntPtrConstant(Offset));
2499 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2500 &X86::GR64RegClass);
2501 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2503 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2504 MachinePointerInfo::getFixedStack(
2505 FuncInfo->getRegSaveFrameIndex(), Offset),
2507 MemOps.push_back(Store);
2511 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2512 // Now store the XMM (fp + vector) parameter registers.
2513 SmallVector<SDValue, 11> SaveXMMOps;
2514 SaveXMMOps.push_back(Chain);
2516 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2517 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2518 SaveXMMOps.push_back(ALVal);
2520 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2521 FuncInfo->getRegSaveFrameIndex()));
2522 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2523 FuncInfo->getVarArgsFPOffset()));
2525 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2526 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2527 &X86::VR128RegClass);
2528 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2529 SaveXMMOps.push_back(Val);
2531 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2532 MVT::Other, SaveXMMOps));
2535 if (!MemOps.empty())
2536 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2540 // Some CCs need callee pop.
2541 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2542 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2543 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2545 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2546 // If this is an sret function, the return should pop the hidden pointer.
2547 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2548 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2549 argsAreStructReturn(Ins) == StackStructReturn)
2550 FuncInfo->setBytesToPopOnReturn(4);
2554 // RegSaveFrameIndex is X86-64 only.
2555 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2556 if (CallConv == CallingConv::X86_FastCall ||
2557 CallConv == CallingConv::X86_ThisCall)
2558 // fastcc functions can't have varargs.
2559 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2562 FuncInfo->setArgumentStackSize(StackSize);
2568 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2569 SDValue StackPtr, SDValue Arg,
2570 SDLoc dl, SelectionDAG &DAG,
2571 const CCValAssign &VA,
2572 ISD::ArgFlagsTy Flags) const {
2573 unsigned LocMemOffset = VA.getLocMemOffset();
2574 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2575 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2576 if (Flags.isByVal())
2577 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2579 return DAG.getStore(Chain, dl, Arg, PtrOff,
2580 MachinePointerInfo::getStack(LocMemOffset),
2584 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2585 /// optimization is performed and it is required.
2587 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2588 SDValue &OutRetAddr, SDValue Chain,
2589 bool IsTailCall, bool Is64Bit,
2590 int FPDiff, SDLoc dl) const {
2591 // Adjust the Return address stack slot.
2592 EVT VT = getPointerTy();
2593 OutRetAddr = getReturnAddressFrameIndex(DAG);
2595 // Load the "old" Return address.
2596 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2597 false, false, false, 0);
2598 return SDValue(OutRetAddr.getNode(), 1);
2601 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2602 /// optimization is performed and it is required (FPDiff!=0).
2603 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2604 SDValue Chain, SDValue RetAddrFrIdx,
2605 EVT PtrVT, unsigned SlotSize,
2606 int FPDiff, SDLoc dl) {
2607 // Store the return address to the appropriate stack slot.
2608 if (!FPDiff) return Chain;
2609 // Calculate the new stack slot for the return address.
2610 int NewReturnAddrFI =
2611 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2613 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2614 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2615 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2621 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2622 SmallVectorImpl<SDValue> &InVals) const {
2623 SelectionDAG &DAG = CLI.DAG;
2625 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2626 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2627 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2628 SDValue Chain = CLI.Chain;
2629 SDValue Callee = CLI.Callee;
2630 CallingConv::ID CallConv = CLI.CallConv;
2631 bool &isTailCall = CLI.IsTailCall;
2632 bool isVarArg = CLI.IsVarArg;
2634 MachineFunction &MF = DAG.getMachineFunction();
2635 bool Is64Bit = Subtarget->is64Bit();
2636 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2637 StructReturnType SR = callIsStructReturn(Outs);
2638 bool IsSibcall = false;
2640 if (MF.getTarget().Options.DisableTailCalls)
2643 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2645 // Force this to be a tail call. The verifier rules are enough to ensure
2646 // that we can lower this successfully without moving the return address
2649 } else if (isTailCall) {
2650 // Check if it's really possible to do a tail call.
2651 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2652 isVarArg, SR != NotStructReturn,
2653 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2654 Outs, OutVals, Ins, DAG);
2656 // Sibcalls are automatically detected tailcalls which do not require
2658 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2665 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2666 "Var args not supported with calling convention fastcc, ghc or hipe");
2668 // Analyze operands of the call, assigning locations to each operand.
2669 SmallVector<CCValAssign, 16> ArgLocs;
2670 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2671 ArgLocs, *DAG.getContext());
2673 // Allocate shadow area for Win64
2675 CCInfo.AllocateStack(32, 8);
2677 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2679 // Get a count of how many bytes are to be pushed on the stack.
2680 unsigned NumBytes = CCInfo.getNextStackOffset();
2682 // This is a sibcall. The memory operands are available in caller's
2683 // own caller's stack.
2685 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2686 IsTailCallConvention(CallConv))
2687 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2690 if (isTailCall && !IsSibcall && !IsMustTail) {
2691 // Lower arguments at fp - stackoffset + fpdiff.
2692 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2693 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2695 FPDiff = NumBytesCallerPushed - NumBytes;
2697 // Set the delta of movement of the returnaddr stackslot.
2698 // But only set if delta is greater than previous delta.
2699 if (FPDiff < X86Info->getTCReturnAddrDelta())
2700 X86Info->setTCReturnAddrDelta(FPDiff);
2703 unsigned NumBytesToPush = NumBytes;
2704 unsigned NumBytesToPop = NumBytes;
2706 // If we have an inalloca argument, all stack space has already been allocated
2707 // for us and be right at the top of the stack. We don't support multiple
2708 // arguments passed in memory when using inalloca.
2709 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2711 if (!ArgLocs.back().isMemLoc())
2712 report_fatal_error("cannot use inalloca attribute on a register "
2714 if (ArgLocs.back().getLocMemOffset() != 0)
2715 report_fatal_error("any parameter with the inalloca attribute must be "
2716 "the only memory argument");
2720 Chain = DAG.getCALLSEQ_START(
2721 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2723 SDValue RetAddrFrIdx;
2724 // Load return address for tail calls.
2725 if (isTailCall && FPDiff)
2726 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2727 Is64Bit, FPDiff, dl);
2729 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2730 SmallVector<SDValue, 8> MemOpChains;
2733 // Walk the register/memloc assignments, inserting copies/loads. In the case
2734 // of tail call optimization arguments are handle later.
2735 const X86RegisterInfo *RegInfo =
2736 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2737 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2738 // Skip inalloca arguments, they have already been written.
2739 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2740 if (Flags.isInAlloca())
2743 CCValAssign &VA = ArgLocs[i];
2744 EVT RegVT = VA.getLocVT();
2745 SDValue Arg = OutVals[i];
2746 bool isByVal = Flags.isByVal();
2748 // Promote the value if needed.
2749 switch (VA.getLocInfo()) {
2750 default: llvm_unreachable("Unknown loc info!");
2751 case CCValAssign::Full: break;
2752 case CCValAssign::SExt:
2753 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2755 case CCValAssign::ZExt:
2756 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2758 case CCValAssign::AExt:
2759 if (RegVT.is128BitVector()) {
2760 // Special case: passing MMX values in XMM registers.
2761 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2762 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2763 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2765 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2767 case CCValAssign::BCvt:
2768 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2770 case CCValAssign::Indirect: {
2771 // Store the argument.
2772 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2773 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2774 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2775 MachinePointerInfo::getFixedStack(FI),
2782 if (VA.isRegLoc()) {
2783 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2784 if (isVarArg && IsWin64) {
2785 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2786 // shadow reg if callee is a varargs function.
2787 unsigned ShadowReg = 0;
2788 switch (VA.getLocReg()) {
2789 case X86::XMM0: ShadowReg = X86::RCX; break;
2790 case X86::XMM1: ShadowReg = X86::RDX; break;
2791 case X86::XMM2: ShadowReg = X86::R8; break;
2792 case X86::XMM3: ShadowReg = X86::R9; break;
2795 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2797 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2798 assert(VA.isMemLoc());
2799 if (!StackPtr.getNode())
2800 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2802 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2803 dl, DAG, VA, Flags));
2807 if (!MemOpChains.empty())
2808 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2810 if (Subtarget->isPICStyleGOT()) {
2811 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2814 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2815 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2817 // If we are tail calling and generating PIC/GOT style code load the
2818 // address of the callee into ECX. The value in ecx is used as target of
2819 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2820 // for tail calls on PIC/GOT architectures. Normally we would just put the
2821 // address of GOT into ebx and then call target@PLT. But for tail calls
2822 // ebx would be restored (since ebx is callee saved) before jumping to the
2825 // Note: The actual moving to ECX is done further down.
2826 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2827 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2828 !G->getGlobal()->hasProtectedVisibility())
2829 Callee = LowerGlobalAddress(Callee, DAG);
2830 else if (isa<ExternalSymbolSDNode>(Callee))
2831 Callee = LowerExternalSymbol(Callee, DAG);
2835 if (Is64Bit && isVarArg && !IsWin64) {
2836 // From AMD64 ABI document:
2837 // For calls that may call functions that use varargs or stdargs
2838 // (prototype-less calls or calls to functions containing ellipsis (...) in
2839 // the declaration) %al is used as hidden argument to specify the number
2840 // of SSE registers used. The contents of %al do not need to match exactly
2841 // the number of registers, but must be an ubound on the number of SSE
2842 // registers used and is in the range 0 - 8 inclusive.
2844 // Count the number of XMM registers allocated.
2845 static const MCPhysReg XMMArgRegs[] = {
2846 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2847 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2849 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2850 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2851 && "SSE registers cannot be used when SSE is disabled");
2853 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2854 DAG.getConstant(NumXMMRegs, MVT::i8)));
2857 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2858 // don't need this because the eligibility check rejects calls that require
2859 // shuffling arguments passed in memory.
2860 if (!IsSibcall && isTailCall) {
2861 // Force all the incoming stack arguments to be loaded from the stack
2862 // before any new outgoing arguments are stored to the stack, because the
2863 // outgoing stack slots may alias the incoming argument stack slots, and
2864 // the alias isn't otherwise explicit. This is slightly more conservative
2865 // than necessary, because it means that each store effectively depends
2866 // on every argument instead of just those arguments it would clobber.
2867 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2869 SmallVector<SDValue, 8> MemOpChains2;
2872 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2873 CCValAssign &VA = ArgLocs[i];
2876 assert(VA.isMemLoc());
2877 SDValue Arg = OutVals[i];
2878 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2879 // Skip inalloca arguments. They don't require any work.
2880 if (Flags.isInAlloca())
2882 // Create frame index.
2883 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2884 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2885 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2886 FIN = DAG.getFrameIndex(FI, getPointerTy());
2888 if (Flags.isByVal()) {
2889 // Copy relative to framepointer.
2890 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2891 if (!StackPtr.getNode())
2892 StackPtr = DAG.getCopyFromReg(Chain, dl,
2893 RegInfo->getStackRegister(),
2895 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2897 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2901 // Store relative to framepointer.
2902 MemOpChains2.push_back(
2903 DAG.getStore(ArgChain, dl, Arg, FIN,
2904 MachinePointerInfo::getFixedStack(FI),
2909 if (!MemOpChains2.empty())
2910 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2912 // Store the return address to the appropriate stack slot.
2913 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2914 getPointerTy(), RegInfo->getSlotSize(),
2918 // Build a sequence of copy-to-reg nodes chained together with token chain
2919 // and flag operands which copy the outgoing args into registers.
2921 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2922 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2923 RegsToPass[i].second, InFlag);
2924 InFlag = Chain.getValue(1);
2927 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2928 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2929 // In the 64-bit large code model, we have to make all calls
2930 // through a register, since the call instruction's 32-bit
2931 // pc-relative offset may not be large enough to hold the whole
2933 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2934 // If the callee is a GlobalAddress node (quite common, every direct call
2935 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2938 // We should use extra load for direct calls to dllimported functions in
2940 const GlobalValue *GV = G->getGlobal();
2941 if (!GV->hasDLLImportStorageClass()) {
2942 unsigned char OpFlags = 0;
2943 bool ExtraLoad = false;
2944 unsigned WrapperKind = ISD::DELETED_NODE;
2946 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2947 // external symbols most go through the PLT in PIC mode. If the symbol
2948 // has hidden or protected visibility, or if it is static or local, then
2949 // we don't need to use the PLT - we can directly call it.
2950 if (Subtarget->isTargetELF() &&
2951 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2952 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2953 OpFlags = X86II::MO_PLT;
2954 } else if (Subtarget->isPICStyleStubAny() &&
2955 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2956 (!Subtarget->getTargetTriple().isMacOSX() ||
2957 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2958 // PC-relative references to external symbols should go through $stub,
2959 // unless we're building with the leopard linker or later, which
2960 // automatically synthesizes these stubs.
2961 OpFlags = X86II::MO_DARWIN_STUB;
2962 } else if (Subtarget->isPICStyleRIPRel() &&
2963 isa<Function>(GV) &&
2964 cast<Function>(GV)->getAttributes().
2965 hasAttribute(AttributeSet::FunctionIndex,
2966 Attribute::NonLazyBind)) {
2967 // If the function is marked as non-lazy, generate an indirect call
2968 // which loads from the GOT directly. This avoids runtime overhead
2969 // at the cost of eager binding (and one extra byte of encoding).
2970 OpFlags = X86II::MO_GOTPCREL;
2971 WrapperKind = X86ISD::WrapperRIP;
2975 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2976 G->getOffset(), OpFlags);
2978 // Add a wrapper if needed.
2979 if (WrapperKind != ISD::DELETED_NODE)
2980 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2981 // Add extra indirection if needed.
2983 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2984 MachinePointerInfo::getGOT(),
2985 false, false, false, 0);
2987 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2988 unsigned char OpFlags = 0;
2990 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2991 // external symbols should go through the PLT.
2992 if (Subtarget->isTargetELF() &&
2993 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2994 OpFlags = X86II::MO_PLT;
2995 } else if (Subtarget->isPICStyleStubAny() &&
2996 (!Subtarget->getTargetTriple().isMacOSX() ||
2997 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2998 // PC-relative references to external symbols should go through $stub,
2999 // unless we're building with the leopard linker or later, which
3000 // automatically synthesizes these stubs.
3001 OpFlags = X86II::MO_DARWIN_STUB;
3004 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3008 // Returns a chain & a flag for retval copy to use.
3009 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3010 SmallVector<SDValue, 8> Ops;
3012 if (!IsSibcall && isTailCall) {
3013 Chain = DAG.getCALLSEQ_END(Chain,
3014 DAG.getIntPtrConstant(NumBytesToPop, true),
3015 DAG.getIntPtrConstant(0, true), InFlag, dl);
3016 InFlag = Chain.getValue(1);
3019 Ops.push_back(Chain);
3020 Ops.push_back(Callee);
3023 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3025 // Add argument registers to the end of the list so that they are known live
3027 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3028 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3029 RegsToPass[i].second.getValueType()));
3031 // Add a register mask operand representing the call-preserved registers.
3032 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3033 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3034 assert(Mask && "Missing call preserved mask for calling convention");
3035 Ops.push_back(DAG.getRegisterMask(Mask));
3037 if (InFlag.getNode())
3038 Ops.push_back(InFlag);
3042 //// If this is the first return lowered for this function, add the regs
3043 //// to the liveout set for the function.
3044 // This isn't right, although it's probably harmless on x86; liveouts
3045 // should be computed from returns not tail calls. Consider a void
3046 // function making a tail call to a function returning int.
3047 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3050 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3051 InFlag = Chain.getValue(1);
3053 // Create the CALLSEQ_END node.
3054 unsigned NumBytesForCalleeToPop;
3055 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3056 DAG.getTarget().Options.GuaranteedTailCallOpt))
3057 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3058 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3059 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3060 SR == StackStructReturn)
3061 // If this is a call to a struct-return function, the callee
3062 // pops the hidden struct pointer, so we have to push it back.
3063 // This is common for Darwin/X86, Linux & Mingw32 targets.
3064 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3065 NumBytesForCalleeToPop = 4;
3067 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3069 // Returns a flag for retval copy to use.
3071 Chain = DAG.getCALLSEQ_END(Chain,
3072 DAG.getIntPtrConstant(NumBytesToPop, true),
3073 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3076 InFlag = Chain.getValue(1);
3079 // Handle result values, copying them out of physregs into vregs that we
3081 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3082 Ins, dl, DAG, InVals);
3085 //===----------------------------------------------------------------------===//
3086 // Fast Calling Convention (tail call) implementation
3087 //===----------------------------------------------------------------------===//
3089 // Like std call, callee cleans arguments, convention except that ECX is
3090 // reserved for storing the tail called function address. Only 2 registers are
3091 // free for argument passing (inreg). Tail call optimization is performed
3093 // * tailcallopt is enabled
3094 // * caller/callee are fastcc
3095 // On X86_64 architecture with GOT-style position independent code only local
3096 // (within module) calls are supported at the moment.
3097 // To keep the stack aligned according to platform abi the function
3098 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3099 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3100 // If a tail called function callee has more arguments than the caller the
3101 // caller needs to make sure that there is room to move the RETADDR to. This is
3102 // achieved by reserving an area the size of the argument delta right after the
3103 // original RETADDR, but before the saved framepointer or the spilled registers
3104 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3116 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3117 /// for a 16 byte align requirement.
3119 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3120 SelectionDAG& DAG) const {
3121 MachineFunction &MF = DAG.getMachineFunction();
3122 const TargetMachine &TM = MF.getTarget();
3123 const X86RegisterInfo *RegInfo =
3124 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3125 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3126 unsigned StackAlignment = TFI.getStackAlignment();
3127 uint64_t AlignMask = StackAlignment - 1;
3128 int64_t Offset = StackSize;
3129 unsigned SlotSize = RegInfo->getSlotSize();
3130 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3131 // Number smaller than 12 so just add the difference.
3132 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3134 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3135 Offset = ((~AlignMask) & Offset) + StackAlignment +
3136 (StackAlignment-SlotSize);
3141 /// MatchingStackOffset - Return true if the given stack call argument is
3142 /// already available in the same position (relatively) of the caller's
3143 /// incoming argument stack.
3145 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3146 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3147 const X86InstrInfo *TII) {
3148 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3150 if (Arg.getOpcode() == ISD::CopyFromReg) {
3151 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3152 if (!TargetRegisterInfo::isVirtualRegister(VR))
3154 MachineInstr *Def = MRI->getVRegDef(VR);
3157 if (!Flags.isByVal()) {
3158 if (!TII->isLoadFromStackSlot(Def, FI))
3161 unsigned Opcode = Def->getOpcode();
3162 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3163 Def->getOperand(1).isFI()) {
3164 FI = Def->getOperand(1).getIndex();
3165 Bytes = Flags.getByValSize();
3169 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3170 if (Flags.isByVal())
3171 // ByVal argument is passed in as a pointer but it's now being
3172 // dereferenced. e.g.
3173 // define @foo(%struct.X* %A) {
3174 // tail call @bar(%struct.X* byval %A)
3177 SDValue Ptr = Ld->getBasePtr();
3178 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3181 FI = FINode->getIndex();
3182 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3183 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3184 FI = FINode->getIndex();
3185 Bytes = Flags.getByValSize();
3189 assert(FI != INT_MAX);
3190 if (!MFI->isFixedObjectIndex(FI))
3192 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3195 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3196 /// for tail call optimization. Targets which want to do tail call
3197 /// optimization should implement this function.
3199 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3200 CallingConv::ID CalleeCC,
3202 bool isCalleeStructRet,
3203 bool isCallerStructRet,
3205 const SmallVectorImpl<ISD::OutputArg> &Outs,
3206 const SmallVectorImpl<SDValue> &OutVals,
3207 const SmallVectorImpl<ISD::InputArg> &Ins,
3208 SelectionDAG &DAG) const {
3209 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3212 // If -tailcallopt is specified, make fastcc functions tail-callable.
3213 const MachineFunction &MF = DAG.getMachineFunction();
3214 const Function *CallerF = MF.getFunction();
3216 // If the function return type is x86_fp80 and the callee return type is not,
3217 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3218 // perform a tailcall optimization here.
3219 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3222 CallingConv::ID CallerCC = CallerF->getCallingConv();
3223 bool CCMatch = CallerCC == CalleeCC;
3224 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3225 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3227 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3228 if (IsTailCallConvention(CalleeCC) && CCMatch)
3233 // Look for obvious safe cases to perform tail call optimization that do not
3234 // require ABI changes. This is what gcc calls sibcall.
3236 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3237 // emit a special epilogue.
3238 const X86RegisterInfo *RegInfo =
3239 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3240 if (RegInfo->needsStackRealignment(MF))
3243 // Also avoid sibcall optimization if either caller or callee uses struct
3244 // return semantics.
3245 if (isCalleeStructRet || isCallerStructRet)
3248 // An stdcall/thiscall caller is expected to clean up its arguments; the
3249 // callee isn't going to do that.
3250 // FIXME: this is more restrictive than needed. We could produce a tailcall
3251 // when the stack adjustment matches. For example, with a thiscall that takes
3252 // only one argument.
3253 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3254 CallerCC == CallingConv::X86_ThisCall))
3257 // Do not sibcall optimize vararg calls unless all arguments are passed via
3259 if (isVarArg && !Outs.empty()) {
3261 // Optimizing for varargs on Win64 is unlikely to be safe without
3262 // additional testing.
3263 if (IsCalleeWin64 || IsCallerWin64)
3266 SmallVector<CCValAssign, 16> ArgLocs;
3267 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3268 DAG.getTarget(), ArgLocs, *DAG.getContext());
3270 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3271 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3272 if (!ArgLocs[i].isRegLoc())
3276 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3277 // stack. Therefore, if it's not used by the call it is not safe to optimize
3278 // this into a sibcall.
3279 bool Unused = false;
3280 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3287 SmallVector<CCValAssign, 16> RVLocs;
3288 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3289 DAG.getTarget(), RVLocs, *DAG.getContext());
3290 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3291 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3292 CCValAssign &VA = RVLocs[i];
3293 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3298 // If the calling conventions do not match, then we'd better make sure the
3299 // results are returned in the same way as what the caller expects.
3301 SmallVector<CCValAssign, 16> RVLocs1;
3302 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3303 DAG.getTarget(), RVLocs1, *DAG.getContext());
3304 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3306 SmallVector<CCValAssign, 16> RVLocs2;
3307 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3308 DAG.getTarget(), RVLocs2, *DAG.getContext());
3309 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3311 if (RVLocs1.size() != RVLocs2.size())
3313 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3314 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3316 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3318 if (RVLocs1[i].isRegLoc()) {
3319 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3322 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3328 // If the callee takes no arguments then go on to check the results of the
3330 if (!Outs.empty()) {
3331 // Check if stack adjustment is needed. For now, do not do this if any
3332 // argument is passed on the stack.
3333 SmallVector<CCValAssign, 16> ArgLocs;
3334 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3335 DAG.getTarget(), ArgLocs, *DAG.getContext());
3337 // Allocate shadow area for Win64
3339 CCInfo.AllocateStack(32, 8);
3341 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3342 if (CCInfo.getNextStackOffset()) {
3343 MachineFunction &MF = DAG.getMachineFunction();
3344 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3347 // Check if the arguments are already laid out in the right way as
3348 // the caller's fixed stack objects.
3349 MachineFrameInfo *MFI = MF.getFrameInfo();
3350 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3351 const X86InstrInfo *TII =
3352 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3353 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3354 CCValAssign &VA = ArgLocs[i];
3355 SDValue Arg = OutVals[i];
3356 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3357 if (VA.getLocInfo() == CCValAssign::Indirect)
3359 if (!VA.isRegLoc()) {
3360 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3367 // If the tailcall address may be in a register, then make sure it's
3368 // possible to register allocate for it. In 32-bit, the call address can
3369 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3370 // callee-saved registers are restored. These happen to be the same
3371 // registers used to pass 'inreg' arguments so watch out for those.
3372 if (!Subtarget->is64Bit() &&
3373 ((!isa<GlobalAddressSDNode>(Callee) &&
3374 !isa<ExternalSymbolSDNode>(Callee)) ||
3375 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3376 unsigned NumInRegs = 0;
3377 // In PIC we need an extra register to formulate the address computation
3379 unsigned MaxInRegs =
3380 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3382 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3383 CCValAssign &VA = ArgLocs[i];
3386 unsigned Reg = VA.getLocReg();
3389 case X86::EAX: case X86::EDX: case X86::ECX:
3390 if (++NumInRegs == MaxInRegs)
3402 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3403 const TargetLibraryInfo *libInfo) const {
3404 return X86::createFastISel(funcInfo, libInfo);
3407 //===----------------------------------------------------------------------===//
3408 // Other Lowering Hooks
3409 //===----------------------------------------------------------------------===//
3411 static bool MayFoldLoad(SDValue Op) {
3412 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3415 static bool MayFoldIntoStore(SDValue Op) {
3416 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3419 static bool isTargetShuffle(unsigned Opcode) {
3421 default: return false;
3422 case X86ISD::PSHUFD:
3423 case X86ISD::PSHUFHW:
3424 case X86ISD::PSHUFLW:
3426 case X86ISD::PALIGNR:
3427 case X86ISD::MOVLHPS:
3428 case X86ISD::MOVLHPD:
3429 case X86ISD::MOVHLPS:
3430 case X86ISD::MOVLPS:
3431 case X86ISD::MOVLPD:
3432 case X86ISD::MOVSHDUP:
3433 case X86ISD::MOVSLDUP:
3434 case X86ISD::MOVDDUP:
3437 case X86ISD::UNPCKL:
3438 case X86ISD::UNPCKH:
3439 case X86ISD::VPERMILP:
3440 case X86ISD::VPERM2X128:
3441 case X86ISD::VPERMI:
3446 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3447 SDValue V1, SelectionDAG &DAG) {
3449 default: llvm_unreachable("Unknown x86 shuffle node");
3450 case X86ISD::MOVSHDUP:
3451 case X86ISD::MOVSLDUP:
3452 case X86ISD::MOVDDUP:
3453 return DAG.getNode(Opc, dl, VT, V1);
3457 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3458 SDValue V1, unsigned TargetMask,
3459 SelectionDAG &DAG) {
3461 default: llvm_unreachable("Unknown x86 shuffle node");
3462 case X86ISD::PSHUFD:
3463 case X86ISD::PSHUFHW:
3464 case X86ISD::PSHUFLW:
3465 case X86ISD::VPERMILP:
3466 case X86ISD::VPERMI:
3467 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3471 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3472 SDValue V1, SDValue V2, unsigned TargetMask,
3473 SelectionDAG &DAG) {
3475 default: llvm_unreachable("Unknown x86 shuffle node");
3476 case X86ISD::PALIGNR:
3478 case X86ISD::VPERM2X128:
3479 return DAG.getNode(Opc, dl, VT, V1, V2,
3480 DAG.getConstant(TargetMask, MVT::i8));
3484 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3485 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3487 default: llvm_unreachable("Unknown x86 shuffle node");
3488 case X86ISD::MOVLHPS:
3489 case X86ISD::MOVLHPD:
3490 case X86ISD::MOVHLPS:
3491 case X86ISD::MOVLPS:
3492 case X86ISD::MOVLPD:
3495 case X86ISD::UNPCKL:
3496 case X86ISD::UNPCKH:
3497 return DAG.getNode(Opc, dl, VT, V1, V2);
3501 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3502 MachineFunction &MF = DAG.getMachineFunction();
3503 const X86RegisterInfo *RegInfo =
3504 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3505 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3506 int ReturnAddrIndex = FuncInfo->getRAIndex();
3508 if (ReturnAddrIndex == 0) {
3509 // Set up a frame object for the return address.
3510 unsigned SlotSize = RegInfo->getSlotSize();
3511 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3514 FuncInfo->setRAIndex(ReturnAddrIndex);
3517 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3520 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3521 bool hasSymbolicDisplacement) {
3522 // Offset should fit into 32 bit immediate field.
3523 if (!isInt<32>(Offset))
3526 // If we don't have a symbolic displacement - we don't have any extra
3528 if (!hasSymbolicDisplacement)
3531 // FIXME: Some tweaks might be needed for medium code model.
3532 if (M != CodeModel::Small && M != CodeModel::Kernel)
3535 // For small code model we assume that latest object is 16MB before end of 31
3536 // bits boundary. We may also accept pretty large negative constants knowing
3537 // that all objects are in the positive half of address space.
3538 if (M == CodeModel::Small && Offset < 16*1024*1024)
3541 // For kernel code model we know that all object resist in the negative half
3542 // of 32bits address space. We may not accept negative offsets, since they may
3543 // be just off and we may accept pretty large positive ones.
3544 if (M == CodeModel::Kernel && Offset > 0)
3550 /// isCalleePop - Determines whether the callee is required to pop its
3551 /// own arguments. Callee pop is necessary to support tail calls.
3552 bool X86::isCalleePop(CallingConv::ID CallingConv,
3553 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3557 switch (CallingConv) {
3560 case CallingConv::X86_StdCall:
3562 case CallingConv::X86_FastCall:
3564 case CallingConv::X86_ThisCall:
3566 case CallingConv::Fast:
3568 case CallingConv::GHC:
3570 case CallingConv::HiPE:
3575 /// \brief Return true if the condition is an unsigned comparison operation.
3576 static bool isX86CCUnsigned(unsigned X86CC) {
3578 default: llvm_unreachable("Invalid integer condition!");
3579 case X86::COND_E: return true;
3580 case X86::COND_G: return false;
3581 case X86::COND_GE: return false;
3582 case X86::COND_L: return false;
3583 case X86::COND_LE: return false;
3584 case X86::COND_NE: return true;
3585 case X86::COND_B: return true;
3586 case X86::COND_A: return true;
3587 case X86::COND_BE: return true;
3588 case X86::COND_AE: return true;
3590 llvm_unreachable("covered switch fell through?!");
3593 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3594 /// specific condition code, returning the condition code and the LHS/RHS of the
3595 /// comparison to make.
3596 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3597 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3599 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3600 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3601 // X > -1 -> X == 0, jump !sign.
3602 RHS = DAG.getConstant(0, RHS.getValueType());
3603 return X86::COND_NS;
3605 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3606 // X < 0 -> X == 0, jump on sign.
3609 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3611 RHS = DAG.getConstant(0, RHS.getValueType());
3612 return X86::COND_LE;
3616 switch (SetCCOpcode) {
3617 default: llvm_unreachable("Invalid integer condition!");
3618 case ISD::SETEQ: return X86::COND_E;
3619 case ISD::SETGT: return X86::COND_G;
3620 case ISD::SETGE: return X86::COND_GE;
3621 case ISD::SETLT: return X86::COND_L;
3622 case ISD::SETLE: return X86::COND_LE;
3623 case ISD::SETNE: return X86::COND_NE;
3624 case ISD::SETULT: return X86::COND_B;
3625 case ISD::SETUGT: return X86::COND_A;
3626 case ISD::SETULE: return X86::COND_BE;
3627 case ISD::SETUGE: return X86::COND_AE;
3631 // First determine if it is required or is profitable to flip the operands.
3633 // If LHS is a foldable load, but RHS is not, flip the condition.
3634 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3635 !ISD::isNON_EXTLoad(RHS.getNode())) {
3636 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3637 std::swap(LHS, RHS);
3640 switch (SetCCOpcode) {
3646 std::swap(LHS, RHS);
3650 // On a floating point condition, the flags are set as follows:
3652 // 0 | 0 | 0 | X > Y
3653 // 0 | 0 | 1 | X < Y
3654 // 1 | 0 | 0 | X == Y
3655 // 1 | 1 | 1 | unordered
3656 switch (SetCCOpcode) {
3657 default: llvm_unreachable("Condcode should be pre-legalized away");
3659 case ISD::SETEQ: return X86::COND_E;
3660 case ISD::SETOLT: // flipped
3662 case ISD::SETGT: return X86::COND_A;
3663 case ISD::SETOLE: // flipped
3665 case ISD::SETGE: return X86::COND_AE;
3666 case ISD::SETUGT: // flipped
3668 case ISD::SETLT: return X86::COND_B;
3669 case ISD::SETUGE: // flipped
3671 case ISD::SETLE: return X86::COND_BE;
3673 case ISD::SETNE: return X86::COND_NE;
3674 case ISD::SETUO: return X86::COND_P;
3675 case ISD::SETO: return X86::COND_NP;
3677 case ISD::SETUNE: return X86::COND_INVALID;
3681 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3682 /// code. Current x86 isa includes the following FP cmov instructions:
3683 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3684 static bool hasFPCMov(unsigned X86CC) {
3700 /// isFPImmLegal - Returns true if the target can instruction select the
3701 /// specified FP immediate natively. If false, the legalizer will
3702 /// materialize the FP immediate as a load from a constant pool.
3703 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3704 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3705 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3711 /// \brief Returns true if it is beneficial to convert a load of a constant
3712 /// to just the constant itself.
3713 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3715 assert(Ty->isIntegerTy());
3717 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3718 if (BitSize == 0 || BitSize > 64)
3723 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3724 /// the specified range (L, H].
3725 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3726 return (Val < 0) || (Val >= Low && Val < Hi);
3729 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3730 /// specified value.
3731 static bool isUndefOrEqual(int Val, int CmpVal) {
3732 return (Val < 0 || Val == CmpVal);
3735 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3736 /// from position Pos and ending in Pos+Size, falls within the specified
3737 /// sequential range (L, L+Pos]. or is undef.
3738 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3739 unsigned Pos, unsigned Size, int Low) {
3740 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3741 if (!isUndefOrEqual(Mask[i], Low))
3746 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3747 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3748 /// the second operand.
3749 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3750 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3751 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3752 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3753 return (Mask[0] < 2 && Mask[1] < 2);
3757 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3758 /// is suitable for input to PSHUFHW.
3759 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3760 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3763 // Lower quadword copied in order or undef.
3764 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3767 // Upper quadword shuffled.
3768 for (unsigned i = 4; i != 8; ++i)
3769 if (!isUndefOrInRange(Mask[i], 4, 8))
3772 if (VT == MVT::v16i16) {
3773 // Lower quadword copied in order or undef.
3774 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3777 // Upper quadword shuffled.
3778 for (unsigned i = 12; i != 16; ++i)
3779 if (!isUndefOrInRange(Mask[i], 12, 16))
3786 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3787 /// is suitable for input to PSHUFLW.
3788 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3789 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3792 // Upper quadword copied in order.
3793 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3796 // Lower quadword shuffled.
3797 for (unsigned i = 0; i != 4; ++i)
3798 if (!isUndefOrInRange(Mask[i], 0, 4))
3801 if (VT == MVT::v16i16) {
3802 // Upper quadword copied in order.
3803 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3806 // Lower quadword shuffled.
3807 for (unsigned i = 8; i != 12; ++i)
3808 if (!isUndefOrInRange(Mask[i], 8, 12))
3815 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3816 /// is suitable for input to PALIGNR.
3817 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3818 const X86Subtarget *Subtarget) {
3819 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3820 (VT.is256BitVector() && !Subtarget->hasInt256()))
3823 unsigned NumElts = VT.getVectorNumElements();
3824 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3825 unsigned NumLaneElts = NumElts/NumLanes;
3827 // Do not handle 64-bit element shuffles with palignr.
3828 if (NumLaneElts == 2)
3831 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3833 for (i = 0; i != NumLaneElts; ++i) {
3838 // Lane is all undef, go to next lane
3839 if (i == NumLaneElts)
3842 int Start = Mask[i+l];
3844 // Make sure its in this lane in one of the sources
3845 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3846 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3849 // If not lane 0, then we must match lane 0
3850 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3853 // Correct second source to be contiguous with first source
3854 if (Start >= (int)NumElts)
3855 Start -= NumElts - NumLaneElts;
3857 // Make sure we're shifting in the right direction.
3858 if (Start <= (int)(i+l))
3863 // Check the rest of the elements to see if they are consecutive.
3864 for (++i; i != NumLaneElts; ++i) {
3865 int Idx = Mask[i+l];
3867 // Make sure its in this lane
3868 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3869 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3872 // If not lane 0, then we must match lane 0
3873 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3876 if (Idx >= (int)NumElts)
3877 Idx -= NumElts - NumLaneElts;
3879 if (!isUndefOrEqual(Idx, Start+i))
3888 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3889 /// the two vector operands have swapped position.
3890 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3891 unsigned NumElems) {
3892 for (unsigned i = 0; i != NumElems; ++i) {
3896 else if (idx < (int)NumElems)
3897 Mask[i] = idx + NumElems;
3899 Mask[i] = idx - NumElems;
3903 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3905 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3906 /// reverse of what x86 shuffles want.
3907 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3909 unsigned NumElems = VT.getVectorNumElements();
3910 unsigned NumLanes = VT.getSizeInBits()/128;
3911 unsigned NumLaneElems = NumElems/NumLanes;
3913 if (NumLaneElems != 2 && NumLaneElems != 4)
3916 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3917 bool symetricMaskRequired =
3918 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3920 // VSHUFPSY divides the resulting vector into 4 chunks.
3921 // The sources are also splitted into 4 chunks, and each destination
3922 // chunk must come from a different source chunk.
3924 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3925 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3927 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3928 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3930 // VSHUFPDY divides the resulting vector into 4 chunks.
3931 // The sources are also splitted into 4 chunks, and each destination
3932 // chunk must come from a different source chunk.
3934 // SRC1 => X3 X2 X1 X0
3935 // SRC2 => Y3 Y2 Y1 Y0
3937 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3939 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3940 unsigned HalfLaneElems = NumLaneElems/2;
3941 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3942 for (unsigned i = 0; i != NumLaneElems; ++i) {
3943 int Idx = Mask[i+l];
3944 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3945 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3947 // For VSHUFPSY, the mask of the second half must be the same as the
3948 // first but with the appropriate offsets. This works in the same way as
3949 // VPERMILPS works with masks.
3950 if (!symetricMaskRequired || Idx < 0)
3952 if (MaskVal[i] < 0) {
3953 MaskVal[i] = Idx - l;
3956 if ((signed)(Idx - l) != MaskVal[i])
3964 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3965 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3966 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3967 if (!VT.is128BitVector())
3970 unsigned NumElems = VT.getVectorNumElements();
3975 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3976 return isUndefOrEqual(Mask[0], 6) &&
3977 isUndefOrEqual(Mask[1], 7) &&
3978 isUndefOrEqual(Mask[2], 2) &&
3979 isUndefOrEqual(Mask[3], 3);
3982 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3983 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3985 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3986 if (!VT.is128BitVector())
3989 unsigned NumElems = VT.getVectorNumElements();
3994 return isUndefOrEqual(Mask[0], 2) &&
3995 isUndefOrEqual(Mask[1], 3) &&
3996 isUndefOrEqual(Mask[2], 2) &&
3997 isUndefOrEqual(Mask[3], 3);
4000 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4001 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4002 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4003 if (!VT.is128BitVector())
4006 unsigned NumElems = VT.getVectorNumElements();
4008 if (NumElems != 2 && NumElems != 4)
4011 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4012 if (!isUndefOrEqual(Mask[i], i + NumElems))
4015 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4016 if (!isUndefOrEqual(Mask[i], i))
4022 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4023 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4024 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4025 if (!VT.is128BitVector())
4028 unsigned NumElems = VT.getVectorNumElements();
4030 if (NumElems != 2 && NumElems != 4)
4033 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4034 if (!isUndefOrEqual(Mask[i], i))
4037 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4038 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4044 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4045 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4046 /// i. e: If all but one element come from the same vector.
4047 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4048 // TODO: Deal with AVX's VINSERTPS
4049 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4052 unsigned CorrectPosV1 = 0;
4053 unsigned CorrectPosV2 = 0;
4054 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4055 if (Mask[i] == -1) {
4063 else if (Mask[i] == i + 4)
4067 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4068 // We have 3 elements (undefs count as elements from any vector) from one
4069 // vector, and one from another.
4076 // Some special combinations that can be optimized.
4079 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4080 SelectionDAG &DAG) {
4081 MVT VT = SVOp->getSimpleValueType(0);
4084 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4087 ArrayRef<int> Mask = SVOp->getMask();
4089 // These are the special masks that may be optimized.
4090 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4091 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4092 bool MatchEvenMask = true;
4093 bool MatchOddMask = true;
4094 for (int i=0; i<8; ++i) {
4095 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4096 MatchEvenMask = false;
4097 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4098 MatchOddMask = false;
4101 if (!MatchEvenMask && !MatchOddMask)
4104 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4106 SDValue Op0 = SVOp->getOperand(0);
4107 SDValue Op1 = SVOp->getOperand(1);
4109 if (MatchEvenMask) {
4110 // Shift the second operand right to 32 bits.
4111 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4112 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4114 // Shift the first operand left to 32 bits.
4115 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4116 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4118 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4119 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4122 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4123 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4124 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4125 bool HasInt256, bool V2IsSplat = false) {
4127 assert(VT.getSizeInBits() >= 128 &&
4128 "Unsupported vector type for unpckl");
4130 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4132 unsigned NumOf256BitLanes;
4133 unsigned NumElts = VT.getVectorNumElements();
4134 if (VT.is256BitVector()) {
4135 if (NumElts != 4 && NumElts != 8 &&
4136 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4139 NumOf256BitLanes = 1;
4140 } else if (VT.is512BitVector()) {
4141 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4142 "Unsupported vector type for unpckh");
4144 NumOf256BitLanes = 2;
4147 NumOf256BitLanes = 1;
4150 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4151 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4153 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4154 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4155 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4156 int BitI = Mask[l256*NumEltsInStride+l+i];
4157 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4158 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4160 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4162 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4170 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4171 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4172 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4173 bool HasInt256, bool V2IsSplat = false) {
4174 assert(VT.getSizeInBits() >= 128 &&
4175 "Unsupported vector type for unpckh");
4177 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4179 unsigned NumOf256BitLanes;
4180 unsigned NumElts = VT.getVectorNumElements();
4181 if (VT.is256BitVector()) {
4182 if (NumElts != 4 && NumElts != 8 &&
4183 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4186 NumOf256BitLanes = 1;
4187 } else if (VT.is512BitVector()) {
4188 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4189 "Unsupported vector type for unpckh");
4191 NumOf256BitLanes = 2;
4194 NumOf256BitLanes = 1;
4197 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4198 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4200 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4201 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4202 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4203 int BitI = Mask[l256*NumEltsInStride+l+i];
4204 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4205 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4207 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4209 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4217 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4218 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4220 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4221 unsigned NumElts = VT.getVectorNumElements();
4222 bool Is256BitVec = VT.is256BitVector();
4224 if (VT.is512BitVector())
4226 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4227 "Unsupported vector type for unpckh");
4229 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4230 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4233 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4234 // FIXME: Need a better way to get rid of this, there's no latency difference
4235 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4236 // the former later. We should also remove the "_undef" special mask.
4237 if (NumElts == 4 && Is256BitVec)
4240 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4241 // independently on 128-bit lanes.
4242 unsigned NumLanes = VT.getSizeInBits()/128;
4243 unsigned NumLaneElts = NumElts/NumLanes;
4245 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4246 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4247 int BitI = Mask[l+i];
4248 int BitI1 = Mask[l+i+1];
4250 if (!isUndefOrEqual(BitI, j))
4252 if (!isUndefOrEqual(BitI1, j))
4260 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4261 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4263 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4264 unsigned NumElts = VT.getVectorNumElements();
4266 if (VT.is512BitVector())
4269 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4270 "Unsupported vector type for unpckh");
4272 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4273 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4276 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4277 // independently on 128-bit lanes.
4278 unsigned NumLanes = VT.getSizeInBits()/128;
4279 unsigned NumLaneElts = NumElts/NumLanes;
4281 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4282 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4283 int BitI = Mask[l+i];
4284 int BitI1 = Mask[l+i+1];
4285 if (!isUndefOrEqual(BitI, j))
4287 if (!isUndefOrEqual(BitI1, j))
4294 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4295 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4296 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4297 if (!VT.is512BitVector())
4300 unsigned NumElts = VT.getVectorNumElements();
4301 unsigned HalfSize = NumElts/2;
4302 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4303 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4308 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4309 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4317 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4318 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4319 /// MOVSD, and MOVD, i.e. setting the lowest element.
4320 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4321 if (VT.getVectorElementType().getSizeInBits() < 32)
4323 if (!VT.is128BitVector())
4326 unsigned NumElts = VT.getVectorNumElements();
4328 if (!isUndefOrEqual(Mask[0], NumElts))
4331 for (unsigned i = 1; i != NumElts; ++i)
4332 if (!isUndefOrEqual(Mask[i], i))
4338 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4339 /// as permutations between 128-bit chunks or halves. As an example: this
4341 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4342 /// The first half comes from the second half of V1 and the second half from the
4343 /// the second half of V2.
4344 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4345 if (!HasFp256 || !VT.is256BitVector())
4348 // The shuffle result is divided into half A and half B. In total the two
4349 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4350 // B must come from C, D, E or F.
4351 unsigned HalfSize = VT.getVectorNumElements()/2;
4352 bool MatchA = false, MatchB = false;
4354 // Check if A comes from one of C, D, E, F.
4355 for (unsigned Half = 0; Half != 4; ++Half) {
4356 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4362 // Check if B comes from one of C, D, E, F.
4363 for (unsigned Half = 0; Half != 4; ++Half) {
4364 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4370 return MatchA && MatchB;
4373 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4374 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4375 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4376 MVT VT = SVOp->getSimpleValueType(0);
4378 unsigned HalfSize = VT.getVectorNumElements()/2;
4380 unsigned FstHalf = 0, SndHalf = 0;
4381 for (unsigned i = 0; i < HalfSize; ++i) {
4382 if (SVOp->getMaskElt(i) > 0) {
4383 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4387 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4388 if (SVOp->getMaskElt(i) > 0) {
4389 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4394 return (FstHalf | (SndHalf << 4));
4397 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4398 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4399 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4403 unsigned NumElts = VT.getVectorNumElements();
4405 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4406 for (unsigned i = 0; i != NumElts; ++i) {
4409 Imm8 |= Mask[i] << (i*2);
4414 unsigned LaneSize = 4;
4415 SmallVector<int, 4> MaskVal(LaneSize, -1);
4417 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4418 for (unsigned i = 0; i != LaneSize; ++i) {
4419 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4423 if (MaskVal[i] < 0) {
4424 MaskVal[i] = Mask[i+l] - l;
4425 Imm8 |= MaskVal[i] << (i*2);
4428 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4435 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4436 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4437 /// Note that VPERMIL mask matching is different depending whether theunderlying
4438 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4439 /// to the same elements of the low, but to the higher half of the source.
4440 /// In VPERMILPD the two lanes could be shuffled independently of each other
4441 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4442 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4443 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4444 if (VT.getSizeInBits() < 256 || EltSize < 32)
4446 bool symetricMaskRequired = (EltSize == 32);
4447 unsigned NumElts = VT.getVectorNumElements();
4449 unsigned NumLanes = VT.getSizeInBits()/128;
4450 unsigned LaneSize = NumElts/NumLanes;
4451 // 2 or 4 elements in one lane
4453 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4454 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4455 for (unsigned i = 0; i != LaneSize; ++i) {
4456 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4458 if (symetricMaskRequired) {
4459 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4460 ExpectedMaskVal[i] = Mask[i+l] - l;
4463 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4471 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4472 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4473 /// element of vector 2 and the other elements to come from vector 1 in order.
4474 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4475 bool V2IsSplat = false, bool V2IsUndef = false) {
4476 if (!VT.is128BitVector())
4479 unsigned NumOps = VT.getVectorNumElements();
4480 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4483 if (!isUndefOrEqual(Mask[0], 0))
4486 for (unsigned i = 1; i != NumOps; ++i)
4487 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4488 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4489 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4495 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4496 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4497 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4498 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4499 const X86Subtarget *Subtarget) {
4500 if (!Subtarget->hasSSE3())
4503 unsigned NumElems = VT.getVectorNumElements();
4505 if ((VT.is128BitVector() && NumElems != 4) ||
4506 (VT.is256BitVector() && NumElems != 8) ||
4507 (VT.is512BitVector() && NumElems != 16))
4510 // "i+1" is the value the indexed mask element must have
4511 for (unsigned i = 0; i != NumElems; i += 2)
4512 if (!isUndefOrEqual(Mask[i], i+1) ||
4513 !isUndefOrEqual(Mask[i+1], i+1))
4519 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4520 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4521 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4522 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4523 const X86Subtarget *Subtarget) {
4524 if (!Subtarget->hasSSE3())
4527 unsigned NumElems = VT.getVectorNumElements();
4529 if ((VT.is128BitVector() && NumElems != 4) ||
4530 (VT.is256BitVector() && NumElems != 8) ||
4531 (VT.is512BitVector() && NumElems != 16))
4534 // "i" is the value the indexed mask element must have
4535 for (unsigned i = 0; i != NumElems; i += 2)
4536 if (!isUndefOrEqual(Mask[i], i) ||
4537 !isUndefOrEqual(Mask[i+1], i))
4543 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4544 /// specifies a shuffle of elements that is suitable for input to 256-bit
4545 /// version of MOVDDUP.
4546 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4547 if (!HasFp256 || !VT.is256BitVector())
4550 unsigned NumElts = VT.getVectorNumElements();
4554 for (unsigned i = 0; i != NumElts/2; ++i)
4555 if (!isUndefOrEqual(Mask[i], 0))
4557 for (unsigned i = NumElts/2; i != NumElts; ++i)
4558 if (!isUndefOrEqual(Mask[i], NumElts/2))
4563 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4564 /// specifies a shuffle of elements that is suitable for input to 128-bit
4565 /// version of MOVDDUP.
4566 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4567 if (!VT.is128BitVector())
4570 unsigned e = VT.getVectorNumElements() / 2;
4571 for (unsigned i = 0; i != e; ++i)
4572 if (!isUndefOrEqual(Mask[i], i))
4574 for (unsigned i = 0; i != e; ++i)
4575 if (!isUndefOrEqual(Mask[e+i], i))
4580 /// isVEXTRACTIndex - Return true if the specified
4581 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4582 /// suitable for instruction that extract 128 or 256 bit vectors
4583 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4584 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4585 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4588 // The index should be aligned on a vecWidth-bit boundary.
4590 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4592 MVT VT = N->getSimpleValueType(0);
4593 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4594 bool Result = (Index * ElSize) % vecWidth == 0;
4599 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4600 /// operand specifies a subvector insert that is suitable for input to
4601 /// insertion of 128 or 256-bit subvectors
4602 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4603 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4604 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4606 // The index should be aligned on a vecWidth-bit boundary.
4608 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4610 MVT VT = N->getSimpleValueType(0);
4611 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4612 bool Result = (Index * ElSize) % vecWidth == 0;
4617 bool X86::isVINSERT128Index(SDNode *N) {
4618 return isVINSERTIndex(N, 128);
4621 bool X86::isVINSERT256Index(SDNode *N) {
4622 return isVINSERTIndex(N, 256);
4625 bool X86::isVEXTRACT128Index(SDNode *N) {
4626 return isVEXTRACTIndex(N, 128);
4629 bool X86::isVEXTRACT256Index(SDNode *N) {
4630 return isVEXTRACTIndex(N, 256);
4633 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4634 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4635 /// Handles 128-bit and 256-bit.
4636 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4637 MVT VT = N->getSimpleValueType(0);
4639 assert((VT.getSizeInBits() >= 128) &&
4640 "Unsupported vector type for PSHUF/SHUFP");
4642 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4643 // independently on 128-bit lanes.
4644 unsigned NumElts = VT.getVectorNumElements();
4645 unsigned NumLanes = VT.getSizeInBits()/128;
4646 unsigned NumLaneElts = NumElts/NumLanes;
4648 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4649 "Only supports 2, 4 or 8 elements per lane");
4651 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4653 for (unsigned i = 0; i != NumElts; ++i) {
4654 int Elt = N->getMaskElt(i);
4655 if (Elt < 0) continue;
4656 Elt &= NumLaneElts - 1;
4657 unsigned ShAmt = (i << Shift) % 8;
4658 Mask |= Elt << ShAmt;
4664 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4665 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4666 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4667 MVT VT = N->getSimpleValueType(0);
4669 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4670 "Unsupported vector type for PSHUFHW");
4672 unsigned NumElts = VT.getVectorNumElements();
4675 for (unsigned l = 0; l != NumElts; l += 8) {
4676 // 8 nodes per lane, but we only care about the last 4.
4677 for (unsigned i = 0; i < 4; ++i) {
4678 int Elt = N->getMaskElt(l+i+4);
4679 if (Elt < 0) continue;
4680 Elt &= 0x3; // only 2-bits.
4681 Mask |= Elt << (i * 2);
4688 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4689 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4690 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4691 MVT VT = N->getSimpleValueType(0);
4693 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4694 "Unsupported vector type for PSHUFHW");
4696 unsigned NumElts = VT.getVectorNumElements();
4699 for (unsigned l = 0; l != NumElts; l += 8) {
4700 // 8 nodes per lane, but we only care about the first 4.
4701 for (unsigned i = 0; i < 4; ++i) {
4702 int Elt = N->getMaskElt(l+i);
4703 if (Elt < 0) continue;
4704 Elt &= 0x3; // only 2-bits
4705 Mask |= Elt << (i * 2);
4712 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4713 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4714 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4715 MVT VT = SVOp->getSimpleValueType(0);
4716 unsigned EltSize = VT.is512BitVector() ? 1 :
4717 VT.getVectorElementType().getSizeInBits() >> 3;
4719 unsigned NumElts = VT.getVectorNumElements();
4720 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4721 unsigned NumLaneElts = NumElts/NumLanes;
4725 for (i = 0; i != NumElts; ++i) {
4726 Val = SVOp->getMaskElt(i);
4730 if (Val >= (int)NumElts)
4731 Val -= NumElts - NumLaneElts;
4733 assert(Val - i > 0 && "PALIGNR imm should be positive");
4734 return (Val - i) * EltSize;
4737 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4738 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4739 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4740 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4743 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4745 MVT VecVT = N->getOperand(0).getSimpleValueType();
4746 MVT ElVT = VecVT.getVectorElementType();
4748 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4749 return Index / NumElemsPerChunk;
4752 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4753 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4754 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4755 llvm_unreachable("Illegal insert subvector for VINSERT");
4758 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4760 MVT VecVT = N->getSimpleValueType(0);
4761 MVT ElVT = VecVT.getVectorElementType();
4763 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4764 return Index / NumElemsPerChunk;
4767 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4768 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4769 /// and VINSERTI128 instructions.
4770 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4771 return getExtractVEXTRACTImmediate(N, 128);
4774 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4775 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4776 /// and VINSERTI64x4 instructions.
4777 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4778 return getExtractVEXTRACTImmediate(N, 256);
4781 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4782 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4783 /// and VINSERTI128 instructions.
4784 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4785 return getInsertVINSERTImmediate(N, 128);
4788 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4789 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4790 /// and VINSERTI64x4 instructions.
4791 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4792 return getInsertVINSERTImmediate(N, 256);
4795 /// isZero - Returns true if Elt is a constant integer zero
4796 static bool isZero(SDValue V) {
4797 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4798 return C && C->isNullValue();
4801 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4803 bool X86::isZeroNode(SDValue Elt) {
4806 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4807 return CFP->getValueAPF().isPosZero();
4811 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4812 /// match movhlps. The lower half elements should come from upper half of
4813 /// V1 (and in order), and the upper half elements should come from the upper
4814 /// half of V2 (and in order).
4815 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4816 if (!VT.is128BitVector())
4818 if (VT.getVectorNumElements() != 4)
4820 for (unsigned i = 0, e = 2; i != e; ++i)
4821 if (!isUndefOrEqual(Mask[i], i+2))
4823 for (unsigned i = 2; i != 4; ++i)
4824 if (!isUndefOrEqual(Mask[i], i+4))
4829 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4830 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4832 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4833 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4835 N = N->getOperand(0).getNode();
4836 if (!ISD::isNON_EXTLoad(N))
4839 *LD = cast<LoadSDNode>(N);
4843 // Test whether the given value is a vector value which will be legalized
4845 static bool WillBeConstantPoolLoad(SDNode *N) {
4846 if (N->getOpcode() != ISD::BUILD_VECTOR)
4849 // Check for any non-constant elements.
4850 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4851 switch (N->getOperand(i).getNode()->getOpcode()) {
4853 case ISD::ConstantFP:
4860 // Vectors of all-zeros and all-ones are materialized with special
4861 // instructions rather than being loaded.
4862 return !ISD::isBuildVectorAllZeros(N) &&
4863 !ISD::isBuildVectorAllOnes(N);
4866 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4867 /// match movlp{s|d}. The lower half elements should come from lower half of
4868 /// V1 (and in order), and the upper half elements should come from the upper
4869 /// half of V2 (and in order). And since V1 will become the source of the
4870 /// MOVLP, it must be either a vector load or a scalar load to vector.
4871 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4872 ArrayRef<int> Mask, MVT VT) {
4873 if (!VT.is128BitVector())
4876 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4878 // Is V2 is a vector load, don't do this transformation. We will try to use
4879 // load folding shufps op.
4880 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4883 unsigned NumElems = VT.getVectorNumElements();
4885 if (NumElems != 2 && NumElems != 4)
4887 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4888 if (!isUndefOrEqual(Mask[i], i))
4890 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4891 if (!isUndefOrEqual(Mask[i], i+NumElems))
4896 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4897 /// to an zero vector.
4898 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4899 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4900 SDValue V1 = N->getOperand(0);
4901 SDValue V2 = N->getOperand(1);
4902 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4903 for (unsigned i = 0; i != NumElems; ++i) {
4904 int Idx = N->getMaskElt(i);
4905 if (Idx >= (int)NumElems) {
4906 unsigned Opc = V2.getOpcode();
4907 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4909 if (Opc != ISD::BUILD_VECTOR ||
4910 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4912 } else if (Idx >= 0) {
4913 unsigned Opc = V1.getOpcode();
4914 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4916 if (Opc != ISD::BUILD_VECTOR ||
4917 !X86::isZeroNode(V1.getOperand(Idx)))
4924 /// getZeroVector - Returns a vector of specified type with all zero elements.
4926 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4927 SelectionDAG &DAG, SDLoc dl) {
4928 assert(VT.isVector() && "Expected a vector type");
4930 // Always build SSE zero vectors as <4 x i32> bitcasted
4931 // to their dest type. This ensures they get CSE'd.
4933 if (VT.is128BitVector()) { // SSE
4934 if (Subtarget->hasSSE2()) { // SSE2
4935 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4936 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4938 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4939 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4941 } else if (VT.is256BitVector()) { // AVX
4942 if (Subtarget->hasInt256()) { // AVX2
4943 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4944 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4945 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4947 // 256-bit logic and arithmetic instructions in AVX are all
4948 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4949 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4950 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4951 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4953 } else if (VT.is512BitVector()) { // AVX-512
4954 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4955 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4956 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4957 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4958 } else if (VT.getScalarType() == MVT::i1) {
4959 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4960 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4961 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4962 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4964 llvm_unreachable("Unexpected vector type");
4966 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4969 /// getOnesVector - Returns a vector of specified type with all bits set.
4970 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4971 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4972 /// Then bitcast to their original type, ensuring they get CSE'd.
4973 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4975 assert(VT.isVector() && "Expected a vector type");
4977 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4979 if (VT.is256BitVector()) {
4980 if (HasInt256) { // AVX2
4981 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4982 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4984 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4985 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4987 } else if (VT.is128BitVector()) {
4988 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4990 llvm_unreachable("Unexpected vector type");
4992 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4995 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4996 /// that point to V2 points to its first element.
4997 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4998 for (unsigned i = 0; i != NumElems; ++i) {
4999 if (Mask[i] > (int)NumElems) {
5005 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5006 /// operation of specified width.
5007 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5009 unsigned NumElems = VT.getVectorNumElements();
5010 SmallVector<int, 8> Mask;
5011 Mask.push_back(NumElems);
5012 for (unsigned i = 1; i != NumElems; ++i)
5014 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5017 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5018 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5020 unsigned NumElems = VT.getVectorNumElements();
5021 SmallVector<int, 8> Mask;
5022 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5024 Mask.push_back(i + NumElems);
5026 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5029 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5030 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5032 unsigned NumElems = VT.getVectorNumElements();
5033 SmallVector<int, 8> Mask;
5034 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5035 Mask.push_back(i + Half);
5036 Mask.push_back(i + NumElems + Half);
5038 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5041 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5042 // a generic shuffle instruction because the target has no such instructions.
5043 // Generate shuffles which repeat i16 and i8 several times until they can be
5044 // represented by v4f32 and then be manipulated by target suported shuffles.
5045 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5046 MVT VT = V.getSimpleValueType();
5047 int NumElems = VT.getVectorNumElements();
5050 while (NumElems > 4) {
5051 if (EltNo < NumElems/2) {
5052 V = getUnpackl(DAG, dl, VT, V, V);
5054 V = getUnpackh(DAG, dl, VT, V, V);
5055 EltNo -= NumElems/2;
5062 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5063 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5064 MVT VT = V.getSimpleValueType();
5067 if (VT.is128BitVector()) {
5068 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5069 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5070 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5072 } else if (VT.is256BitVector()) {
5073 // To use VPERMILPS to splat scalars, the second half of indicies must
5074 // refer to the higher part, which is a duplication of the lower one,
5075 // because VPERMILPS can only handle in-lane permutations.
5076 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5077 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5079 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5080 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5083 llvm_unreachable("Vector size not supported");
5085 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5088 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5089 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5090 MVT SrcVT = SV->getSimpleValueType(0);
5091 SDValue V1 = SV->getOperand(0);
5094 int EltNo = SV->getSplatIndex();
5095 int NumElems = SrcVT.getVectorNumElements();
5096 bool Is256BitVec = SrcVT.is256BitVector();
5098 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5099 "Unknown how to promote splat for type");
5101 // Extract the 128-bit part containing the splat element and update
5102 // the splat element index when it refers to the higher register.
5104 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5105 if (EltNo >= NumElems/2)
5106 EltNo -= NumElems/2;
5109 // All i16 and i8 vector types can't be used directly by a generic shuffle
5110 // instruction because the target has no such instruction. Generate shuffles
5111 // which repeat i16 and i8 several times until they fit in i32, and then can
5112 // be manipulated by target suported shuffles.
5113 MVT EltVT = SrcVT.getVectorElementType();
5114 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5115 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5117 // Recreate the 256-bit vector and place the same 128-bit vector
5118 // into the low and high part. This is necessary because we want
5119 // to use VPERM* to shuffle the vectors
5121 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5124 return getLegalSplat(DAG, V1, EltNo);
5127 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5128 /// vector of zero or undef vector. This produces a shuffle where the low
5129 /// element of V2 is swizzled into the zero/undef vector, landing at element
5130 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5131 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5133 const X86Subtarget *Subtarget,
5134 SelectionDAG &DAG) {
5135 MVT VT = V2.getSimpleValueType();
5137 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5138 unsigned NumElems = VT.getVectorNumElements();
5139 SmallVector<int, 16> MaskVec;
5140 for (unsigned i = 0; i != NumElems; ++i)
5141 // If this is the insertion idx, put the low elt of V2 here.
5142 MaskVec.push_back(i == Idx ? NumElems : i);
5143 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5146 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5147 /// target specific opcode. Returns true if the Mask could be calculated.
5148 /// Sets IsUnary to true if only uses one source.
5149 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5150 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5151 unsigned NumElems = VT.getVectorNumElements();
5155 switch(N->getOpcode()) {
5157 ImmN = N->getOperand(N->getNumOperands()-1);
5158 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5160 case X86ISD::UNPCKH:
5161 DecodeUNPCKHMask(VT, Mask);
5163 case X86ISD::UNPCKL:
5164 DecodeUNPCKLMask(VT, Mask);
5166 case X86ISD::MOVHLPS:
5167 DecodeMOVHLPSMask(NumElems, Mask);
5169 case X86ISD::MOVLHPS:
5170 DecodeMOVLHPSMask(NumElems, Mask);
5172 case X86ISD::PALIGNR:
5173 ImmN = N->getOperand(N->getNumOperands()-1);
5174 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5176 case X86ISD::PSHUFD:
5177 case X86ISD::VPERMILP:
5178 ImmN = N->getOperand(N->getNumOperands()-1);
5179 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5182 case X86ISD::PSHUFHW:
5183 ImmN = N->getOperand(N->getNumOperands()-1);
5184 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5187 case X86ISD::PSHUFLW:
5188 ImmN = N->getOperand(N->getNumOperands()-1);
5189 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5192 case X86ISD::VPERMI:
5193 ImmN = N->getOperand(N->getNumOperands()-1);
5194 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5198 case X86ISD::MOVSD: {
5199 // The index 0 always comes from the first element of the second source,
5200 // this is why MOVSS and MOVSD are used in the first place. The other
5201 // elements come from the other positions of the first source vector
5202 Mask.push_back(NumElems);
5203 for (unsigned i = 1; i != NumElems; ++i) {
5208 case X86ISD::VPERM2X128:
5209 ImmN = N->getOperand(N->getNumOperands()-1);
5210 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5211 if (Mask.empty()) return false;
5213 case X86ISD::MOVDDUP:
5214 case X86ISD::MOVLHPD:
5215 case X86ISD::MOVLPD:
5216 case X86ISD::MOVLPS:
5217 case X86ISD::MOVSHDUP:
5218 case X86ISD::MOVSLDUP:
5219 // Not yet implemented
5221 default: llvm_unreachable("unknown target shuffle node");
5227 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5228 /// element of the result of the vector shuffle.
5229 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5232 return SDValue(); // Limit search depth.
5234 SDValue V = SDValue(N, 0);
5235 EVT VT = V.getValueType();
5236 unsigned Opcode = V.getOpcode();
5238 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5239 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5240 int Elt = SV->getMaskElt(Index);
5243 return DAG.getUNDEF(VT.getVectorElementType());
5245 unsigned NumElems = VT.getVectorNumElements();
5246 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5247 : SV->getOperand(1);
5248 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5251 // Recurse into target specific vector shuffles to find scalars.
5252 if (isTargetShuffle(Opcode)) {
5253 MVT ShufVT = V.getSimpleValueType();
5254 unsigned NumElems = ShufVT.getVectorNumElements();
5255 SmallVector<int, 16> ShuffleMask;
5258 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5261 int Elt = ShuffleMask[Index];
5263 return DAG.getUNDEF(ShufVT.getVectorElementType());
5265 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5267 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5271 // Actual nodes that may contain scalar elements
5272 if (Opcode == ISD::BITCAST) {
5273 V = V.getOperand(0);
5274 EVT SrcVT = V.getValueType();
5275 unsigned NumElems = VT.getVectorNumElements();
5277 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5281 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5282 return (Index == 0) ? V.getOperand(0)
5283 : DAG.getUNDEF(VT.getVectorElementType());
5285 if (V.getOpcode() == ISD::BUILD_VECTOR)
5286 return V.getOperand(Index);
5291 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5292 /// shuffle operation which come from a consecutively from a zero. The
5293 /// search can start in two different directions, from left or right.
5294 /// We count undefs as zeros until PreferredNum is reached.
5295 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5296 unsigned NumElems, bool ZerosFromLeft,
5298 unsigned PreferredNum = -1U) {
5299 unsigned NumZeros = 0;
5300 for (unsigned i = 0; i != NumElems; ++i) {
5301 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5302 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5306 if (X86::isZeroNode(Elt))
5308 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5309 NumZeros = std::min(NumZeros + 1, PreferredNum);
5317 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5318 /// correspond consecutively to elements from one of the vector operands,
5319 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5321 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5322 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5323 unsigned NumElems, unsigned &OpNum) {
5324 bool SeenV1 = false;
5325 bool SeenV2 = false;
5327 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5328 int Idx = SVOp->getMaskElt(i);
5329 // Ignore undef indicies
5333 if (Idx < (int)NumElems)
5338 // Only accept consecutive elements from the same vector
5339 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5343 OpNum = SeenV1 ? 0 : 1;
5347 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5348 /// logical left shift of a vector.
5349 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5350 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5352 SVOp->getSimpleValueType(0).getVectorNumElements();
5353 unsigned NumZeros = getNumOfConsecutiveZeros(
5354 SVOp, NumElems, false /* check zeros from right */, DAG,
5355 SVOp->getMaskElt(0));
5361 // Considering the elements in the mask that are not consecutive zeros,
5362 // check if they consecutively come from only one of the source vectors.
5364 // V1 = {X, A, B, C} 0
5366 // vector_shuffle V1, V2 <1, 2, 3, X>
5368 if (!isShuffleMaskConsecutive(SVOp,
5369 0, // Mask Start Index
5370 NumElems-NumZeros, // Mask End Index(exclusive)
5371 NumZeros, // Where to start looking in the src vector
5372 NumElems, // Number of elements in vector
5373 OpSrc)) // Which source operand ?
5378 ShVal = SVOp->getOperand(OpSrc);
5382 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5383 /// logical left shift of a vector.
5384 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5385 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5387 SVOp->getSimpleValueType(0).getVectorNumElements();
5388 unsigned NumZeros = getNumOfConsecutiveZeros(
5389 SVOp, NumElems, true /* check zeros from left */, DAG,
5390 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5396 // Considering the elements in the mask that are not consecutive zeros,
5397 // check if they consecutively come from only one of the source vectors.
5399 // 0 { A, B, X, X } = V2
5401 // vector_shuffle V1, V2 <X, X, 4, 5>
5403 if (!isShuffleMaskConsecutive(SVOp,
5404 NumZeros, // Mask Start Index
5405 NumElems, // Mask End Index(exclusive)
5406 0, // Where to start looking in the src vector
5407 NumElems, // Number of elements in vector
5408 OpSrc)) // Which source operand ?
5413 ShVal = SVOp->getOperand(OpSrc);
5417 /// isVectorShift - Returns true if the shuffle can be implemented as a
5418 /// logical left or right shift of a vector.
5419 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5420 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5421 // Although the logic below support any bitwidth size, there are no
5422 // shift instructions which handle more than 128-bit vectors.
5423 if (!SVOp->getSimpleValueType(0).is128BitVector())
5426 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5427 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5433 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5435 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5436 unsigned NumNonZero, unsigned NumZero,
5438 const X86Subtarget* Subtarget,
5439 const TargetLowering &TLI) {
5446 for (unsigned i = 0; i < 16; ++i) {
5447 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5448 if (ThisIsNonZero && First) {
5450 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5452 V = DAG.getUNDEF(MVT::v8i16);
5457 SDValue ThisElt, LastElt;
5458 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5459 if (LastIsNonZero) {
5460 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5461 MVT::i16, Op.getOperand(i-1));
5463 if (ThisIsNonZero) {
5464 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5465 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5466 ThisElt, DAG.getConstant(8, MVT::i8));
5468 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5472 if (ThisElt.getNode())
5473 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5474 DAG.getIntPtrConstant(i/2));
5478 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5481 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5483 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5484 unsigned NumNonZero, unsigned NumZero,
5486 const X86Subtarget* Subtarget,
5487 const TargetLowering &TLI) {
5494 for (unsigned i = 0; i < 8; ++i) {
5495 bool isNonZero = (NonZeros & (1 << i)) != 0;
5499 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5501 V = DAG.getUNDEF(MVT::v8i16);
5504 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5505 MVT::v8i16, V, Op.getOperand(i),
5506 DAG.getIntPtrConstant(i));
5513 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5514 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5515 unsigned NonZeros, unsigned NumNonZero,
5516 unsigned NumZero, SelectionDAG &DAG,
5517 const X86Subtarget *Subtarget,
5518 const TargetLowering &TLI) {
5519 // We know there's at least one non-zero element
5520 unsigned FirstNonZeroIdx = 0;
5521 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5522 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5523 X86::isZeroNode(FirstNonZero)) {
5525 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5528 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5529 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5532 SDValue V = FirstNonZero.getOperand(0);
5533 MVT VVT = V.getSimpleValueType();
5534 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5537 unsigned FirstNonZeroDst =
5538 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5539 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5540 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5541 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5543 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5544 SDValue Elem = Op.getOperand(Idx);
5545 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5548 // TODO: What else can be here? Deal with it.
5549 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5552 // TODO: Some optimizations are still possible here
5553 // ex: Getting one element from a vector, and the rest from another.
5554 if (Elem.getOperand(0) != V)
5557 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5560 else if (IncorrectIdx == -1U) {
5564 // There was already one element with an incorrect index.
5565 // We can't optimize this case to an insertps.
5569 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5571 EVT VT = Op.getSimpleValueType();
5572 unsigned ElementMoveMask = 0;
5573 if (IncorrectIdx == -1U)
5574 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5576 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5578 SDValue InsertpsMask =
5579 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5580 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5586 /// getVShift - Return a vector logical shift node.
5588 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5589 unsigned NumBits, SelectionDAG &DAG,
5590 const TargetLowering &TLI, SDLoc dl) {
5591 assert(VT.is128BitVector() && "Unknown type for VShift");
5592 EVT ShVT = MVT::v2i64;
5593 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5594 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5595 return DAG.getNode(ISD::BITCAST, dl, VT,
5596 DAG.getNode(Opc, dl, ShVT, SrcOp,
5597 DAG.getConstant(NumBits,
5598 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5602 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5604 // Check if the scalar load can be widened into a vector load. And if
5605 // the address is "base + cst" see if the cst can be "absorbed" into
5606 // the shuffle mask.
5607 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5608 SDValue Ptr = LD->getBasePtr();
5609 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5611 EVT PVT = LD->getValueType(0);
5612 if (PVT != MVT::i32 && PVT != MVT::f32)
5617 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5618 FI = FINode->getIndex();
5620 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5621 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5622 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5623 Offset = Ptr.getConstantOperandVal(1);
5624 Ptr = Ptr.getOperand(0);
5629 // FIXME: 256-bit vector instructions don't require a strict alignment,
5630 // improve this code to support it better.
5631 unsigned RequiredAlign = VT.getSizeInBits()/8;
5632 SDValue Chain = LD->getChain();
5633 // Make sure the stack object alignment is at least 16 or 32.
5634 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5635 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5636 if (MFI->isFixedObjectIndex(FI)) {
5637 // Can't change the alignment. FIXME: It's possible to compute
5638 // the exact stack offset and reference FI + adjust offset instead.
5639 // If someone *really* cares about this. That's the way to implement it.
5642 MFI->setObjectAlignment(FI, RequiredAlign);
5646 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5647 // Ptr + (Offset & ~15).
5650 if ((Offset % RequiredAlign) & 3)
5652 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5654 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5655 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5657 int EltNo = (Offset - StartOffset) >> 2;
5658 unsigned NumElems = VT.getVectorNumElements();
5660 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5661 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5662 LD->getPointerInfo().getWithOffset(StartOffset),
5663 false, false, false, 0);
5665 SmallVector<int, 8> Mask;
5666 for (unsigned i = 0; i != NumElems; ++i)
5667 Mask.push_back(EltNo);
5669 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5675 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5676 /// vector of type 'VT', see if the elements can be replaced by a single large
5677 /// load which has the same value as a build_vector whose operands are 'elts'.
5679 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5681 /// FIXME: we'd also like to handle the case where the last elements are zero
5682 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5683 /// There's even a handy isZeroNode for that purpose.
5684 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5685 SDLoc &DL, SelectionDAG &DAG,
5686 bool isAfterLegalize) {
5687 EVT EltVT = VT.getVectorElementType();
5688 unsigned NumElems = Elts.size();
5690 LoadSDNode *LDBase = nullptr;
5691 unsigned LastLoadedElt = -1U;
5693 // For each element in the initializer, see if we've found a load or an undef.
5694 // If we don't find an initial load element, or later load elements are
5695 // non-consecutive, bail out.
5696 for (unsigned i = 0; i < NumElems; ++i) {
5697 SDValue Elt = Elts[i];
5699 if (!Elt.getNode() ||
5700 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5703 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5705 LDBase = cast<LoadSDNode>(Elt.getNode());
5709 if (Elt.getOpcode() == ISD::UNDEF)
5712 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5713 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5718 // If we have found an entire vector of loads and undefs, then return a large
5719 // load of the entire vector width starting at the base pointer. If we found
5720 // consecutive loads for the low half, generate a vzext_load node.
5721 if (LastLoadedElt == NumElems - 1) {
5723 if (isAfterLegalize &&
5724 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5727 SDValue NewLd = SDValue();
5729 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5730 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5731 LDBase->getPointerInfo(),
5732 LDBase->isVolatile(), LDBase->isNonTemporal(),
5733 LDBase->isInvariant(), 0);
5734 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5735 LDBase->getPointerInfo(),
5736 LDBase->isVolatile(), LDBase->isNonTemporal(),
5737 LDBase->isInvariant(), LDBase->getAlignment());
5739 if (LDBase->hasAnyUseOfValue(1)) {
5740 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5742 SDValue(NewLd.getNode(), 1));
5743 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5744 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5745 SDValue(NewLd.getNode(), 1));
5750 if (NumElems == 4 && LastLoadedElt == 1 &&
5751 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5752 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5753 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5755 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5756 LDBase->getPointerInfo(),
5757 LDBase->getAlignment(),
5758 false/*isVolatile*/, true/*ReadMem*/,
5761 // Make sure the newly-created LOAD is in the same position as LDBase in
5762 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5763 // update uses of LDBase's output chain to use the TokenFactor.
5764 if (LDBase->hasAnyUseOfValue(1)) {
5765 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5766 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5767 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5768 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5769 SDValue(ResNode.getNode(), 1));
5772 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5777 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5778 /// to generate a splat value for the following cases:
5779 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5780 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5781 /// a scalar load, or a constant.
5782 /// The VBROADCAST node is returned when a pattern is found,
5783 /// or SDValue() otherwise.
5784 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5785 SelectionDAG &DAG) {
5786 if (!Subtarget->hasFp256())
5789 MVT VT = Op.getSimpleValueType();
5792 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5793 "Unsupported vector type for broadcast.");
5798 switch (Op.getOpcode()) {
5800 // Unknown pattern found.
5803 case ISD::BUILD_VECTOR: {
5804 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5805 BitVector UndefElements;
5806 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5808 // We need a splat of a single value to use broadcast, and it doesn't
5809 // make any sense if the value is only in one element of the vector.
5810 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5814 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5815 Ld.getOpcode() == ISD::ConstantFP);
5817 // Make sure that all of the users of a non-constant load are from the
5818 // BUILD_VECTOR node.
5819 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5824 case ISD::VECTOR_SHUFFLE: {
5825 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5827 // Shuffles must have a splat mask where the first element is
5829 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5832 SDValue Sc = Op.getOperand(0);
5833 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5834 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5836 if (!Subtarget->hasInt256())
5839 // Use the register form of the broadcast instruction available on AVX2.
5840 if (VT.getSizeInBits() >= 256)
5841 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5842 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5845 Ld = Sc.getOperand(0);
5846 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5847 Ld.getOpcode() == ISD::ConstantFP);
5849 // The scalar_to_vector node and the suspected
5850 // load node must have exactly one user.
5851 // Constants may have multiple users.
5853 // AVX-512 has register version of the broadcast
5854 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5855 Ld.getValueType().getSizeInBits() >= 32;
5856 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5863 bool IsGE256 = (VT.getSizeInBits() >= 256);
5865 // Handle the broadcasting a single constant scalar from the constant pool
5866 // into a vector. On Sandybridge it is still better to load a constant vector
5867 // from the constant pool and not to broadcast it from a scalar.
5868 if (ConstSplatVal && Subtarget->hasInt256()) {
5869 EVT CVT = Ld.getValueType();
5870 assert(!CVT.isVector() && "Must not broadcast a vector type");
5871 unsigned ScalarSize = CVT.getSizeInBits();
5873 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5874 const Constant *C = nullptr;
5875 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5876 C = CI->getConstantIntValue();
5877 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5878 C = CF->getConstantFPValue();
5880 assert(C && "Invalid constant type");
5882 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5883 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5884 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5885 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5886 MachinePointerInfo::getConstantPool(),
5887 false, false, false, Alignment);
5889 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5893 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5894 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5896 // Handle AVX2 in-register broadcasts.
5897 if (!IsLoad && Subtarget->hasInt256() &&
5898 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5899 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5901 // The scalar source must be a normal load.
5905 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5906 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5908 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5909 // double since there is no vbroadcastsd xmm
5910 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5911 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5912 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5915 // Unsupported broadcast.
5919 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5920 /// underlying vector and index.
5922 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5924 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5926 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5927 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5930 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5932 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5934 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5935 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5938 // In this case the vector is the extract_subvector expression and the index
5939 // is 2, as specified by the shuffle.
5940 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5941 SDValue ShuffleVec = SVOp->getOperand(0);
5942 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5943 assert(ShuffleVecVT.getVectorElementType() ==
5944 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5946 int ShuffleIdx = SVOp->getMaskElt(Idx);
5947 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5948 ExtractedFromVec = ShuffleVec;
5954 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5955 MVT VT = Op.getSimpleValueType();
5957 // Skip if insert_vec_elt is not supported.
5958 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5959 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5963 unsigned NumElems = Op.getNumOperands();
5967 SmallVector<unsigned, 4> InsertIndices;
5968 SmallVector<int, 8> Mask(NumElems, -1);
5970 for (unsigned i = 0; i != NumElems; ++i) {
5971 unsigned Opc = Op.getOperand(i).getOpcode();
5973 if (Opc == ISD::UNDEF)
5976 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5977 // Quit if more than 1 elements need inserting.
5978 if (InsertIndices.size() > 1)
5981 InsertIndices.push_back(i);
5985 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5986 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5987 // Quit if non-constant index.
5988 if (!isa<ConstantSDNode>(ExtIdx))
5990 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5992 // Quit if extracted from vector of different type.
5993 if (ExtractedFromVec.getValueType() != VT)
5996 if (!VecIn1.getNode())
5997 VecIn1 = ExtractedFromVec;
5998 else if (VecIn1 != ExtractedFromVec) {
5999 if (!VecIn2.getNode())
6000 VecIn2 = ExtractedFromVec;
6001 else if (VecIn2 != ExtractedFromVec)
6002 // Quit if more than 2 vectors to shuffle
6006 if (ExtractedFromVec == VecIn1)
6008 else if (ExtractedFromVec == VecIn2)
6009 Mask[i] = Idx + NumElems;
6012 if (!VecIn1.getNode())
6015 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6016 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6017 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6018 unsigned Idx = InsertIndices[i];
6019 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6020 DAG.getIntPtrConstant(Idx));
6026 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6028 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6030 MVT VT = Op.getSimpleValueType();
6031 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6032 "Unexpected type in LowerBUILD_VECTORvXi1!");
6035 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6036 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6037 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6038 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6041 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6042 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6043 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6044 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6047 bool AllContants = true;
6048 uint64_t Immediate = 0;
6049 int NonConstIdx = -1;
6050 bool IsSplat = true;
6051 unsigned NumNonConsts = 0;
6052 unsigned NumConsts = 0;
6053 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6054 SDValue In = Op.getOperand(idx);
6055 if (In.getOpcode() == ISD::UNDEF)
6057 if (!isa<ConstantSDNode>(In)) {
6058 AllContants = false;
6064 if (cast<ConstantSDNode>(In)->getZExtValue())
6065 Immediate |= (1ULL << idx);
6067 if (In != Op.getOperand(0))
6072 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6073 DAG.getConstant(Immediate, MVT::i16));
6074 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6075 DAG.getIntPtrConstant(0));
6078 if (NumNonConsts == 1 && NonConstIdx != 0) {
6081 SDValue VecAsImm = DAG.getConstant(Immediate,
6082 MVT::getIntegerVT(VT.getSizeInBits()));
6083 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6086 DstVec = DAG.getUNDEF(VT);
6087 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6088 Op.getOperand(NonConstIdx),
6089 DAG.getIntPtrConstant(NonConstIdx));
6091 if (!IsSplat && (NonConstIdx != 0))
6092 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6093 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6096 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6097 DAG.getConstant(-1, SelectVT),
6098 DAG.getConstant(0, SelectVT));
6100 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6101 DAG.getConstant((Immediate | 1), SelectVT),
6102 DAG.getConstant(Immediate, SelectVT));
6103 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6106 /// \brief Return true if \p N implements a horizontal binop and return the
6107 /// operands for the horizontal binop into V0 and V1.
6109 /// This is a helper function of PerformBUILD_VECTORCombine.
6110 /// This function checks that the build_vector \p N in input implements a
6111 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6112 /// operation to match.
6113 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6114 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6115 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6118 /// This function only analyzes elements of \p N whose indices are
6119 /// in range [BaseIdx, LastIdx).
6120 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6122 unsigned BaseIdx, unsigned LastIdx,
6123 SDValue &V0, SDValue &V1) {
6124 EVT VT = N->getValueType(0);
6126 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6127 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6128 "Invalid Vector in input!");
6130 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6131 bool CanFold = true;
6132 unsigned ExpectedVExtractIdx = BaseIdx;
6133 unsigned NumElts = LastIdx - BaseIdx;
6134 V0 = DAG.getUNDEF(VT);
6135 V1 = DAG.getUNDEF(VT);
6137 // Check if N implements a horizontal binop.
6138 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6139 SDValue Op = N->getOperand(i + BaseIdx);
6142 if (Op->getOpcode() == ISD::UNDEF) {
6143 // Update the expected vector extract index.
6144 if (i * 2 == NumElts)
6145 ExpectedVExtractIdx = BaseIdx;
6146 ExpectedVExtractIdx += 2;
6150 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6155 SDValue Op0 = Op.getOperand(0);
6156 SDValue Op1 = Op.getOperand(1);
6158 // Try to match the following pattern:
6159 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6160 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6161 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6162 Op0.getOperand(0) == Op1.getOperand(0) &&
6163 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6164 isa<ConstantSDNode>(Op1.getOperand(1)));
6168 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6169 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6171 if (i * 2 < NumElts) {
6172 if (V0.getOpcode() == ISD::UNDEF)
6173 V0 = Op0.getOperand(0);
6175 if (V1.getOpcode() == ISD::UNDEF)
6176 V1 = Op0.getOperand(0);
6177 if (i * 2 == NumElts)
6178 ExpectedVExtractIdx = BaseIdx;
6181 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6182 if (I0 == ExpectedVExtractIdx)
6183 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6184 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6185 // Try to match the following dag sequence:
6186 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6187 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6191 ExpectedVExtractIdx += 2;
6197 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6198 /// a concat_vector.
6200 /// This is a helper function of PerformBUILD_VECTORCombine.
6201 /// This function expects two 256-bit vectors called V0 and V1.
6202 /// At first, each vector is split into two separate 128-bit vectors.
6203 /// Then, the resulting 128-bit vectors are used to implement two
6204 /// horizontal binary operations.
6206 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6208 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6209 /// the two new horizontal binop.
6210 /// When Mode is set, the first horizontal binop dag node would take as input
6211 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6212 /// horizontal binop dag node would take as input the lower 128-bit of V1
6213 /// and the upper 128-bit of V1.
6215 /// HADD V0_LO, V0_HI
6216 /// HADD V1_LO, V1_HI
6218 /// Otherwise, the first horizontal binop dag node takes as input the lower
6219 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6220 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6222 /// HADD V0_LO, V1_LO
6223 /// HADD V0_HI, V1_HI
6225 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6226 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6227 /// the upper 128-bits of the result.
6228 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6229 SDLoc DL, SelectionDAG &DAG,
6230 unsigned X86Opcode, bool Mode,
6231 bool isUndefLO, bool isUndefHI) {
6232 EVT VT = V0.getValueType();
6233 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6234 "Invalid nodes in input!");
6236 unsigned NumElts = VT.getVectorNumElements();
6237 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6238 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6239 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6240 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6241 EVT NewVT = V0_LO.getValueType();
6243 SDValue LO = DAG.getUNDEF(NewVT);
6244 SDValue HI = DAG.getUNDEF(NewVT);
6247 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6248 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6249 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6250 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6251 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6253 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6254 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6255 V1_LO->getOpcode() != ISD::UNDEF))
6256 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6258 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6259 V1_HI->getOpcode() != ISD::UNDEF))
6260 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6263 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6266 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6267 /// sequence of 'vadd + vsub + blendi'.
6268 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6269 const X86Subtarget *Subtarget) {
6271 EVT VT = BV->getValueType(0);
6272 unsigned NumElts = VT.getVectorNumElements();
6273 SDValue InVec0 = DAG.getUNDEF(VT);
6274 SDValue InVec1 = DAG.getUNDEF(VT);
6276 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6277 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6279 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6281 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6284 // Odd-numbered elements in the input build vector are obtained from
6285 // adding two integer/float elements.
6286 // Even-numbered elements in the input build vector are obtained from
6287 // subtracting two integer/float elements.
6288 unsigned ExpectedOpcode = ISD::FSUB;
6289 unsigned NextExpectedOpcode = ISD::FADD;
6290 bool AddFound = false;
6291 bool SubFound = false;
6293 for (unsigned i = 0, e = NumElts; i != e; i++) {
6294 SDValue Op = BV->getOperand(i);
6296 // Skip 'undef' values.
6297 unsigned Opcode = Op.getOpcode();
6298 if (Opcode == ISD::UNDEF) {
6299 std::swap(ExpectedOpcode, NextExpectedOpcode);
6303 // Early exit if we found an unexpected opcode.
6304 if (Opcode != ExpectedOpcode)
6307 SDValue Op0 = Op.getOperand(0);
6308 SDValue Op1 = Op.getOperand(1);
6310 // Try to match the following pattern:
6311 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6312 // Early exit if we cannot match that sequence.
6313 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6314 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6315 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6316 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6317 Op0.getOperand(1) != Op1.getOperand(1))
6320 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6324 // We found a valid add/sub node. Update the information accordingly.
6330 // Update InVec0 and InVec1.
6331 if (InVec0.getOpcode() == ISD::UNDEF)
6332 InVec0 = Op0.getOperand(0);
6333 if (InVec1.getOpcode() == ISD::UNDEF)
6334 InVec1 = Op1.getOperand(0);
6336 // Make sure that operands in input to each add/sub node always
6337 // come from a same pair of vectors.
6338 if (InVec0 != Op0.getOperand(0)) {
6339 if (ExpectedOpcode == ISD::FSUB)
6342 // FADD is commutable. Try to commute the operands
6343 // and then test again.
6344 std::swap(Op0, Op1);
6345 if (InVec0 != Op0.getOperand(0))
6349 if (InVec1 != Op1.getOperand(0))
6352 // Update the pair of expected opcodes.
6353 std::swap(ExpectedOpcode, NextExpectedOpcode);
6356 // Don't try to fold this build_vector into a VSELECT if it has
6357 // too many UNDEF operands.
6358 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6359 InVec1.getOpcode() != ISD::UNDEF) {
6360 // Emit a sequence of vector add and sub followed by a VSELECT.
6361 // The new VSELECT will be lowered into a BLENDI.
6362 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6363 // and emit a single ADDSUB instruction.
6364 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6365 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6367 // Construct the VSELECT mask.
6368 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6369 EVT SVT = MaskVT.getVectorElementType();
6370 unsigned SVTBits = SVT.getSizeInBits();
6371 SmallVector<SDValue, 8> Ops;
6373 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6374 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6375 APInt::getAllOnesValue(SVTBits);
6376 SDValue Constant = DAG.getConstant(Value, SVT);
6377 Ops.push_back(Constant);
6380 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6381 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6387 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6388 const X86Subtarget *Subtarget) {
6390 EVT VT = N->getValueType(0);
6391 unsigned NumElts = VT.getVectorNumElements();
6392 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6393 SDValue InVec0, InVec1;
6395 // Try to match an ADDSUB.
6396 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6397 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6398 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6399 if (Value.getNode())
6403 // Try to match horizontal ADD/SUB.
6404 unsigned NumUndefsLO = 0;
6405 unsigned NumUndefsHI = 0;
6406 unsigned Half = NumElts/2;
6408 // Count the number of UNDEF operands in the build_vector in input.
6409 for (unsigned i = 0, e = Half; i != e; ++i)
6410 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6413 for (unsigned i = Half, e = NumElts; i != e; ++i)
6414 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6417 // Early exit if this is either a build_vector of all UNDEFs or all the
6418 // operands but one are UNDEF.
6419 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6422 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6423 // Try to match an SSE3 float HADD/HSUB.
6424 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6425 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6427 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6428 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6429 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6430 // Try to match an SSSE3 integer HADD/HSUB.
6431 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6432 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6434 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6435 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6438 if (!Subtarget->hasAVX())
6441 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6442 // Try to match an AVX horizontal add/sub of packed single/double
6443 // precision floating point values from 256-bit vectors.
6444 SDValue InVec2, InVec3;
6445 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6446 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6447 ((InVec0.getOpcode() == ISD::UNDEF ||
6448 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6449 ((InVec1.getOpcode() == ISD::UNDEF ||
6450 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6451 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6453 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6454 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6455 ((InVec0.getOpcode() == ISD::UNDEF ||
6456 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6457 ((InVec1.getOpcode() == ISD::UNDEF ||
6458 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6459 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6460 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6461 // Try to match an AVX2 horizontal add/sub of signed integers.
6462 SDValue InVec2, InVec3;
6464 bool CanFold = true;
6466 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6467 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6468 ((InVec0.getOpcode() == ISD::UNDEF ||
6469 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6470 ((InVec1.getOpcode() == ISD::UNDEF ||
6471 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6472 X86Opcode = X86ISD::HADD;
6473 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6474 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6475 ((InVec0.getOpcode() == ISD::UNDEF ||
6476 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6477 ((InVec1.getOpcode() == ISD::UNDEF ||
6478 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6479 X86Opcode = X86ISD::HSUB;
6484 // Fold this build_vector into a single horizontal add/sub.
6485 // Do this only if the target has AVX2.
6486 if (Subtarget->hasAVX2())
6487 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6489 // Do not try to expand this build_vector into a pair of horizontal
6490 // add/sub if we can emit a pair of scalar add/sub.
6491 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6494 // Convert this build_vector into a pair of horizontal binop followed by
6496 bool isUndefLO = NumUndefsLO == Half;
6497 bool isUndefHI = NumUndefsHI == Half;
6498 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6499 isUndefLO, isUndefHI);
6503 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6504 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6506 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6507 X86Opcode = X86ISD::HADD;
6508 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6509 X86Opcode = X86ISD::HSUB;
6510 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6511 X86Opcode = X86ISD::FHADD;
6512 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6513 X86Opcode = X86ISD::FHSUB;
6517 // Don't try to expand this build_vector into a pair of horizontal add/sub
6518 // if we can simply emit a pair of scalar add/sub.
6519 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6522 // Convert this build_vector into two horizontal add/sub followed by
6524 bool isUndefLO = NumUndefsLO == Half;
6525 bool isUndefHI = NumUndefsHI == Half;
6526 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6527 isUndefLO, isUndefHI);
6534 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6537 MVT VT = Op.getSimpleValueType();
6538 MVT ExtVT = VT.getVectorElementType();
6539 unsigned NumElems = Op.getNumOperands();
6541 // Generate vectors for predicate vectors.
6542 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6543 return LowerBUILD_VECTORvXi1(Op, DAG);
6545 // Vectors containing all zeros can be matched by pxor and xorps later
6546 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6547 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6548 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6549 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6552 return getZeroVector(VT, Subtarget, DAG, dl);
6555 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6556 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6557 // vpcmpeqd on 256-bit vectors.
6558 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6559 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6562 if (!VT.is512BitVector())
6563 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6566 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6567 if (Broadcast.getNode())
6570 unsigned EVTBits = ExtVT.getSizeInBits();
6572 unsigned NumZero = 0;
6573 unsigned NumNonZero = 0;
6574 unsigned NonZeros = 0;
6575 bool IsAllConstants = true;
6576 SmallSet<SDValue, 8> Values;
6577 for (unsigned i = 0; i < NumElems; ++i) {
6578 SDValue Elt = Op.getOperand(i);
6579 if (Elt.getOpcode() == ISD::UNDEF)
6582 if (Elt.getOpcode() != ISD::Constant &&
6583 Elt.getOpcode() != ISD::ConstantFP)
6584 IsAllConstants = false;
6585 if (X86::isZeroNode(Elt))
6588 NonZeros |= (1 << i);
6593 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6594 if (NumNonZero == 0)
6595 return DAG.getUNDEF(VT);
6597 // Special case for single non-zero, non-undef, element.
6598 if (NumNonZero == 1) {
6599 unsigned Idx = countTrailingZeros(NonZeros);
6600 SDValue Item = Op.getOperand(Idx);
6602 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6603 // the value are obviously zero, truncate the value to i32 and do the
6604 // insertion that way. Only do this if the value is non-constant or if the
6605 // value is a constant being inserted into element 0. It is cheaper to do
6606 // a constant pool load than it is to do a movd + shuffle.
6607 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6608 (!IsAllConstants || Idx == 0)) {
6609 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6611 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6612 EVT VecVT = MVT::v4i32;
6613 unsigned VecElts = 4;
6615 // Truncate the value (which may itself be a constant) to i32, and
6616 // convert it to a vector with movd (S2V+shuffle to zero extend).
6617 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6618 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6619 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6621 // Now we have our 32-bit value zero extended in the low element of
6622 // a vector. If Idx != 0, swizzle it into place.
6624 SmallVector<int, 4> Mask;
6625 Mask.push_back(Idx);
6626 for (unsigned i = 1; i != VecElts; ++i)
6628 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6631 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6635 // If we have a constant or non-constant insertion into the low element of
6636 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6637 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6638 // depending on what the source datatype is.
6641 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6643 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6644 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6645 if (VT.is256BitVector() || VT.is512BitVector()) {
6646 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6647 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6648 Item, DAG.getIntPtrConstant(0));
6650 assert(VT.is128BitVector() && "Expected an SSE value type!");
6651 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6652 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6653 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6656 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6657 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6658 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6659 if (VT.is256BitVector()) {
6660 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6661 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6663 assert(VT.is128BitVector() && "Expected an SSE value type!");
6664 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6666 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6670 // Is it a vector logical left shift?
6671 if (NumElems == 2 && Idx == 1 &&
6672 X86::isZeroNode(Op.getOperand(0)) &&
6673 !X86::isZeroNode(Op.getOperand(1))) {
6674 unsigned NumBits = VT.getSizeInBits();
6675 return getVShift(true, VT,
6676 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6677 VT, Op.getOperand(1)),
6678 NumBits/2, DAG, *this, dl);
6681 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6684 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6685 // is a non-constant being inserted into an element other than the low one,
6686 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6687 // movd/movss) to move this into the low element, then shuffle it into
6689 if (EVTBits == 32) {
6690 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6692 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6693 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6694 SmallVector<int, 8> MaskVec;
6695 for (unsigned i = 0; i != NumElems; ++i)
6696 MaskVec.push_back(i == Idx ? 0 : 1);
6697 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6701 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6702 if (Values.size() == 1) {
6703 if (EVTBits == 32) {
6704 // Instead of a shuffle like this:
6705 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6706 // Check if it's possible to issue this instead.
6707 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6708 unsigned Idx = countTrailingZeros(NonZeros);
6709 SDValue Item = Op.getOperand(Idx);
6710 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6711 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6716 // A vector full of immediates; various special cases are already
6717 // handled, so this is best done with a single constant-pool load.
6721 // For AVX-length vectors, build the individual 128-bit pieces and use
6722 // shuffles to put them in place.
6723 if (VT.is256BitVector() || VT.is512BitVector()) {
6724 SmallVector<SDValue, 64> V;
6725 for (unsigned i = 0; i != NumElems; ++i)
6726 V.push_back(Op.getOperand(i));
6728 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6730 // Build both the lower and upper subvector.
6731 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6732 makeArrayRef(&V[0], NumElems/2));
6733 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6734 makeArrayRef(&V[NumElems / 2], NumElems/2));
6736 // Recreate the wider vector with the lower and upper part.
6737 if (VT.is256BitVector())
6738 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6739 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6742 // Let legalizer expand 2-wide build_vectors.
6743 if (EVTBits == 64) {
6744 if (NumNonZero == 1) {
6745 // One half is zero or undef.
6746 unsigned Idx = countTrailingZeros(NonZeros);
6747 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6748 Op.getOperand(Idx));
6749 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6754 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6755 if (EVTBits == 8 && NumElems == 16) {
6756 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6758 if (V.getNode()) return V;
6761 if (EVTBits == 16 && NumElems == 8) {
6762 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6764 if (V.getNode()) return V;
6767 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6768 if (EVTBits == 32 && NumElems == 4) {
6769 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6770 NumZero, DAG, Subtarget, *this);
6775 // If element VT is == 32 bits, turn it into a number of shuffles.
6776 SmallVector<SDValue, 8> V(NumElems);
6777 if (NumElems == 4 && NumZero > 0) {
6778 for (unsigned i = 0; i < 4; ++i) {
6779 bool isZero = !(NonZeros & (1 << i));
6781 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6783 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6786 for (unsigned i = 0; i < 2; ++i) {
6787 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6790 V[i] = V[i*2]; // Must be a zero vector.
6793 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6796 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6799 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6804 bool Reverse1 = (NonZeros & 0x3) == 2;
6805 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6809 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6810 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6812 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6815 if (Values.size() > 1 && VT.is128BitVector()) {
6816 // Check for a build vector of consecutive loads.
6817 for (unsigned i = 0; i < NumElems; ++i)
6818 V[i] = Op.getOperand(i);
6820 // Check for elements which are consecutive loads.
6821 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6825 // Check for a build vector from mostly shuffle plus few inserting.
6826 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6830 // For SSE 4.1, use insertps to put the high elements into the low element.
6831 if (getSubtarget()->hasSSE41()) {
6833 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6834 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6836 Result = DAG.getUNDEF(VT);
6838 for (unsigned i = 1; i < NumElems; ++i) {
6839 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6840 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6841 Op.getOperand(i), DAG.getIntPtrConstant(i));
6846 // Otherwise, expand into a number of unpckl*, start by extending each of
6847 // our (non-undef) elements to the full vector width with the element in the
6848 // bottom slot of the vector (which generates no code for SSE).
6849 for (unsigned i = 0; i < NumElems; ++i) {
6850 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6851 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6853 V[i] = DAG.getUNDEF(VT);
6856 // Next, we iteratively mix elements, e.g. for v4f32:
6857 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6858 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6859 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6860 unsigned EltStride = NumElems >> 1;
6861 while (EltStride != 0) {
6862 for (unsigned i = 0; i < EltStride; ++i) {
6863 // If V[i+EltStride] is undef and this is the first round of mixing,
6864 // then it is safe to just drop this shuffle: V[i] is already in the
6865 // right place, the one element (since it's the first round) being
6866 // inserted as undef can be dropped. This isn't safe for successive
6867 // rounds because they will permute elements within both vectors.
6868 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6869 EltStride == NumElems/2)
6872 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6881 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6882 // to create 256-bit vectors from two other 128-bit ones.
6883 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6885 MVT ResVT = Op.getSimpleValueType();
6887 assert((ResVT.is256BitVector() ||
6888 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6890 SDValue V1 = Op.getOperand(0);
6891 SDValue V2 = Op.getOperand(1);
6892 unsigned NumElems = ResVT.getVectorNumElements();
6893 if(ResVT.is256BitVector())
6894 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6896 if (Op.getNumOperands() == 4) {
6897 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6898 ResVT.getVectorNumElements()/2);
6899 SDValue V3 = Op.getOperand(2);
6900 SDValue V4 = Op.getOperand(3);
6901 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6902 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6904 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6907 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6908 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6909 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6910 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6911 Op.getNumOperands() == 4)));
6913 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6914 // from two other 128-bit ones.
6916 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6917 return LowerAVXCONCAT_VECTORS(Op, DAG);
6921 //===----------------------------------------------------------------------===//
6922 // Vector shuffle lowering
6924 // This is an experimental code path for lowering vector shuffles on x86. It is
6925 // designed to handle arbitrary vector shuffles and blends, gracefully
6926 // degrading performance as necessary. It works hard to recognize idiomatic
6927 // shuffles and lower them to optimal instruction patterns without leaving
6928 // a framework that allows reasonably efficient handling of all vector shuffle
6930 //===----------------------------------------------------------------------===//
6932 /// \brief Tiny helper function to identify a no-op mask.
6934 /// This is a somewhat boring predicate function. It checks whether the mask
6935 /// array input, which is assumed to be a single-input shuffle mask of the kind
6936 /// used by the X86 shuffle instructions (not a fully general
6937 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6938 /// in-place shuffle are 'no-op's.
6939 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6940 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6941 if (Mask[i] != -1 && Mask[i] != i)
6946 /// \brief Helper function to classify a mask as a single-input mask.
6948 /// This isn't a generic single-input test because in the vector shuffle
6949 /// lowering we canonicalize single inputs to be the first input operand. This
6950 /// means we can more quickly test for a single input by only checking whether
6951 /// an input from the second operand exists. We also assume that the size of
6952 /// mask corresponds to the size of the input vectors which isn't true in the
6953 /// fully general case.
6954 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6956 if (M >= (int)Mask.size())
6961 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6963 /// This helper function produces an 8-bit shuffle immediate corresponding to
6964 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6965 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6968 /// NB: We rely heavily on "undef" masks preserving the input lane.
6969 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6970 SelectionDAG &DAG) {
6971 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6972 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6973 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6974 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6975 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6978 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6979 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6980 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6981 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6982 return DAG.getConstant(Imm, MVT::i8);
6985 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6987 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6988 /// support for floating point shuffles but not integer shuffles. These
6989 /// instructions will incur a domain crossing penalty on some chips though so
6990 /// it is better to avoid lowering through this for integer vectors where
6992 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6993 const X86Subtarget *Subtarget,
6994 SelectionDAG &DAG) {
6996 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6997 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6998 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6999 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7000 ArrayRef<int> Mask = SVOp->getMask();
7001 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7003 if (isSingleInputShuffleMask(Mask)) {
7004 // Straight shuffle of a single input vector. Simulate this by using the
7005 // single input as both of the "inputs" to this instruction..
7006 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7007 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7008 DAG.getConstant(SHUFPDMask, MVT::i8));
7010 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7011 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7013 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7014 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7015 DAG.getConstant(SHUFPDMask, MVT::i8));
7018 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7020 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7021 /// the integer unit to minimize domain crossing penalties. However, for blends
7022 /// it falls back to the floating point shuffle operation with appropriate bit
7024 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7025 const X86Subtarget *Subtarget,
7026 SelectionDAG &DAG) {
7028 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7029 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7030 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7031 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7032 ArrayRef<int> Mask = SVOp->getMask();
7033 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7035 if (isSingleInputShuffleMask(Mask)) {
7036 // Straight shuffle of a single input vector. For everything from SSE2
7037 // onward this has a single fast instruction with no scary immediates.
7038 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7039 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7040 int WidenedMask[4] = {
7041 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7042 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7044 ISD::BITCAST, DL, MVT::v2i64,
7045 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7046 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7049 // We implement this with SHUFPD which is pretty lame because it will likely
7050 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7051 // However, all the alternatives are still more cycles and newer chips don't
7052 // have this problem. It would be really nice if x86 had better shuffles here.
7053 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7054 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7055 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7056 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7059 /// \brief Lower 4-lane 32-bit floating point shuffles.
7061 /// Uses instructions exclusively from the floating point unit to minimize
7062 /// domain crossing penalties, as these are sufficient to implement all v4f32
7064 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7065 const X86Subtarget *Subtarget,
7066 SelectionDAG &DAG) {
7068 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7069 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7070 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7071 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7072 ArrayRef<int> Mask = SVOp->getMask();
7073 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7075 SDValue LowV = V1, HighV = V2;
7076 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7079 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7081 if (NumV2Elements == 0)
7082 // Straight shuffle of a single input vector. We pass the input vector to
7083 // both operands to simulate this with a SHUFPS.
7084 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7085 getV4X86ShuffleImm8ForMask(Mask, DAG));
7087 if (NumV2Elements == 1) {
7089 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7091 // Compute the index adjacent to V2Index and in the same half by toggling
7093 int V2AdjIndex = V2Index ^ 1;
7095 if (Mask[V2AdjIndex] == -1) {
7096 // Handles all the cases where we have a single V2 element and an undef.
7097 // This will only ever happen in the high lanes because we commute the
7098 // vector otherwise.
7100 std::swap(LowV, HighV);
7101 NewMask[V2Index] -= 4;
7103 // Handle the case where the V2 element ends up adjacent to a V1 element.
7104 // To make this work, blend them together as the first step.
7105 int V1Index = V2AdjIndex;
7106 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7107 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7108 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7110 // Now proceed to reconstruct the final blend as we have the necessary
7111 // high or low half formed.
7118 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7119 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7121 } else if (NumV2Elements == 2) {
7122 if (Mask[0] < 4 && Mask[1] < 4) {
7123 // Handle the easy case where we have V1 in the low lanes and V2 in the
7124 // high lanes. We never see this reversed because we sort the shuffle.
7128 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7129 // trying to place elements directly, just blend them and set up the final
7130 // shuffle to place them.
7132 // The first two blend mask elements are for V1, the second two are for
7134 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7135 Mask[2] < 4 ? Mask[2] : Mask[3],
7136 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7137 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7138 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7139 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7141 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7144 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7145 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7146 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7147 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7150 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7151 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7154 /// \brief Lower 4-lane i32 vector shuffles.
7156 /// We try to handle these with integer-domain shuffles where we can, but for
7157 /// blends we use the floating point domain blend instructions.
7158 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7159 const X86Subtarget *Subtarget,
7160 SelectionDAG &DAG) {
7162 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7163 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7164 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7165 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7166 ArrayRef<int> Mask = SVOp->getMask();
7167 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7169 if (isSingleInputShuffleMask(Mask))
7170 // Straight shuffle of a single input vector. For everything from SSE2
7171 // onward this has a single fast instruction with no scary immediates.
7172 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7173 getV4X86ShuffleImm8ForMask(Mask, DAG));
7175 // We implement this with SHUFPS because it can blend from two vectors.
7176 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7177 // up the inputs, bypassing domain shift penalties that we would encur if we
7178 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7180 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7181 DAG.getVectorShuffle(
7183 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7184 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7187 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7188 /// shuffle lowering, and the most complex part.
7190 /// The lowering strategy is to try to form pairs of input lanes which are
7191 /// targeted at the same half of the final vector, and then use a dword shuffle
7192 /// to place them onto the right half, and finally unpack the paired lanes into
7193 /// their final position.
7195 /// The exact breakdown of how to form these dword pairs and align them on the
7196 /// correct sides is really tricky. See the comments within the function for
7197 /// more of the details.
7198 static SDValue lowerV8I16SingleInputVectorShuffle(
7199 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7200 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7201 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7202 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7203 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7205 SmallVector<int, 4> LoInputs;
7206 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7207 [](int M) { return M >= 0; });
7208 std::sort(LoInputs.begin(), LoInputs.end());
7209 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7210 SmallVector<int, 4> HiInputs;
7211 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7212 [](int M) { return M >= 0; });
7213 std::sort(HiInputs.begin(), HiInputs.end());
7214 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7216 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7217 int NumHToL = LoInputs.size() - NumLToL;
7219 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7220 int NumHToH = HiInputs.size() - NumLToH;
7221 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7222 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7223 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7224 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7226 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7227 // such inputs we can swap two of the dwords across the half mark and end up
7228 // with <=2 inputs to each half in each half. Once there, we can fall through
7229 // to the generic code below. For example:
7231 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7232 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7234 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7236 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7237 int ThreeInputHalfSum, int OneInputHalfOffset) {
7238 // Compute the index of dword with only one word among the three inputs in
7239 // a half by taking the sum of the half with three inputs and subtracting
7240 // the sum of the actual three inputs. The difference is the remaining
7242 int DWordA = (ThreeInputHalfSum -
7243 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7245 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7247 int PSHUFDMask[] = {0, 1, 2, 3};
7248 PSHUFDMask[DWordA] = DWordB;
7249 PSHUFDMask[DWordB] = DWordA;
7250 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7251 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7252 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7253 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7255 // Adjust the mask to match the new locations of A and B.
7257 if (M != -1 && M/2 == DWordA)
7258 M = 2 * DWordB + M % 2;
7259 else if (M != -1 && M/2 == DWordB)
7260 M = 2 * DWordA + M % 2;
7262 // Recurse back into this routine to re-compute state now that this isn't
7263 // a 3 and 1 problem.
7264 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7267 if (NumLToL == 3 && NumHToL == 1)
7268 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7269 else if (NumLToL == 1 && NumHToL == 3)
7270 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7271 else if (NumLToH == 1 && NumHToH == 3)
7272 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7273 else if (NumLToH == 3 && NumHToH == 1)
7274 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7276 // At this point there are at most two inputs to the low and high halves from
7277 // each half. That means the inputs can always be grouped into dwords and
7278 // those dwords can then be moved to the correct half with a dword shuffle.
7279 // We use at most one low and one high word shuffle to collect these paired
7280 // inputs into dwords, and finally a dword shuffle to place them.
7281 int PSHUFLMask[4] = {-1, -1, -1, -1};
7282 int PSHUFHMask[4] = {-1, -1, -1, -1};
7283 int PSHUFDMask[4] = {-1, -1, -1, -1};
7285 // First fix the masks for all the inputs that are staying in their
7286 // original halves. This will then dictate the targets of the cross-half
7288 auto fixInPlaceInputs = [&PSHUFDMask](
7289 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7290 MutableArrayRef<int> HalfMask, int HalfOffset) {
7291 if (InPlaceInputs.empty())
7293 if (InPlaceInputs.size() == 1) {
7294 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7295 InPlaceInputs[0] - HalfOffset;
7296 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7300 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7301 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7302 InPlaceInputs[0] - HalfOffset;
7303 // Put the second input next to the first so that they are packed into
7304 // a dword. We find the adjacent index by toggling the low bit.
7305 int AdjIndex = InPlaceInputs[0] ^ 1;
7306 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7307 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7308 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7310 if (!HToLInputs.empty())
7311 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7312 if (!LToHInputs.empty())
7313 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7315 // Now gather the cross-half inputs and place them into a free dword of
7316 // their target half.
7317 // FIXME: This operation could almost certainly be simplified dramatically to
7318 // look more like the 3-1 fixing operation.
7319 auto moveInputsToRightHalf = [&PSHUFDMask](
7320 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7321 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7322 int SourceOffset, int DestOffset) {
7323 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7324 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7326 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7328 int LowWord = Word & ~1;
7329 int HighWord = Word | 1;
7330 return isWordClobbered(SourceHalfMask, LowWord) ||
7331 isWordClobbered(SourceHalfMask, HighWord);
7334 if (IncomingInputs.empty())
7337 if (ExistingInputs.empty()) {
7338 // Map any dwords with inputs from them into the right half.
7339 for (int Input : IncomingInputs) {
7340 // If the source half mask maps over the inputs, turn those into
7341 // swaps and use the swapped lane.
7342 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7343 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7344 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7345 Input - SourceOffset;
7346 // We have to swap the uses in our half mask in one sweep.
7347 for (int &M : HalfMask)
7348 if (M == SourceHalfMask[Input - SourceOffset])
7350 else if (M == Input)
7351 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7353 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7354 Input - SourceOffset &&
7355 "Previous placement doesn't match!");
7357 // Note that this correctly re-maps both when we do a swap and when
7358 // we observe the other side of the swap above. We rely on that to
7359 // avoid swapping the members of the input list directly.
7360 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7363 // Map the input's dword into the correct half.
7364 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7365 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7367 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7369 "Previous placement doesn't match!");
7372 // And just directly shift any other-half mask elements to be same-half
7373 // as we will have mirrored the dword containing the element into the
7374 // same position within that half.
7375 for (int &M : HalfMask)
7376 if (M >= SourceOffset && M < SourceOffset + 4) {
7377 M = M - SourceOffset + DestOffset;
7378 assert(M >= 0 && "This should never wrap below zero!");
7383 // Ensure we have the input in a viable dword of its current half. This
7384 // is particularly tricky because the original position may be clobbered
7385 // by inputs being moved and *staying* in that half.
7386 if (IncomingInputs.size() == 1) {
7387 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7388 int InputFixed = std::find(std::begin(SourceHalfMask),
7389 std::end(SourceHalfMask), -1) -
7390 std::begin(SourceHalfMask) + SourceOffset;
7391 SourceHalfMask[InputFixed - SourceOffset] =
7392 IncomingInputs[0] - SourceOffset;
7393 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7395 IncomingInputs[0] = InputFixed;
7397 } else if (IncomingInputs.size() == 2) {
7398 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7399 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7400 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7401 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7402 "Not all dwords can be clobbered!");
7403 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7404 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7405 for (int &M : HalfMask)
7406 if (M == IncomingInputs[0])
7407 M = SourceDWordBase + SourceOffset;
7408 else if (M == IncomingInputs[1])
7409 M = SourceDWordBase + 1 + SourceOffset;
7410 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7411 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7414 llvm_unreachable("Unhandled input size!");
7417 // Now hoist the DWord down to the right half.
7418 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7419 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7420 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7421 for (int Input : IncomingInputs)
7422 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7423 FreeDWord * 2 + Input % 2);
7425 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7426 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7427 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7428 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7430 // Now enact all the shuffles we've computed to move the inputs into their
7432 if (!isNoopShuffleMask(PSHUFLMask))
7433 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7434 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7435 if (!isNoopShuffleMask(PSHUFHMask))
7436 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7437 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7438 if (!isNoopShuffleMask(PSHUFDMask))
7439 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7440 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7441 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7442 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7444 // At this point, each half should contain all its inputs, and we can then
7445 // just shuffle them into their final position.
7446 assert(std::count_if(LoMask.begin(), LoMask.end(),
7447 [](int M) { return M >= 4; }) == 0 &&
7448 "Failed to lift all the high half inputs to the low mask!");
7449 assert(std::count_if(HiMask.begin(), HiMask.end(),
7450 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7451 "Failed to lift all the low half inputs to the high mask!");
7453 // Do a half shuffle for the low mask.
7454 if (!isNoopShuffleMask(LoMask))
7455 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7456 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7458 // Do a half shuffle with the high mask after shifting its values down.
7459 for (int &M : HiMask)
7462 if (!isNoopShuffleMask(HiMask))
7463 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7464 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7469 /// \brief Detect whether the mask pattern should be lowered through
7472 /// This essentially tests whether viewing the mask as an interleaving of two
7473 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7474 /// lowering it through interleaving is a significantly better strategy.
7475 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7476 int NumEvenInputs[2] = {0, 0};
7477 int NumOddInputs[2] = {0, 0};
7478 int NumLoInputs[2] = {0, 0};
7479 int NumHiInputs[2] = {0, 0};
7480 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7484 int InputIdx = Mask[i] >= Size;
7487 ++NumLoInputs[InputIdx];
7489 ++NumHiInputs[InputIdx];
7492 ++NumEvenInputs[InputIdx];
7494 ++NumOddInputs[InputIdx];
7497 // The minimum number of cross-input results for both the interleaved and
7498 // split cases. If interleaving results in fewer cross-input results, return
7500 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7501 NumEvenInputs[0] + NumOddInputs[1]);
7502 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7503 NumLoInputs[0] + NumHiInputs[1]);
7504 return InterleavedCrosses < SplitCrosses;
7507 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7509 /// This strategy only works when the inputs from each vector fit into a single
7510 /// half of that vector, and generally there are not so many inputs as to leave
7511 /// the in-place shuffles required highly constrained (and thus expensive). It
7512 /// shifts all the inputs into a single side of both input vectors and then
7513 /// uses an unpack to interleave these inputs in a single vector. At that
7514 /// point, we will fall back on the generic single input shuffle lowering.
7515 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7517 MutableArrayRef<int> Mask,
7518 const X86Subtarget *Subtarget,
7519 SelectionDAG &DAG) {
7520 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7521 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7522 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7523 for (int i = 0; i < 8; ++i)
7524 if (Mask[i] >= 0 && Mask[i] < 4)
7525 LoV1Inputs.push_back(i);
7526 else if (Mask[i] >= 4 && Mask[i] < 8)
7527 HiV1Inputs.push_back(i);
7528 else if (Mask[i] >= 8 && Mask[i] < 12)
7529 LoV2Inputs.push_back(i);
7530 else if (Mask[i] >= 12)
7531 HiV2Inputs.push_back(i);
7533 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7534 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7537 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7538 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7539 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7541 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7542 HiV1Inputs.size() + HiV2Inputs.size();
7544 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7545 ArrayRef<int> HiInputs, bool MoveToLo,
7547 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7548 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7549 if (BadInputs.empty())
7552 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7553 int MoveOffset = MoveToLo ? 0 : 4;
7555 if (GoodInputs.empty()) {
7556 for (int BadInput : BadInputs) {
7557 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7558 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7561 if (GoodInputs.size() == 2) {
7562 // If the low inputs are spread across two dwords, pack them into
7564 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7565 Mask[GoodInputs[0]] - MaskOffset;
7566 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7567 Mask[GoodInputs[1]] - MaskOffset;
7568 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7569 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7571 // Otherwise pin the low inputs.
7572 for (int GoodInput : GoodInputs)
7573 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7577 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7578 std::begin(MoveMask);
7579 assert(MoveMaskIdx >= MoveOffset && "Established above");
7581 if (BadInputs.size() == 2) {
7582 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7583 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7584 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7585 Mask[BadInputs[0]] - MaskOffset;
7586 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7587 Mask[BadInputs[1]] - MaskOffset;
7588 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7589 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7591 assert(BadInputs.size() == 1 && "All sizes handled");
7592 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7593 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7597 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7600 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7602 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7605 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7606 // cross-half traffic in the final shuffle.
7608 // Munge the mask to be a single-input mask after the unpack merges the
7612 M = 2 * (M % 4) + (M / 8);
7614 return DAG.getVectorShuffle(
7615 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7616 DL, MVT::v8i16, V1, V2),
7617 DAG.getUNDEF(MVT::v8i16), Mask);
7620 /// \brief Generic lowering of 8-lane i16 shuffles.
7622 /// This handles both single-input shuffles and combined shuffle/blends with
7623 /// two inputs. The single input shuffles are immediately delegated to
7624 /// a dedicated lowering routine.
7626 /// The blends are lowered in one of three fundamental ways. If there are few
7627 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7628 /// of the input is significantly cheaper when lowered as an interleaving of
7629 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7630 /// halves of the inputs separately (making them have relatively few inputs)
7631 /// and then concatenate them.
7632 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7633 const X86Subtarget *Subtarget,
7634 SelectionDAG &DAG) {
7636 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7637 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7638 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7639 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7640 ArrayRef<int> OrigMask = SVOp->getMask();
7641 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7642 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7643 MutableArrayRef<int> Mask(MaskStorage);
7645 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7647 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7648 auto isV2 = [](int M) { return M >= 8; };
7650 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7651 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7653 if (NumV2Inputs == 0)
7654 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7656 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7657 "to be V1-input shuffles.");
7659 if (NumV1Inputs + NumV2Inputs <= 4)
7660 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7662 // Check whether an interleaving lowering is likely to be more efficient.
7663 // This isn't perfect but it is a strong heuristic that tends to work well on
7664 // the kinds of shuffles that show up in practice.
7666 // FIXME: Handle 1x, 2x, and 4x interleaving.
7667 if (shouldLowerAsInterleaving(Mask)) {
7668 // FIXME: Figure out whether we should pack these into the low or high
7671 int EMask[8], OMask[8];
7672 for (int i = 0; i < 4; ++i) {
7673 EMask[i] = Mask[2*i];
7674 OMask[i] = Mask[2*i + 1];
7679 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7680 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7682 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7685 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7686 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7688 for (int i = 0; i < 4; ++i) {
7689 LoBlendMask[i] = Mask[i];
7690 HiBlendMask[i] = Mask[i + 4];
7693 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7694 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7695 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7696 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7698 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7699 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7702 /// \brief Generic lowering of v16i8 shuffles.
7704 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7705 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7706 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7707 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7709 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7710 const X86Subtarget *Subtarget,
7711 SelectionDAG &DAG) {
7713 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7714 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7715 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7716 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7717 ArrayRef<int> OrigMask = SVOp->getMask();
7718 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7719 int MaskStorage[16] = {
7720 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7721 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7722 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7723 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7724 MutableArrayRef<int> Mask(MaskStorage);
7725 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7726 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7728 // For single-input shuffles, there are some nicer lowering tricks we can use.
7729 if (isSingleInputShuffleMask(Mask)) {
7730 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7731 // Notably, this handles splat and partial-splat shuffles more efficiently.
7732 // However, it only makes sense if the pre-duplication shuffle simplifies
7733 // things significantly. Currently, this means we need to be able to
7734 // express the pre-duplication shuffle as an i16 shuffle.
7736 // FIXME: We should check for other patterns which can be widened into an
7737 // i16 shuffle as well.
7738 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7739 for (int i = 0; i < 16; i += 2) {
7740 if (Mask[i] != Mask[i + 1])
7745 auto tryToWidenViaDuplication = [&]() -> SDValue {
7746 if (!canWidenViaDuplication(Mask))
7748 SmallVector<int, 4> LoInputs;
7749 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7750 [](int M) { return M >= 0 && M < 8; });
7751 std::sort(LoInputs.begin(), LoInputs.end());
7752 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7754 SmallVector<int, 4> HiInputs;
7755 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7756 [](int M) { return M >= 8; });
7757 std::sort(HiInputs.begin(), HiInputs.end());
7758 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7761 bool TargetLo = LoInputs.size() >= HiInputs.size();
7762 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7763 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7765 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7766 SmallDenseMap<int, int, 8> LaneMap;
7767 for (int I : InPlaceInputs) {
7768 PreDupI16Shuffle[I/2] = I/2;
7771 int j = TargetLo ? 0 : 4, je = j + 4;
7772 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7773 // Check if j is already a shuffle of this input. This happens when
7774 // there are two adjacent bytes after we move the low one.
7775 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7776 // If we haven't yet mapped the input, search for a slot into which
7778 while (j < je && PreDupI16Shuffle[j] != -1)
7782 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7785 // Map this input with the i16 shuffle.
7786 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7789 // Update the lane map based on the mapping we ended up with.
7790 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7793 ISD::BITCAST, DL, MVT::v16i8,
7794 DAG.getVectorShuffle(MVT::v8i16, DL,
7795 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7796 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7798 // Unpack the bytes to form the i16s that will be shuffled into place.
7799 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7800 MVT::v16i8, V1, V1);
7802 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7803 for (int i = 0; i < 16; i += 2) {
7805 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7806 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7809 ISD::BITCAST, DL, MVT::v16i8,
7810 DAG.getVectorShuffle(MVT::v8i16, DL,
7811 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7812 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7814 if (SDValue V = tryToWidenViaDuplication())
7818 // Check whether an interleaving lowering is likely to be more efficient.
7819 // This isn't perfect but it is a strong heuristic that tends to work well on
7820 // the kinds of shuffles that show up in practice.
7822 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7823 if (shouldLowerAsInterleaving(Mask)) {
7824 // FIXME: Figure out whether we should pack these into the low or high
7827 int EMask[16], OMask[16];
7828 for (int i = 0; i < 8; ++i) {
7829 EMask[i] = Mask[2*i];
7830 OMask[i] = Mask[2*i + 1];
7835 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7836 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7838 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7841 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7842 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7843 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7844 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7846 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7847 MutableArrayRef<int> V1HalfBlendMask,
7848 MutableArrayRef<int> V2HalfBlendMask) {
7849 for (int i = 0; i < 8; ++i)
7850 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7851 V1HalfBlendMask[i] = HalfMask[i];
7853 } else if (HalfMask[i] >= 16) {
7854 V2HalfBlendMask[i] = HalfMask[i] - 16;
7855 HalfMask[i] = i + 8;
7858 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7859 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7861 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7863 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7864 MutableArrayRef<int> HiBlendMask) {
7866 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7867 // them out and avoid using UNPCK{L,H} to extract the elements of V as
7869 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7870 [](int M) { return M >= 0 && M % 2 == 1; }) &&
7871 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7872 [](int M) { return M >= 0 && M % 2 == 1; })) {
7873 // Use a mask to drop the high bytes.
7874 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7875 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7876 DAG.getConstant(0x00FF, MVT::v8i16));
7878 // This will be a single vector shuffle instead of a blend so nuke V2.
7879 V2 = DAG.getUNDEF(MVT::v8i16);
7881 // Squash the masks to point directly into V1.
7882 for (int &M : LoBlendMask)
7885 for (int &M : HiBlendMask)
7889 // Otherwise just unpack the low half of V into V1 and the high half into
7890 // V2 so that we can blend them as i16s.
7891 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7892 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7893 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7894 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7897 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7898 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7899 return std::make_pair(BlendedLo, BlendedHi);
7901 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7902 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7903 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7905 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7906 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7908 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7911 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7913 /// This routine breaks down the specific type of 128-bit shuffle and
7914 /// dispatches to the lowering routines accordingly.
7915 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7916 MVT VT, const X86Subtarget *Subtarget,
7917 SelectionDAG &DAG) {
7918 switch (VT.SimpleTy) {
7920 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7922 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7924 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7926 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7928 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7930 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7933 llvm_unreachable("Unimplemented!");
7937 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7938 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7939 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7940 if (Mask[i] + 1 != Mask[i+1])
7946 /// \brief Top-level lowering for x86 vector shuffles.
7948 /// This handles decomposition, canonicalization, and lowering of all x86
7949 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7950 /// above in helper routines. The canonicalization attempts to widen shuffles
7951 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7952 /// s.t. only one of the two inputs needs to be tested, etc.
7953 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7954 SelectionDAG &DAG) {
7955 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7956 ArrayRef<int> Mask = SVOp->getMask();
7957 SDValue V1 = Op.getOperand(0);
7958 SDValue V2 = Op.getOperand(1);
7959 MVT VT = Op.getSimpleValueType();
7960 int NumElements = VT.getVectorNumElements();
7963 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7965 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7966 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7967 if (V1IsUndef && V2IsUndef)
7968 return DAG.getUNDEF(VT);
7970 // When we create a shuffle node we put the UNDEF node to second operand,
7971 // but in some cases the first operand may be transformed to UNDEF.
7972 // In this case we should just commute the node.
7974 return DAG.getCommutedVectorShuffle(*SVOp);
7976 // Check for non-undef masks pointing at an undef vector and make the masks
7977 // undef as well. This makes it easier to match the shuffle based solely on
7981 if (M >= NumElements) {
7982 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7983 for (int &M : NewMask)
7984 if (M >= NumElements)
7986 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7989 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7990 // lanes but wider integers. We cap this to not form integers larger than i64
7991 // but it might be interesting to form i128 integers to handle flipping the
7992 // low and high halves of AVX 256-bit vectors.
7993 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7994 areAdjacentMasksSequential(Mask)) {
7995 SmallVector<int, 8> NewMask;
7996 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7997 NewMask.push_back(Mask[i] / 2);
7999 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8000 VT.getVectorNumElements() / 2);
8001 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8002 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8003 return DAG.getNode(ISD::BITCAST, dl, VT,
8004 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8007 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8008 for (int M : SVOp->getMask())
8011 else if (M < NumElements)
8016 // Commute the shuffle as needed such that more elements come from V1 than
8017 // V2. This allows us to match the shuffle pattern strictly on how many
8018 // elements come from V1 without handling the symmetric cases.
8019 if (NumV2Elements > NumV1Elements)
8020 return DAG.getCommutedVectorShuffle(*SVOp);
8022 // When the number of V1 and V2 elements are the same, try to minimize the
8023 // number of uses of V2 in the low half of the vector.
8024 if (NumV1Elements == NumV2Elements) {
8025 int LowV1Elements = 0, LowV2Elements = 0;
8026 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8027 if (M >= NumElements)
8031 if (LowV2Elements > LowV1Elements)
8032 return DAG.getCommutedVectorShuffle(*SVOp);
8035 // For each vector width, delegate to a specialized lowering routine.
8036 if (VT.getSizeInBits() == 128)
8037 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8039 llvm_unreachable("Unimplemented!");
8043 //===----------------------------------------------------------------------===//
8044 // Legacy vector shuffle lowering
8046 // This code is the legacy code handling vector shuffles until the above
8047 // replaces its functionality and performance.
8048 //===----------------------------------------------------------------------===//
8050 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8051 bool hasInt256, unsigned *MaskOut = nullptr) {
8052 MVT EltVT = VT.getVectorElementType();
8054 // There is no blend with immediate in AVX-512.
8055 if (VT.is512BitVector())
8058 if (!hasSSE41 || EltVT == MVT::i8)
8060 if (!hasInt256 && VT == MVT::v16i16)
8063 unsigned MaskValue = 0;
8064 unsigned NumElems = VT.getVectorNumElements();
8065 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8066 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8067 unsigned NumElemsInLane = NumElems / NumLanes;
8069 // Blend for v16i16 should be symetric for the both lanes.
8070 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8072 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8073 int EltIdx = MaskVals[i];
8075 if ((EltIdx < 0 || EltIdx == (int)i) &&
8076 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8079 if (((unsigned)EltIdx == (i + NumElems)) &&
8080 (SndLaneEltIdx < 0 ||
8081 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8082 MaskValue |= (1 << i);
8088 *MaskOut = MaskValue;
8092 // Try to lower a shuffle node into a simple blend instruction.
8093 // This function assumes isBlendMask returns true for this
8094 // SuffleVectorSDNode
8095 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8097 const X86Subtarget *Subtarget,
8098 SelectionDAG &DAG) {
8099 MVT VT = SVOp->getSimpleValueType(0);
8100 MVT EltVT = VT.getVectorElementType();
8101 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8102 Subtarget->hasInt256() && "Trying to lower a "
8103 "VECTOR_SHUFFLE to a Blend but "
8104 "with the wrong mask"));
8105 SDValue V1 = SVOp->getOperand(0);
8106 SDValue V2 = SVOp->getOperand(1);
8108 unsigned NumElems = VT.getVectorNumElements();
8110 // Convert i32 vectors to floating point if it is not AVX2.
8111 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8113 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8114 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8116 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8117 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8120 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8121 DAG.getConstant(MaskValue, MVT::i32));
8122 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8125 /// In vector type \p VT, return true if the element at index \p InputIdx
8126 /// falls on a different 128-bit lane than \p OutputIdx.
8127 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8128 unsigned OutputIdx) {
8129 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8130 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8133 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8134 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8135 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8136 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8138 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8139 SelectionDAG &DAG) {
8140 MVT VT = V1.getSimpleValueType();
8141 assert(VT.is128BitVector() || VT.is256BitVector());
8143 MVT EltVT = VT.getVectorElementType();
8144 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8145 unsigned NumElts = VT.getVectorNumElements();
8147 SmallVector<SDValue, 32> PshufbMask;
8148 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8149 int InputIdx = MaskVals[OutputIdx];
8150 unsigned InputByteIdx;
8152 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8153 InputByteIdx = 0x80;
8155 // Cross lane is not allowed.
8156 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8158 InputByteIdx = InputIdx * EltSizeInBytes;
8159 // Index is an byte offset within the 128-bit lane.
8160 InputByteIdx &= 0xf;
8163 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8164 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8165 if (InputByteIdx != 0x80)
8170 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8172 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8173 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8174 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8177 // v8i16 shuffles - Prefer shuffles in the following order:
8178 // 1. [all] pshuflw, pshufhw, optional move
8179 // 2. [ssse3] 1 x pshufb
8180 // 3. [ssse3] 2 x pshufb + 1 x por
8181 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8183 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8184 SelectionDAG &DAG) {
8185 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8186 SDValue V1 = SVOp->getOperand(0);
8187 SDValue V2 = SVOp->getOperand(1);
8189 SmallVector<int, 8> MaskVals;
8191 // Determine if more than 1 of the words in each of the low and high quadwords
8192 // of the result come from the same quadword of one of the two inputs. Undef
8193 // mask values count as coming from any quadword, for better codegen.
8195 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8196 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8197 unsigned LoQuad[] = { 0, 0, 0, 0 };
8198 unsigned HiQuad[] = { 0, 0, 0, 0 };
8199 // Indices of quads used.
8200 std::bitset<4> InputQuads;
8201 for (unsigned i = 0; i < 8; ++i) {
8202 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8203 int EltIdx = SVOp->getMaskElt(i);
8204 MaskVals.push_back(EltIdx);
8213 InputQuads.set(EltIdx / 4);
8216 int BestLoQuad = -1;
8217 unsigned MaxQuad = 1;
8218 for (unsigned i = 0; i < 4; ++i) {
8219 if (LoQuad[i] > MaxQuad) {
8221 MaxQuad = LoQuad[i];
8225 int BestHiQuad = -1;
8227 for (unsigned i = 0; i < 4; ++i) {
8228 if (HiQuad[i] > MaxQuad) {
8230 MaxQuad = HiQuad[i];
8234 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8235 // of the two input vectors, shuffle them into one input vector so only a
8236 // single pshufb instruction is necessary. If there are more than 2 input
8237 // quads, disable the next transformation since it does not help SSSE3.
8238 bool V1Used = InputQuads[0] || InputQuads[1];
8239 bool V2Used = InputQuads[2] || InputQuads[3];
8240 if (Subtarget->hasSSSE3()) {
8241 if (InputQuads.count() == 2 && V1Used && V2Used) {
8242 BestLoQuad = InputQuads[0] ? 0 : 1;
8243 BestHiQuad = InputQuads[2] ? 2 : 3;
8245 if (InputQuads.count() > 2) {
8251 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8252 // the shuffle mask. If a quad is scored as -1, that means that it contains
8253 // words from all 4 input quadwords.
8255 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8257 BestLoQuad < 0 ? 0 : BestLoQuad,
8258 BestHiQuad < 0 ? 1 : BestHiQuad
8260 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8261 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8262 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8263 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8265 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8266 // source words for the shuffle, to aid later transformations.
8267 bool AllWordsInNewV = true;
8268 bool InOrder[2] = { true, true };
8269 for (unsigned i = 0; i != 8; ++i) {
8270 int idx = MaskVals[i];
8272 InOrder[i/4] = false;
8273 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8275 AllWordsInNewV = false;
8279 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8280 if (AllWordsInNewV) {
8281 for (int i = 0; i != 8; ++i) {
8282 int idx = MaskVals[i];
8285 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8286 if ((idx != i) && idx < 4)
8288 if ((idx != i) && idx > 3)
8297 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8298 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8299 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8300 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8301 unsigned TargetMask = 0;
8302 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8303 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8304 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8305 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8306 getShufflePSHUFLWImmediate(SVOp);
8307 V1 = NewV.getOperand(0);
8308 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8312 // Promote splats to a larger type which usually leads to more efficient code.
8313 // FIXME: Is this true if pshufb is available?
8314 if (SVOp->isSplat())
8315 return PromoteSplat(SVOp, DAG);
8317 // If we have SSSE3, and all words of the result are from 1 input vector,
8318 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8319 // is present, fall back to case 4.
8320 if (Subtarget->hasSSSE3()) {
8321 SmallVector<SDValue,16> pshufbMask;
8323 // If we have elements from both input vectors, set the high bit of the
8324 // shuffle mask element to zero out elements that come from V2 in the V1
8325 // mask, and elements that come from V1 in the V2 mask, so that the two
8326 // results can be OR'd together.
8327 bool TwoInputs = V1Used && V2Used;
8328 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8330 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8332 // Calculate the shuffle mask for the second input, shuffle it, and
8333 // OR it with the first shuffled input.
8334 CommuteVectorShuffleMask(MaskVals, 8);
8335 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8336 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8337 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8340 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8341 // and update MaskVals with new element order.
8342 std::bitset<8> InOrder;
8343 if (BestLoQuad >= 0) {
8344 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8345 for (int i = 0; i != 4; ++i) {
8346 int idx = MaskVals[i];
8349 } else if ((idx / 4) == BestLoQuad) {
8354 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8357 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8358 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8359 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8361 getShufflePSHUFLWImmediate(SVOp), DAG);
8365 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8366 // and update MaskVals with the new element order.
8367 if (BestHiQuad >= 0) {
8368 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8369 for (unsigned i = 4; i != 8; ++i) {
8370 int idx = MaskVals[i];
8373 } else if ((idx / 4) == BestHiQuad) {
8374 MaskV[i] = (idx & 3) + 4;
8378 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8381 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8382 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8383 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8385 getShufflePSHUFHWImmediate(SVOp), DAG);
8389 // In case BestHi & BestLo were both -1, which means each quadword has a word
8390 // from each of the four input quadwords, calculate the InOrder bitvector now
8391 // before falling through to the insert/extract cleanup.
8392 if (BestLoQuad == -1 && BestHiQuad == -1) {
8394 for (int i = 0; i != 8; ++i)
8395 if (MaskVals[i] < 0 || MaskVals[i] == i)
8399 // The other elements are put in the right place using pextrw and pinsrw.
8400 for (unsigned i = 0; i != 8; ++i) {
8403 int EltIdx = MaskVals[i];
8406 SDValue ExtOp = (EltIdx < 8) ?
8407 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8408 DAG.getIntPtrConstant(EltIdx)) :
8409 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8410 DAG.getIntPtrConstant(EltIdx - 8));
8411 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8412 DAG.getIntPtrConstant(i));
8417 /// \brief v16i16 shuffles
8419 /// FIXME: We only support generation of a single pshufb currently. We can
8420 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8421 /// well (e.g 2 x pshufb + 1 x por).
8423 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8424 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8425 SDValue V1 = SVOp->getOperand(0);
8426 SDValue V2 = SVOp->getOperand(1);
8429 if (V2.getOpcode() != ISD::UNDEF)
8432 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8433 return getPSHUFB(MaskVals, V1, dl, DAG);
8436 // v16i8 shuffles - Prefer shuffles in the following order:
8437 // 1. [ssse3] 1 x pshufb
8438 // 2. [ssse3] 2 x pshufb + 1 x por
8439 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8440 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8441 const X86Subtarget* Subtarget,
8442 SelectionDAG &DAG) {
8443 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8444 SDValue V1 = SVOp->getOperand(0);
8445 SDValue V2 = SVOp->getOperand(1);
8447 ArrayRef<int> MaskVals = SVOp->getMask();
8449 // Promote splats to a larger type which usually leads to more efficient code.
8450 // FIXME: Is this true if pshufb is available?
8451 if (SVOp->isSplat())
8452 return PromoteSplat(SVOp, DAG);
8454 // If we have SSSE3, case 1 is generated when all result bytes come from
8455 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8456 // present, fall back to case 3.
8458 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8459 if (Subtarget->hasSSSE3()) {
8460 SmallVector<SDValue,16> pshufbMask;
8462 // If all result elements are from one input vector, then only translate
8463 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8465 // Otherwise, we have elements from both input vectors, and must zero out
8466 // elements that come from V2 in the first mask, and V1 in the second mask
8467 // so that we can OR them together.
8468 for (unsigned i = 0; i != 16; ++i) {
8469 int EltIdx = MaskVals[i];
8470 if (EltIdx < 0 || EltIdx >= 16)
8472 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8474 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8475 DAG.getNode(ISD::BUILD_VECTOR, dl,
8476 MVT::v16i8, pshufbMask));
8478 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8479 // the 2nd operand if it's undefined or zero.
8480 if (V2.getOpcode() == ISD::UNDEF ||
8481 ISD::isBuildVectorAllZeros(V2.getNode()))
8484 // Calculate the shuffle mask for the second input, shuffle it, and
8485 // OR it with the first shuffled input.
8487 for (unsigned i = 0; i != 16; ++i) {
8488 int EltIdx = MaskVals[i];
8489 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8490 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8492 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8493 DAG.getNode(ISD::BUILD_VECTOR, dl,
8494 MVT::v16i8, pshufbMask));
8495 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8498 // No SSSE3 - Calculate in place words and then fix all out of place words
8499 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8500 // the 16 different words that comprise the two doublequadword input vectors.
8501 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8502 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8504 for (int i = 0; i != 8; ++i) {
8505 int Elt0 = MaskVals[i*2];
8506 int Elt1 = MaskVals[i*2+1];
8508 // This word of the result is all undef, skip it.
8509 if (Elt0 < 0 && Elt1 < 0)
8512 // This word of the result is already in the correct place, skip it.
8513 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8516 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8517 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8520 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8521 // using a single extract together, load it and store it.
8522 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8523 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8524 DAG.getIntPtrConstant(Elt1 / 2));
8525 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8526 DAG.getIntPtrConstant(i));
8530 // If Elt1 is defined, extract it from the appropriate source. If the
8531 // source byte is not also odd, shift the extracted word left 8 bits
8532 // otherwise clear the bottom 8 bits if we need to do an or.
8534 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8535 DAG.getIntPtrConstant(Elt1 / 2));
8536 if ((Elt1 & 1) == 0)
8537 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8539 TLI.getShiftAmountTy(InsElt.getValueType())));
8541 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8542 DAG.getConstant(0xFF00, MVT::i16));
8544 // If Elt0 is defined, extract it from the appropriate source. If the
8545 // source byte is not also even, shift the extracted word right 8 bits. If
8546 // Elt1 was also defined, OR the extracted values together before
8547 // inserting them in the result.
8549 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8550 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8551 if ((Elt0 & 1) != 0)
8552 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8554 TLI.getShiftAmountTy(InsElt0.getValueType())));
8556 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8557 DAG.getConstant(0x00FF, MVT::i16));
8558 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8561 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8562 DAG.getIntPtrConstant(i));
8564 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8567 // v32i8 shuffles - Translate to VPSHUFB if possible.
8569 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8570 const X86Subtarget *Subtarget,
8571 SelectionDAG &DAG) {
8572 MVT VT = SVOp->getSimpleValueType(0);
8573 SDValue V1 = SVOp->getOperand(0);
8574 SDValue V2 = SVOp->getOperand(1);
8576 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8578 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8579 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8580 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8582 // VPSHUFB may be generated if
8583 // (1) one of input vector is undefined or zeroinitializer.
8584 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8585 // And (2) the mask indexes don't cross the 128-bit lane.
8586 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8587 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8590 if (V1IsAllZero && !V2IsAllZero) {
8591 CommuteVectorShuffleMask(MaskVals, 32);
8594 return getPSHUFB(MaskVals, V1, dl, DAG);
8597 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8598 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8599 /// done when every pair / quad of shuffle mask elements point to elements in
8600 /// the right sequence. e.g.
8601 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8603 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8604 SelectionDAG &DAG) {
8605 MVT VT = SVOp->getSimpleValueType(0);
8607 unsigned NumElems = VT.getVectorNumElements();
8610 switch (VT.SimpleTy) {
8611 default: llvm_unreachable("Unexpected!");
8614 return SDValue(SVOp, 0);
8615 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8616 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8617 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8618 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8619 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8620 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8623 SmallVector<int, 8> MaskVec;
8624 for (unsigned i = 0; i != NumElems; i += Scale) {
8626 for (unsigned j = 0; j != Scale; ++j) {
8627 int EltIdx = SVOp->getMaskElt(i+j);
8631 StartIdx = (EltIdx / Scale);
8632 if (EltIdx != (int)(StartIdx*Scale + j))
8635 MaskVec.push_back(StartIdx);
8638 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8639 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8640 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8643 /// getVZextMovL - Return a zero-extending vector move low node.
8645 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8646 SDValue SrcOp, SelectionDAG &DAG,
8647 const X86Subtarget *Subtarget, SDLoc dl) {
8648 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8649 LoadSDNode *LD = nullptr;
8650 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8651 LD = dyn_cast<LoadSDNode>(SrcOp);
8653 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8655 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8656 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8657 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8658 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8659 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8661 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8662 return DAG.getNode(ISD::BITCAST, dl, VT,
8663 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8664 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8672 return DAG.getNode(ISD::BITCAST, dl, VT,
8673 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8674 DAG.getNode(ISD::BITCAST, dl,
8678 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8679 /// which could not be matched by any known target speficic shuffle
8681 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8683 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8684 if (NewOp.getNode())
8687 MVT VT = SVOp->getSimpleValueType(0);
8689 unsigned NumElems = VT.getVectorNumElements();
8690 unsigned NumLaneElems = NumElems / 2;
8693 MVT EltVT = VT.getVectorElementType();
8694 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8697 SmallVector<int, 16> Mask;
8698 for (unsigned l = 0; l < 2; ++l) {
8699 // Build a shuffle mask for the output, discovering on the fly which
8700 // input vectors to use as shuffle operands (recorded in InputUsed).
8701 // If building a suitable shuffle vector proves too hard, then bail
8702 // out with UseBuildVector set.
8703 bool UseBuildVector = false;
8704 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8705 unsigned LaneStart = l * NumLaneElems;
8706 for (unsigned i = 0; i != NumLaneElems; ++i) {
8707 // The mask element. This indexes into the input.
8708 int Idx = SVOp->getMaskElt(i+LaneStart);
8710 // the mask element does not index into any input vector.
8715 // The input vector this mask element indexes into.
8716 int Input = Idx / NumLaneElems;
8718 // Turn the index into an offset from the start of the input vector.
8719 Idx -= Input * NumLaneElems;
8721 // Find or create a shuffle vector operand to hold this input.
8723 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8724 if (InputUsed[OpNo] == Input)
8725 // This input vector is already an operand.
8727 if (InputUsed[OpNo] < 0) {
8728 // Create a new operand for this input vector.
8729 InputUsed[OpNo] = Input;
8734 if (OpNo >= array_lengthof(InputUsed)) {
8735 // More than two input vectors used! Give up on trying to create a
8736 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8737 UseBuildVector = true;
8741 // Add the mask index for the new shuffle vector.
8742 Mask.push_back(Idx + OpNo * NumLaneElems);
8745 if (UseBuildVector) {
8746 SmallVector<SDValue, 16> SVOps;
8747 for (unsigned i = 0; i != NumLaneElems; ++i) {
8748 // The mask element. This indexes into the input.
8749 int Idx = SVOp->getMaskElt(i+LaneStart);
8751 SVOps.push_back(DAG.getUNDEF(EltVT));
8755 // The input vector this mask element indexes into.
8756 int Input = Idx / NumElems;
8758 // Turn the index into an offset from the start of the input vector.
8759 Idx -= Input * NumElems;
8761 // Extract the vector element by hand.
8762 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8763 SVOp->getOperand(Input),
8764 DAG.getIntPtrConstant(Idx)));
8767 // Construct the output using a BUILD_VECTOR.
8768 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8769 } else if (InputUsed[0] < 0) {
8770 // No input vectors were used! The result is undefined.
8771 Output[l] = DAG.getUNDEF(NVT);
8773 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8774 (InputUsed[0] % 2) * NumLaneElems,
8776 // If only one input was used, use an undefined vector for the other.
8777 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8778 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8779 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8780 // At least one input vector was used. Create a new shuffle vector.
8781 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8787 // Concatenate the result back
8788 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8791 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8792 /// 4 elements, and match them with several different shuffle types.
8794 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8795 SDValue V1 = SVOp->getOperand(0);
8796 SDValue V2 = SVOp->getOperand(1);
8798 MVT VT = SVOp->getSimpleValueType(0);
8800 assert(VT.is128BitVector() && "Unsupported vector size");
8802 std::pair<int, int> Locs[4];
8803 int Mask1[] = { -1, -1, -1, -1 };
8804 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8808 for (unsigned i = 0; i != 4; ++i) {
8809 int Idx = PermMask[i];
8811 Locs[i] = std::make_pair(-1, -1);
8813 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8815 Locs[i] = std::make_pair(0, NumLo);
8819 Locs[i] = std::make_pair(1, NumHi);
8821 Mask1[2+NumHi] = Idx;
8827 if (NumLo <= 2 && NumHi <= 2) {
8828 // If no more than two elements come from either vector. This can be
8829 // implemented with two shuffles. First shuffle gather the elements.
8830 // The second shuffle, which takes the first shuffle as both of its
8831 // vector operands, put the elements into the right order.
8832 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8834 int Mask2[] = { -1, -1, -1, -1 };
8836 for (unsigned i = 0; i != 4; ++i)
8837 if (Locs[i].first != -1) {
8838 unsigned Idx = (i < 2) ? 0 : 4;
8839 Idx += Locs[i].first * 2 + Locs[i].second;
8843 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8846 if (NumLo == 3 || NumHi == 3) {
8847 // Otherwise, we must have three elements from one vector, call it X, and
8848 // one element from the other, call it Y. First, use a shufps to build an
8849 // intermediate vector with the one element from Y and the element from X
8850 // that will be in the same half in the final destination (the indexes don't
8851 // matter). Then, use a shufps to build the final vector, taking the half
8852 // containing the element from Y from the intermediate, and the other half
8855 // Normalize it so the 3 elements come from V1.
8856 CommuteVectorShuffleMask(PermMask, 4);
8860 // Find the element from V2.
8862 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8863 int Val = PermMask[HiIndex];
8870 Mask1[0] = PermMask[HiIndex];
8872 Mask1[2] = PermMask[HiIndex^1];
8874 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8877 Mask1[0] = PermMask[0];
8878 Mask1[1] = PermMask[1];
8879 Mask1[2] = HiIndex & 1 ? 6 : 4;
8880 Mask1[3] = HiIndex & 1 ? 4 : 6;
8881 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8884 Mask1[0] = HiIndex & 1 ? 2 : 0;
8885 Mask1[1] = HiIndex & 1 ? 0 : 2;
8886 Mask1[2] = PermMask[2];
8887 Mask1[3] = PermMask[3];
8892 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8895 // Break it into (shuffle shuffle_hi, shuffle_lo).
8896 int LoMask[] = { -1, -1, -1, -1 };
8897 int HiMask[] = { -1, -1, -1, -1 };
8899 int *MaskPtr = LoMask;
8900 unsigned MaskIdx = 0;
8903 for (unsigned i = 0; i != 4; ++i) {
8910 int Idx = PermMask[i];
8912 Locs[i] = std::make_pair(-1, -1);
8913 } else if (Idx < 4) {
8914 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8915 MaskPtr[LoIdx] = Idx;
8918 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8919 MaskPtr[HiIdx] = Idx;
8924 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8925 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8926 int MaskOps[] = { -1, -1, -1, -1 };
8927 for (unsigned i = 0; i != 4; ++i)
8928 if (Locs[i].first != -1)
8929 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8930 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8933 static bool MayFoldVectorLoad(SDValue V) {
8934 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8935 V = V.getOperand(0);
8937 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8938 V = V.getOperand(0);
8939 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8940 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8941 // BUILD_VECTOR (load), undef
8942 V = V.getOperand(0);
8944 return MayFoldLoad(V);
8948 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8949 MVT VT = Op.getSimpleValueType();
8951 // Canonizalize to v2f64.
8952 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8953 return DAG.getNode(ISD::BITCAST, dl, VT,
8954 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8959 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8961 SDValue V1 = Op.getOperand(0);
8962 SDValue V2 = Op.getOperand(1);
8963 MVT VT = Op.getSimpleValueType();
8965 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8967 if (HasSSE2 && VT == MVT::v2f64)
8968 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8970 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8971 return DAG.getNode(ISD::BITCAST, dl, VT,
8972 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8973 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8974 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8978 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8979 SDValue V1 = Op.getOperand(0);
8980 SDValue V2 = Op.getOperand(1);
8981 MVT VT = Op.getSimpleValueType();
8983 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8984 "unsupported shuffle type");
8986 if (V2.getOpcode() == ISD::UNDEF)
8990 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8994 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8995 SDValue V1 = Op.getOperand(0);
8996 SDValue V2 = Op.getOperand(1);
8997 MVT VT = Op.getSimpleValueType();
8998 unsigned NumElems = VT.getVectorNumElements();
9000 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9001 // operand of these instructions is only memory, so check if there's a
9002 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9004 bool CanFoldLoad = false;
9006 // Trivial case, when V2 comes from a load.
9007 if (MayFoldVectorLoad(V2))
9010 // When V1 is a load, it can be folded later into a store in isel, example:
9011 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9013 // (MOVLPSmr addr:$src1, VR128:$src2)
9014 // So, recognize this potential and also use MOVLPS or MOVLPD
9015 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9018 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9020 if (HasSSE2 && NumElems == 2)
9021 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9024 // If we don't care about the second element, proceed to use movss.
9025 if (SVOp->getMaskElt(1) != -1)
9026 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9029 // movl and movlp will both match v2i64, but v2i64 is never matched by
9030 // movl earlier because we make it strict to avoid messing with the movlp load
9031 // folding logic (see the code above getMOVLP call). Match it here then,
9032 // this is horrible, but will stay like this until we move all shuffle
9033 // matching to x86 specific nodes. Note that for the 1st condition all
9034 // types are matched with movsd.
9036 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9037 // as to remove this logic from here, as much as possible
9038 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9039 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9040 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9043 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9045 // Invert the operand order and use SHUFPS to match it.
9046 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9047 getShuffleSHUFImmediate(SVOp), DAG);
9050 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9051 SelectionDAG &DAG) {
9053 MVT VT = Load->getSimpleValueType(0);
9054 MVT EVT = VT.getVectorElementType();
9055 SDValue Addr = Load->getOperand(1);
9056 SDValue NewAddr = DAG.getNode(
9057 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9058 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9061 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9062 DAG.getMachineFunction().getMachineMemOperand(
9063 Load->getMemOperand(), 0, EVT.getStoreSize()));
9067 // It is only safe to call this function if isINSERTPSMask is true for
9068 // this shufflevector mask.
9069 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9070 SelectionDAG &DAG) {
9071 // Generate an insertps instruction when inserting an f32 from memory onto a
9072 // v4f32 or when copying a member from one v4f32 to another.
9073 // We also use it for transferring i32 from one register to another,
9074 // since it simply copies the same bits.
9075 // If we're transferring an i32 from memory to a specific element in a
9076 // register, we output a generic DAG that will match the PINSRD
9078 MVT VT = SVOp->getSimpleValueType(0);
9079 MVT EVT = VT.getVectorElementType();
9080 SDValue V1 = SVOp->getOperand(0);
9081 SDValue V2 = SVOp->getOperand(1);
9082 auto Mask = SVOp->getMask();
9083 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9084 "unsupported vector type for insertps/pinsrd");
9086 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9087 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9088 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9096 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9099 // If we have 1 element from each vector, we have to check if we're
9100 // changing V1's element's place. If so, we're done. Otherwise, we
9101 // should assume we're changing V2's element's place and behave
9103 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9104 assert(DestIndex <= INT32_MAX && "truncated destination index");
9105 if (FromV1 == FromV2 &&
9106 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9110 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9113 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9114 "More than one element from V1 and from V2, or no elements from one "
9115 "of the vectors. This case should not have returned true from "
9120 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9123 // Get an index into the source vector in the range [0,4) (the mask is
9124 // in the range [0,8) because it can address V1 and V2)
9125 unsigned SrcIndex = Mask[DestIndex] % 4;
9126 if (MayFoldLoad(From)) {
9127 // Trivial case, when From comes from a load and is only used by the
9128 // shuffle. Make it use insertps from the vector that we need from that
9131 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9132 if (!NewLoad.getNode())
9135 if (EVT == MVT::f32) {
9136 // Create this as a scalar to vector to match the instruction pattern.
9137 SDValue LoadScalarToVector =
9138 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9139 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9140 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9142 } else { // EVT == MVT::i32
9143 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9144 // instruction, to match the PINSRD instruction, which loads an i32 to a
9145 // certain vector element.
9146 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9147 DAG.getConstant(DestIndex, MVT::i32));
9151 // Vector-element-to-vector
9152 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9153 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9156 // Reduce a vector shuffle to zext.
9157 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9158 SelectionDAG &DAG) {
9159 // PMOVZX is only available from SSE41.
9160 if (!Subtarget->hasSSE41())
9163 MVT VT = Op.getSimpleValueType();
9165 // Only AVX2 support 256-bit vector integer extending.
9166 if (!Subtarget->hasInt256() && VT.is256BitVector())
9169 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9171 SDValue V1 = Op.getOperand(0);
9172 SDValue V2 = Op.getOperand(1);
9173 unsigned NumElems = VT.getVectorNumElements();
9175 // Extending is an unary operation and the element type of the source vector
9176 // won't be equal to or larger than i64.
9177 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9178 VT.getVectorElementType() == MVT::i64)
9181 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9182 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9183 while ((1U << Shift) < NumElems) {
9184 if (SVOp->getMaskElt(1U << Shift) == 1)
9187 // The maximal ratio is 8, i.e. from i8 to i64.
9192 // Check the shuffle mask.
9193 unsigned Mask = (1U << Shift) - 1;
9194 for (unsigned i = 0; i != NumElems; ++i) {
9195 int EltIdx = SVOp->getMaskElt(i);
9196 if ((i & Mask) != 0 && EltIdx != -1)
9198 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9202 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9203 MVT NeVT = MVT::getIntegerVT(NBits);
9204 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9206 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9209 // Simplify the operand as it's prepared to be fed into shuffle.
9210 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9211 if (V1.getOpcode() == ISD::BITCAST &&
9212 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9213 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9214 V1.getOperand(0).getOperand(0)
9215 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9216 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9217 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9218 ConstantSDNode *CIdx =
9219 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9220 // If it's foldable, i.e. normal load with single use, we will let code
9221 // selection to fold it. Otherwise, we will short the conversion sequence.
9222 if (CIdx && CIdx->getZExtValue() == 0 &&
9223 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9224 MVT FullVT = V.getSimpleValueType();
9225 MVT V1VT = V1.getSimpleValueType();
9226 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9227 // The "ext_vec_elt" node is wider than the result node.
9228 // In this case we should extract subvector from V.
9229 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9230 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9231 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9232 FullVT.getVectorNumElements()/Ratio);
9233 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9234 DAG.getIntPtrConstant(0));
9236 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9240 return DAG.getNode(ISD::BITCAST, DL, VT,
9241 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9244 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9245 SelectionDAG &DAG) {
9246 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9247 MVT VT = Op.getSimpleValueType();
9249 SDValue V1 = Op.getOperand(0);
9250 SDValue V2 = Op.getOperand(1);
9252 if (isZeroShuffle(SVOp))
9253 return getZeroVector(VT, Subtarget, DAG, dl);
9255 // Handle splat operations
9256 if (SVOp->isSplat()) {
9257 // Use vbroadcast whenever the splat comes from a foldable load
9258 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9259 if (Broadcast.getNode())
9263 // Check integer expanding shuffles.
9264 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9265 if (NewOp.getNode())
9268 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9270 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9272 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9273 if (NewOp.getNode())
9274 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9275 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9276 // FIXME: Figure out a cleaner way to do this.
9277 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9278 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9279 if (NewOp.getNode()) {
9280 MVT NewVT = NewOp.getSimpleValueType();
9281 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9282 NewVT, true, false))
9283 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9286 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9287 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9288 if (NewOp.getNode()) {
9289 MVT NewVT = NewOp.getSimpleValueType();
9290 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9291 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9300 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9301 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9302 SDValue V1 = Op.getOperand(0);
9303 SDValue V2 = Op.getOperand(1);
9304 MVT VT = Op.getSimpleValueType();
9306 unsigned NumElems = VT.getVectorNumElements();
9307 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9308 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9309 bool V1IsSplat = false;
9310 bool V2IsSplat = false;
9311 bool HasSSE2 = Subtarget->hasSSE2();
9312 bool HasFp256 = Subtarget->hasFp256();
9313 bool HasInt256 = Subtarget->hasInt256();
9314 MachineFunction &MF = DAG.getMachineFunction();
9315 bool OptForSize = MF.getFunction()->getAttributes().
9316 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9318 // Check if we should use the experimental vector shuffle lowering. If so,
9319 // delegate completely to that code path.
9320 if (ExperimentalVectorShuffleLowering)
9321 return lowerVectorShuffle(Op, Subtarget, DAG);
9323 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9325 if (V1IsUndef && V2IsUndef)
9326 return DAG.getUNDEF(VT);
9328 // When we create a shuffle node we put the UNDEF node to second operand,
9329 // but in some cases the first operand may be transformed to UNDEF.
9330 // In this case we should just commute the node.
9332 return DAG.getCommutedVectorShuffle(*SVOp);
9334 // Vector shuffle lowering takes 3 steps:
9336 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9337 // narrowing and commutation of operands should be handled.
9338 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9340 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9341 // so the shuffle can be broken into other shuffles and the legalizer can
9342 // try the lowering again.
9344 // The general idea is that no vector_shuffle operation should be left to
9345 // be matched during isel, all of them must be converted to a target specific
9348 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9349 // narrowing and commutation of operands should be handled. The actual code
9350 // doesn't include all of those, work in progress...
9351 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9352 if (NewOp.getNode())
9355 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9357 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9358 // unpckh_undef). Only use pshufd if speed is more important than size.
9359 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9360 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9361 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9362 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9364 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9365 V2IsUndef && MayFoldVectorLoad(V1))
9366 return getMOVDDup(Op, dl, V1, DAG);
9368 if (isMOVHLPS_v_undef_Mask(M, VT))
9369 return getMOVHighToLow(Op, dl, DAG);
9371 // Use to match splats
9372 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9373 (VT == MVT::v2f64 || VT == MVT::v2i64))
9374 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9376 if (isPSHUFDMask(M, VT)) {
9377 // The actual implementation will match the mask in the if above and then
9378 // during isel it can match several different instructions, not only pshufd
9379 // as its name says, sad but true, emulate the behavior for now...
9380 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9381 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9383 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9385 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9386 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9388 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9389 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9392 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9396 if (isPALIGNRMask(M, VT, Subtarget))
9397 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9398 getShufflePALIGNRImmediate(SVOp),
9401 // Check if this can be converted into a logical shift.
9402 bool isLeft = false;
9405 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9406 if (isShift && ShVal.hasOneUse()) {
9407 // If the shifted value has multiple uses, it may be cheaper to use
9408 // v_set0 + movlhps or movhlps, etc.
9409 MVT EltVT = VT.getVectorElementType();
9410 ShAmt *= EltVT.getSizeInBits();
9411 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9414 if (isMOVLMask(M, VT)) {
9415 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9416 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9417 if (!isMOVLPMask(M, VT)) {
9418 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9419 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9421 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9422 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9426 // FIXME: fold these into legal mask.
9427 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9428 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9430 if (isMOVHLPSMask(M, VT))
9431 return getMOVHighToLow(Op, dl, DAG);
9433 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9434 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9436 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9437 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9439 if (isMOVLPMask(M, VT))
9440 return getMOVLP(Op, dl, DAG, HasSSE2);
9442 if (ShouldXformToMOVHLPS(M, VT) ||
9443 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9444 return DAG.getCommutedVectorShuffle(*SVOp);
9447 // No better options. Use a vshldq / vsrldq.
9448 MVT EltVT = VT.getVectorElementType();
9449 ShAmt *= EltVT.getSizeInBits();
9450 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9453 bool Commuted = false;
9454 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9455 // 1,1,1,1 -> v8i16 though.
9456 BitVector UndefElements;
9457 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9458 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9460 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9461 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9464 // Canonicalize the splat or undef, if present, to be on the RHS.
9465 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9466 CommuteVectorShuffleMask(M, NumElems);
9468 std::swap(V1IsSplat, V2IsSplat);
9472 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9473 // Shuffling low element of v1 into undef, just return v1.
9476 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9477 // the instruction selector will not match, so get a canonical MOVL with
9478 // swapped operands to undo the commute.
9479 return getMOVL(DAG, dl, VT, V2, V1);
9482 if (isUNPCKLMask(M, VT, HasInt256))
9483 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9485 if (isUNPCKHMask(M, VT, HasInt256))
9486 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9489 // Normalize mask so all entries that point to V2 points to its first
9490 // element then try to match unpck{h|l} again. If match, return a
9491 // new vector_shuffle with the corrected mask.p
9492 SmallVector<int, 8> NewMask(M.begin(), M.end());
9493 NormalizeMask(NewMask, NumElems);
9494 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9495 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9496 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9497 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9501 // Commute is back and try unpck* again.
9502 // FIXME: this seems wrong.
9503 CommuteVectorShuffleMask(M, NumElems);
9505 std::swap(V1IsSplat, V2IsSplat);
9507 if (isUNPCKLMask(M, VT, HasInt256))
9508 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9510 if (isUNPCKHMask(M, VT, HasInt256))
9511 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9514 // Normalize the node to match x86 shuffle ops if needed
9515 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9516 return DAG.getCommutedVectorShuffle(*SVOp);
9518 // The checks below are all present in isShuffleMaskLegal, but they are
9519 // inlined here right now to enable us to directly emit target specific
9520 // nodes, and remove one by one until they don't return Op anymore.
9522 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9523 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9524 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9525 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9528 if (isPSHUFHWMask(M, VT, HasInt256))
9529 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9530 getShufflePSHUFHWImmediate(SVOp),
9533 if (isPSHUFLWMask(M, VT, HasInt256))
9534 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9535 getShufflePSHUFLWImmediate(SVOp),
9539 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9541 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9543 if (isSHUFPMask(M, VT))
9544 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9545 getShuffleSHUFImmediate(SVOp), DAG);
9547 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9548 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9549 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9550 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9552 //===--------------------------------------------------------------------===//
9553 // Generate target specific nodes for 128 or 256-bit shuffles only
9554 // supported in the AVX instruction set.
9557 // Handle VMOVDDUPY permutations
9558 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9559 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9561 // Handle VPERMILPS/D* permutations
9562 if (isVPERMILPMask(M, VT)) {
9563 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9564 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9565 getShuffleSHUFImmediate(SVOp), DAG);
9566 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9567 getShuffleSHUFImmediate(SVOp), DAG);
9571 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9572 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9573 Idx*(NumElems/2), DAG, dl);
9575 // Handle VPERM2F128/VPERM2I128 permutations
9576 if (isVPERM2X128Mask(M, VT, HasFp256))
9577 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9578 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9580 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9581 return getINSERTPS(SVOp, dl, DAG);
9584 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9585 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9587 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9588 VT.is512BitVector()) {
9589 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9590 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9591 SmallVector<SDValue, 16> permclMask;
9592 for (unsigned i = 0; i != NumElems; ++i) {
9593 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9596 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9598 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9599 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9600 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9601 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9602 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9605 //===--------------------------------------------------------------------===//
9606 // Since no target specific shuffle was selected for this generic one,
9607 // lower it into other known shuffles. FIXME: this isn't true yet, but
9608 // this is the plan.
9611 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9612 if (VT == MVT::v8i16) {
9613 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9614 if (NewOp.getNode())
9618 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9619 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9620 if (NewOp.getNode())
9624 if (VT == MVT::v16i8) {
9625 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9626 if (NewOp.getNode())
9630 if (VT == MVT::v32i8) {
9631 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9632 if (NewOp.getNode())
9636 // Handle all 128-bit wide vectors with 4 elements, and match them with
9637 // several different shuffle types.
9638 if (NumElems == 4 && VT.is128BitVector())
9639 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9641 // Handle general 256-bit shuffles
9642 if (VT.is256BitVector())
9643 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9648 // This function assumes its argument is a BUILD_VECTOR of constants or
9649 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9651 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9652 unsigned &MaskValue) {
9654 unsigned NumElems = BuildVector->getNumOperands();
9655 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9656 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9657 unsigned NumElemsInLane = NumElems / NumLanes;
9659 // Blend for v16i16 should be symetric for the both lanes.
9660 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9661 SDValue EltCond = BuildVector->getOperand(i);
9662 SDValue SndLaneEltCond =
9663 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9665 int Lane1Cond = -1, Lane2Cond = -1;
9666 if (isa<ConstantSDNode>(EltCond))
9667 Lane1Cond = !isZero(EltCond);
9668 if (isa<ConstantSDNode>(SndLaneEltCond))
9669 Lane2Cond = !isZero(SndLaneEltCond);
9671 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9672 // Lane1Cond != 0, means we want the first argument.
9673 // Lane1Cond == 0, means we want the second argument.
9674 // The encoding of this argument is 0 for the first argument, 1
9675 // for the second. Therefore, invert the condition.
9676 MaskValue |= !Lane1Cond << i;
9677 else if (Lane1Cond < 0)
9678 MaskValue |= !Lane2Cond << i;
9685 // Try to lower a vselect node into a simple blend instruction.
9686 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9687 SelectionDAG &DAG) {
9688 SDValue Cond = Op.getOperand(0);
9689 SDValue LHS = Op.getOperand(1);
9690 SDValue RHS = Op.getOperand(2);
9692 MVT VT = Op.getSimpleValueType();
9693 MVT EltVT = VT.getVectorElementType();
9694 unsigned NumElems = VT.getVectorNumElements();
9696 // There is no blend with immediate in AVX-512.
9697 if (VT.is512BitVector())
9700 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9702 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9705 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9708 // Check the mask for BLEND and build the value.
9709 unsigned MaskValue = 0;
9710 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9713 // Convert i32 vectors to floating point if it is not AVX2.
9714 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9716 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9717 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9719 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9720 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9723 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9724 DAG.getConstant(MaskValue, MVT::i32));
9725 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9728 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9729 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9730 if (BlendOp.getNode())
9733 // Some types for vselect were previously set to Expand, not Legal or
9734 // Custom. Return an empty SDValue so we fall-through to Expand, after
9735 // the Custom lowering phase.
9736 MVT VT = Op.getSimpleValueType();
9737 switch (VT.SimpleTy) {
9745 // We couldn't create a "Blend with immediate" node.
9746 // This node should still be legal, but we'll have to emit a blendv*
9751 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9752 MVT VT = Op.getSimpleValueType();
9755 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9758 if (VT.getSizeInBits() == 8) {
9759 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9760 Op.getOperand(0), Op.getOperand(1));
9761 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9762 DAG.getValueType(VT));
9763 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9766 if (VT.getSizeInBits() == 16) {
9767 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9768 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9770 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9771 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9772 DAG.getNode(ISD::BITCAST, dl,
9776 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9777 Op.getOperand(0), Op.getOperand(1));
9778 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9779 DAG.getValueType(VT));
9780 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9783 if (VT == MVT::f32) {
9784 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9785 // the result back to FR32 register. It's only worth matching if the
9786 // result has a single use which is a store or a bitcast to i32. And in
9787 // the case of a store, it's not worth it if the index is a constant 0,
9788 // because a MOVSSmr can be used instead, which is smaller and faster.
9789 if (!Op.hasOneUse())
9791 SDNode *User = *Op.getNode()->use_begin();
9792 if ((User->getOpcode() != ISD::STORE ||
9793 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9794 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9795 (User->getOpcode() != ISD::BITCAST ||
9796 User->getValueType(0) != MVT::i32))
9798 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9799 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9802 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9805 if (VT == MVT::i32 || VT == MVT::i64) {
9806 // ExtractPS/pextrq works with constant index.
9807 if (isa<ConstantSDNode>(Op.getOperand(1)))
9813 /// Extract one bit from mask vector, like v16i1 or v8i1.
9814 /// AVX-512 feature.
9816 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9817 SDValue Vec = Op.getOperand(0);
9819 MVT VecVT = Vec.getSimpleValueType();
9820 SDValue Idx = Op.getOperand(1);
9821 MVT EltVT = Op.getSimpleValueType();
9823 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9825 // variable index can't be handled in mask registers,
9826 // extend vector to VR512
9827 if (!isa<ConstantSDNode>(Idx)) {
9828 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9829 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9830 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9831 ExtVT.getVectorElementType(), Ext, Idx);
9832 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9835 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9836 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9837 unsigned MaxSift = rc->getSize()*8 - 1;
9838 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9839 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9840 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9841 DAG.getConstant(MaxSift, MVT::i8));
9842 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9843 DAG.getIntPtrConstant(0));
9847 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9848 SelectionDAG &DAG) const {
9850 SDValue Vec = Op.getOperand(0);
9851 MVT VecVT = Vec.getSimpleValueType();
9852 SDValue Idx = Op.getOperand(1);
9854 if (Op.getSimpleValueType() == MVT::i1)
9855 return ExtractBitFromMaskVector(Op, DAG);
9857 if (!isa<ConstantSDNode>(Idx)) {
9858 if (VecVT.is512BitVector() ||
9859 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9860 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9863 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9864 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9865 MaskEltVT.getSizeInBits());
9867 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9868 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9869 getZeroVector(MaskVT, Subtarget, DAG, dl),
9870 Idx, DAG.getConstant(0, getPointerTy()));
9871 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9872 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9873 Perm, DAG.getConstant(0, getPointerTy()));
9878 // If this is a 256-bit vector result, first extract the 128-bit vector and
9879 // then extract the element from the 128-bit vector.
9880 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9882 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9883 // Get the 128-bit vector.
9884 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9885 MVT EltVT = VecVT.getVectorElementType();
9887 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9889 //if (IdxVal >= NumElems/2)
9890 // IdxVal -= NumElems/2;
9891 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9892 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9893 DAG.getConstant(IdxVal, MVT::i32));
9896 assert(VecVT.is128BitVector() && "Unexpected vector length");
9898 if (Subtarget->hasSSE41()) {
9899 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9904 MVT VT = Op.getSimpleValueType();
9905 // TODO: handle v16i8.
9906 if (VT.getSizeInBits() == 16) {
9907 SDValue Vec = Op.getOperand(0);
9908 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9910 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9911 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9912 DAG.getNode(ISD::BITCAST, dl,
9915 // Transform it so it match pextrw which produces a 32-bit result.
9916 MVT EltVT = MVT::i32;
9917 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9918 Op.getOperand(0), Op.getOperand(1));
9919 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9920 DAG.getValueType(VT));
9921 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9924 if (VT.getSizeInBits() == 32) {
9925 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9929 // SHUFPS the element to the lowest double word, then movss.
9930 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9931 MVT VVT = Op.getOperand(0).getSimpleValueType();
9932 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9933 DAG.getUNDEF(VVT), Mask);
9934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9935 DAG.getIntPtrConstant(0));
9938 if (VT.getSizeInBits() == 64) {
9939 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9940 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9941 // to match extract_elt for f64.
9942 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9946 // UNPCKHPD the element to the lowest double word, then movsd.
9947 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9948 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9949 int Mask[2] = { 1, -1 };
9950 MVT VVT = Op.getOperand(0).getSimpleValueType();
9951 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9952 DAG.getUNDEF(VVT), Mask);
9953 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9954 DAG.getIntPtrConstant(0));
9960 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9961 MVT VT = Op.getSimpleValueType();
9962 MVT EltVT = VT.getVectorElementType();
9965 SDValue N0 = Op.getOperand(0);
9966 SDValue N1 = Op.getOperand(1);
9967 SDValue N2 = Op.getOperand(2);
9969 if (!VT.is128BitVector())
9972 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9973 isa<ConstantSDNode>(N2)) {
9975 if (VT == MVT::v8i16)
9976 Opc = X86ISD::PINSRW;
9977 else if (VT == MVT::v16i8)
9978 Opc = X86ISD::PINSRB;
9980 Opc = X86ISD::PINSRB;
9982 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9984 if (N1.getValueType() != MVT::i32)
9985 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9986 if (N2.getValueType() != MVT::i32)
9987 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9988 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9991 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9992 // Bits [7:6] of the constant are the source select. This will always be
9993 // zero here. The DAG Combiner may combine an extract_elt index into these
9994 // bits. For example (insert (extract, 3), 2) could be matched by putting
9995 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9996 // Bits [5:4] of the constant are the destination select. This is the
9997 // value of the incoming immediate.
9998 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9999 // combine either bitwise AND or insert of float 0.0 to set these bits.
10000 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10001 // Create this as a scalar to vector..
10002 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10003 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10006 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10007 // PINSR* works with constant index.
10013 /// Insert one bit to mask vector, like v16i1 or v8i1.
10014 /// AVX-512 feature.
10016 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10018 SDValue Vec = Op.getOperand(0);
10019 SDValue Elt = Op.getOperand(1);
10020 SDValue Idx = Op.getOperand(2);
10021 MVT VecVT = Vec.getSimpleValueType();
10023 if (!isa<ConstantSDNode>(Idx)) {
10024 // Non constant index. Extend source and destination,
10025 // insert element and then truncate the result.
10026 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10027 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10028 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10029 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10030 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10031 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10034 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10035 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10036 if (Vec.getOpcode() == ISD::UNDEF)
10037 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10038 DAG.getConstant(IdxVal, MVT::i8));
10039 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10040 unsigned MaxSift = rc->getSize()*8 - 1;
10041 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10042 DAG.getConstant(MaxSift, MVT::i8));
10043 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10044 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10045 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10048 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10049 MVT VT = Op.getSimpleValueType();
10050 MVT EltVT = VT.getVectorElementType();
10052 if (EltVT == MVT::i1)
10053 return InsertBitToMaskVector(Op, DAG);
10056 SDValue N0 = Op.getOperand(0);
10057 SDValue N1 = Op.getOperand(1);
10058 SDValue N2 = Op.getOperand(2);
10060 // If this is a 256-bit vector result, first extract the 128-bit vector,
10061 // insert the element into the extracted half and then place it back.
10062 if (VT.is256BitVector() || VT.is512BitVector()) {
10063 if (!isa<ConstantSDNode>(N2))
10066 // Get the desired 128-bit vector half.
10067 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10068 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10070 // Insert the element into the desired half.
10071 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10072 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10074 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10075 DAG.getConstant(IdxIn128, MVT::i32));
10077 // Insert the changed part back to the 256-bit vector
10078 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10081 if (Subtarget->hasSSE41())
10082 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10084 if (EltVT == MVT::i8)
10087 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10088 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10089 // as its second argument.
10090 if (N1.getValueType() != MVT::i32)
10091 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10092 if (N2.getValueType() != MVT::i32)
10093 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10094 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10099 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10101 MVT OpVT = Op.getSimpleValueType();
10103 // If this is a 256-bit vector result, first insert into a 128-bit
10104 // vector and then insert into the 256-bit vector.
10105 if (!OpVT.is128BitVector()) {
10106 // Insert into a 128-bit vector.
10107 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10108 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10109 OpVT.getVectorNumElements() / SizeFactor);
10111 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10113 // Insert the 128-bit vector.
10114 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10117 if (OpVT == MVT::v1i64 &&
10118 Op.getOperand(0).getValueType() == MVT::i64)
10119 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10121 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10122 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10123 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10124 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10127 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10128 // a simple subregister reference or explicit instructions to grab
10129 // upper bits of a vector.
10130 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10131 SelectionDAG &DAG) {
10133 SDValue In = Op.getOperand(0);
10134 SDValue Idx = Op.getOperand(1);
10135 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10136 MVT ResVT = Op.getSimpleValueType();
10137 MVT InVT = In.getSimpleValueType();
10139 if (Subtarget->hasFp256()) {
10140 if (ResVT.is128BitVector() &&
10141 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10142 isa<ConstantSDNode>(Idx)) {
10143 return Extract128BitVector(In, IdxVal, DAG, dl);
10145 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10146 isa<ConstantSDNode>(Idx)) {
10147 return Extract256BitVector(In, IdxVal, DAG, dl);
10153 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10154 // simple superregister reference or explicit instructions to insert
10155 // the upper bits of a vector.
10156 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10157 SelectionDAG &DAG) {
10158 if (Subtarget->hasFp256()) {
10159 SDLoc dl(Op.getNode());
10160 SDValue Vec = Op.getNode()->getOperand(0);
10161 SDValue SubVec = Op.getNode()->getOperand(1);
10162 SDValue Idx = Op.getNode()->getOperand(2);
10164 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10165 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10166 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10167 isa<ConstantSDNode>(Idx)) {
10168 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10169 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10172 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10173 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10174 isa<ConstantSDNode>(Idx)) {
10175 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10176 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10182 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10183 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10184 // one of the above mentioned nodes. It has to be wrapped because otherwise
10185 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10186 // be used to form addressing mode. These wrapped nodes will be selected
10189 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10190 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10192 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10193 // global base reg.
10194 unsigned char OpFlag = 0;
10195 unsigned WrapperKind = X86ISD::Wrapper;
10196 CodeModel::Model M = DAG.getTarget().getCodeModel();
10198 if (Subtarget->isPICStyleRIPRel() &&
10199 (M == CodeModel::Small || M == CodeModel::Kernel))
10200 WrapperKind = X86ISD::WrapperRIP;
10201 else if (Subtarget->isPICStyleGOT())
10202 OpFlag = X86II::MO_GOTOFF;
10203 else if (Subtarget->isPICStyleStubPIC())
10204 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10206 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10207 CP->getAlignment(),
10208 CP->getOffset(), OpFlag);
10210 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10211 // With PIC, the address is actually $g + Offset.
10213 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10214 DAG.getNode(X86ISD::GlobalBaseReg,
10215 SDLoc(), getPointerTy()),
10222 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10223 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10225 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10226 // global base reg.
10227 unsigned char OpFlag = 0;
10228 unsigned WrapperKind = X86ISD::Wrapper;
10229 CodeModel::Model M = DAG.getTarget().getCodeModel();
10231 if (Subtarget->isPICStyleRIPRel() &&
10232 (M == CodeModel::Small || M == CodeModel::Kernel))
10233 WrapperKind = X86ISD::WrapperRIP;
10234 else if (Subtarget->isPICStyleGOT())
10235 OpFlag = X86II::MO_GOTOFF;
10236 else if (Subtarget->isPICStyleStubPIC())
10237 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10239 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10242 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10244 // With PIC, the address is actually $g + Offset.
10246 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10247 DAG.getNode(X86ISD::GlobalBaseReg,
10248 SDLoc(), getPointerTy()),
10255 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10256 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10258 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10259 // global base reg.
10260 unsigned char OpFlag = 0;
10261 unsigned WrapperKind = X86ISD::Wrapper;
10262 CodeModel::Model M = DAG.getTarget().getCodeModel();
10264 if (Subtarget->isPICStyleRIPRel() &&
10265 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10266 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10267 OpFlag = X86II::MO_GOTPCREL;
10268 WrapperKind = X86ISD::WrapperRIP;
10269 } else if (Subtarget->isPICStyleGOT()) {
10270 OpFlag = X86II::MO_GOT;
10271 } else if (Subtarget->isPICStyleStubPIC()) {
10272 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10273 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10274 OpFlag = X86II::MO_DARWIN_NONLAZY;
10277 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10280 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10282 // With PIC, the address is actually $g + Offset.
10283 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10284 !Subtarget->is64Bit()) {
10285 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10286 DAG.getNode(X86ISD::GlobalBaseReg,
10287 SDLoc(), getPointerTy()),
10291 // For symbols that require a load from a stub to get the address, emit the
10293 if (isGlobalStubReference(OpFlag))
10294 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10295 MachinePointerInfo::getGOT(), false, false, false, 0);
10301 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10302 // Create the TargetBlockAddressAddress node.
10303 unsigned char OpFlags =
10304 Subtarget->ClassifyBlockAddressReference();
10305 CodeModel::Model M = DAG.getTarget().getCodeModel();
10306 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10307 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10309 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10312 if (Subtarget->isPICStyleRIPRel() &&
10313 (M == CodeModel::Small || M == CodeModel::Kernel))
10314 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10316 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10318 // With PIC, the address is actually $g + Offset.
10319 if (isGlobalRelativeToPICBase(OpFlags)) {
10320 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10321 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10329 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10330 int64_t Offset, SelectionDAG &DAG) const {
10331 // Create the TargetGlobalAddress node, folding in the constant
10332 // offset if it is legal.
10333 unsigned char OpFlags =
10334 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10335 CodeModel::Model M = DAG.getTarget().getCodeModel();
10337 if (OpFlags == X86II::MO_NO_FLAG &&
10338 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10339 // A direct static reference to a global.
10340 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10343 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10346 if (Subtarget->isPICStyleRIPRel() &&
10347 (M == CodeModel::Small || M == CodeModel::Kernel))
10348 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10350 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10352 // With PIC, the address is actually $g + Offset.
10353 if (isGlobalRelativeToPICBase(OpFlags)) {
10354 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10355 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10359 // For globals that require a load from a stub to get the address, emit the
10361 if (isGlobalStubReference(OpFlags))
10362 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10363 MachinePointerInfo::getGOT(), false, false, false, 0);
10365 // If there was a non-zero offset that we didn't fold, create an explicit
10366 // addition for it.
10368 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10369 DAG.getConstant(Offset, getPointerTy()));
10375 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10376 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10377 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10378 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10382 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10383 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10384 unsigned char OperandFlags, bool LocalDynamic = false) {
10385 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10386 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10388 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10389 GA->getValueType(0),
10393 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10397 SDValue Ops[] = { Chain, TGA, *InFlag };
10398 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10400 SDValue Ops[] = { Chain, TGA };
10401 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10404 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10405 MFI->setAdjustsStack(true);
10407 SDValue Flag = Chain.getValue(1);
10408 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10411 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10413 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10416 SDLoc dl(GA); // ? function entry point might be better
10417 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10418 DAG.getNode(X86ISD::GlobalBaseReg,
10419 SDLoc(), PtrVT), InFlag);
10420 InFlag = Chain.getValue(1);
10422 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10427 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10429 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10430 X86::RAX, X86II::MO_TLSGD);
10433 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10439 // Get the start address of the TLS block for this module.
10440 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10441 .getInfo<X86MachineFunctionInfo>();
10442 MFI->incNumLocalDynamicTLSAccesses();
10446 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10447 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10450 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10451 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10452 InFlag = Chain.getValue(1);
10453 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10454 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10457 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10461 unsigned char OperandFlags = X86II::MO_DTPOFF;
10462 unsigned WrapperKind = X86ISD::Wrapper;
10463 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10464 GA->getValueType(0),
10465 GA->getOffset(), OperandFlags);
10466 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10468 // Add x@dtpoff with the base.
10469 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10472 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10473 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10474 const EVT PtrVT, TLSModel::Model model,
10475 bool is64Bit, bool isPIC) {
10478 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10479 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10480 is64Bit ? 257 : 256));
10482 SDValue ThreadPointer =
10483 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10484 MachinePointerInfo(Ptr), false, false, false, 0);
10486 unsigned char OperandFlags = 0;
10487 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10489 unsigned WrapperKind = X86ISD::Wrapper;
10490 if (model == TLSModel::LocalExec) {
10491 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10492 } else if (model == TLSModel::InitialExec) {
10494 OperandFlags = X86II::MO_GOTTPOFF;
10495 WrapperKind = X86ISD::WrapperRIP;
10497 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10500 llvm_unreachable("Unexpected model");
10503 // emit "addl x@ntpoff,%eax" (local exec)
10504 // or "addl x@indntpoff,%eax" (initial exec)
10505 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10507 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10508 GA->getOffset(), OperandFlags);
10509 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10511 if (model == TLSModel::InitialExec) {
10512 if (isPIC && !is64Bit) {
10513 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10514 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10518 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10519 MachinePointerInfo::getGOT(), false, false, false, 0);
10522 // The address of the thread local variable is the add of the thread
10523 // pointer with the offset of the variable.
10524 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10528 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10530 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10531 const GlobalValue *GV = GA->getGlobal();
10533 if (Subtarget->isTargetELF()) {
10534 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10537 case TLSModel::GeneralDynamic:
10538 if (Subtarget->is64Bit())
10539 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10540 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10541 case TLSModel::LocalDynamic:
10542 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10543 Subtarget->is64Bit());
10544 case TLSModel::InitialExec:
10545 case TLSModel::LocalExec:
10546 return LowerToTLSExecModel(
10547 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10548 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10550 llvm_unreachable("Unknown TLS model.");
10553 if (Subtarget->isTargetDarwin()) {
10554 // Darwin only has one model of TLS. Lower to that.
10555 unsigned char OpFlag = 0;
10556 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10557 X86ISD::WrapperRIP : X86ISD::Wrapper;
10559 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10560 // global base reg.
10561 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10562 !Subtarget->is64Bit();
10564 OpFlag = X86II::MO_TLVP_PIC_BASE;
10566 OpFlag = X86II::MO_TLVP;
10568 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10569 GA->getValueType(0),
10570 GA->getOffset(), OpFlag);
10571 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10573 // With PIC32, the address is actually $g + Offset.
10575 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10576 DAG.getNode(X86ISD::GlobalBaseReg,
10577 SDLoc(), getPointerTy()),
10580 // Lowering the machine isd will make sure everything is in the right
10582 SDValue Chain = DAG.getEntryNode();
10583 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10584 SDValue Args[] = { Chain, Offset };
10585 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10587 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10588 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10589 MFI->setAdjustsStack(true);
10591 // And our return value (tls address) is in the standard call return value
10593 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10594 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10595 Chain.getValue(1));
10598 if (Subtarget->isTargetKnownWindowsMSVC() ||
10599 Subtarget->isTargetWindowsGNU()) {
10600 // Just use the implicit TLS architecture
10601 // Need to generate someting similar to:
10602 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10604 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10605 // mov rcx, qword [rdx+rcx*8]
10606 // mov eax, .tls$:tlsvar
10607 // [rax+rcx] contains the address
10608 // Windows 64bit: gs:0x58
10609 // Windows 32bit: fs:__tls_array
10612 SDValue Chain = DAG.getEntryNode();
10614 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10615 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10616 // use its literal value of 0x2C.
10617 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10618 ? Type::getInt8PtrTy(*DAG.getContext(),
10620 : Type::getInt32PtrTy(*DAG.getContext(),
10624 Subtarget->is64Bit()
10625 ? DAG.getIntPtrConstant(0x58)
10626 : (Subtarget->isTargetWindowsGNU()
10627 ? DAG.getIntPtrConstant(0x2C)
10628 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10630 SDValue ThreadPointer =
10631 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10632 MachinePointerInfo(Ptr), false, false, false, 0);
10634 // Load the _tls_index variable
10635 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10636 if (Subtarget->is64Bit())
10637 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10638 IDX, MachinePointerInfo(), MVT::i32,
10641 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10642 false, false, false, 0);
10644 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10646 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10648 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10649 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10650 false, false, false, 0);
10652 // Get the offset of start of .tls section
10653 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10654 GA->getValueType(0),
10655 GA->getOffset(), X86II::MO_SECREL);
10656 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10658 // The address of the thread local variable is the add of the thread
10659 // pointer with the offset of the variable.
10660 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10663 llvm_unreachable("TLS not implemented for this target.");
10666 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10667 /// and take a 2 x i32 value to shift plus a shift amount.
10668 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10669 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10670 MVT VT = Op.getSimpleValueType();
10671 unsigned VTBits = VT.getSizeInBits();
10673 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10674 SDValue ShOpLo = Op.getOperand(0);
10675 SDValue ShOpHi = Op.getOperand(1);
10676 SDValue ShAmt = Op.getOperand(2);
10677 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10678 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10680 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10681 DAG.getConstant(VTBits - 1, MVT::i8));
10682 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10683 DAG.getConstant(VTBits - 1, MVT::i8))
10684 : DAG.getConstant(0, VT);
10686 SDValue Tmp2, Tmp3;
10687 if (Op.getOpcode() == ISD::SHL_PARTS) {
10688 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10689 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10691 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10692 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10695 // If the shift amount is larger or equal than the width of a part we can't
10696 // rely on the results of shld/shrd. Insert a test and select the appropriate
10697 // values for large shift amounts.
10698 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10699 DAG.getConstant(VTBits, MVT::i8));
10700 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10701 AndNode, DAG.getConstant(0, MVT::i8));
10704 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10705 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10706 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10708 if (Op.getOpcode() == ISD::SHL_PARTS) {
10709 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10710 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10712 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10713 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10716 SDValue Ops[2] = { Lo, Hi };
10717 return DAG.getMergeValues(Ops, dl);
10720 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10721 SelectionDAG &DAG) const {
10722 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10724 if (SrcVT.isVector())
10727 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10728 "Unknown SINT_TO_FP to lower!");
10730 // These are really Legal; return the operand so the caller accepts it as
10732 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10734 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10735 Subtarget->is64Bit()) {
10740 unsigned Size = SrcVT.getSizeInBits()/8;
10741 MachineFunction &MF = DAG.getMachineFunction();
10742 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10743 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10744 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10746 MachinePointerInfo::getFixedStack(SSFI),
10748 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10751 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10753 SelectionDAG &DAG) const {
10757 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10759 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10761 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10763 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10765 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10766 MachineMemOperand *MMO;
10768 int SSFI = FI->getIndex();
10770 DAG.getMachineFunction()
10771 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10772 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10774 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10775 StackSlot = StackSlot.getOperand(1);
10777 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10778 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10780 Tys, Ops, SrcVT, MMO);
10783 Chain = Result.getValue(1);
10784 SDValue InFlag = Result.getValue(2);
10786 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10787 // shouldn't be necessary except that RFP cannot be live across
10788 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10789 MachineFunction &MF = DAG.getMachineFunction();
10790 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10791 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10792 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10793 Tys = DAG.getVTList(MVT::Other);
10795 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10797 MachineMemOperand *MMO =
10798 DAG.getMachineFunction()
10799 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10800 MachineMemOperand::MOStore, SSFISize, SSFISize);
10802 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10803 Ops, Op.getValueType(), MMO);
10804 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10805 MachinePointerInfo::getFixedStack(SSFI),
10806 false, false, false, 0);
10812 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10813 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10814 SelectionDAG &DAG) const {
10815 // This algorithm is not obvious. Here it is what we're trying to output:
10818 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10819 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10821 haddpd %xmm0, %xmm0
10823 pshufd $0x4e, %xmm0, %xmm1
10829 LLVMContext *Context = DAG.getContext();
10831 // Build some magic constants.
10832 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10833 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10834 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10836 SmallVector<Constant*,2> CV1;
10838 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10839 APInt(64, 0x4330000000000000ULL))));
10841 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10842 APInt(64, 0x4530000000000000ULL))));
10843 Constant *C1 = ConstantVector::get(CV1);
10844 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10846 // Load the 64-bit value into an XMM register.
10847 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10849 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10850 MachinePointerInfo::getConstantPool(),
10851 false, false, false, 16);
10852 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10853 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10856 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10857 MachinePointerInfo::getConstantPool(),
10858 false, false, false, 16);
10859 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10860 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10863 if (Subtarget->hasSSE3()) {
10864 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10865 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10867 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10868 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10870 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10871 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10875 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10876 DAG.getIntPtrConstant(0));
10879 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10880 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10881 SelectionDAG &DAG) const {
10883 // FP constant to bias correct the final result.
10884 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10887 // Load the 32-bit value into an XMM register.
10888 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10891 // Zero out the upper parts of the register.
10892 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10894 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10895 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10896 DAG.getIntPtrConstant(0));
10898 // Or the load with the bias.
10899 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10900 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10901 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10902 MVT::v2f64, Load)),
10903 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10904 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10905 MVT::v2f64, Bias)));
10906 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10907 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10908 DAG.getIntPtrConstant(0));
10910 // Subtract the bias.
10911 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10913 // Handle final rounding.
10914 EVT DestVT = Op.getValueType();
10916 if (DestVT.bitsLT(MVT::f64))
10917 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10918 DAG.getIntPtrConstant(0));
10919 if (DestVT.bitsGT(MVT::f64))
10920 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10922 // Handle final rounding.
10926 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10927 SelectionDAG &DAG) const {
10928 SDValue N0 = Op.getOperand(0);
10929 MVT SVT = N0.getSimpleValueType();
10932 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10933 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10934 "Custom UINT_TO_FP is not supported!");
10936 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10937 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10938 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10941 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10942 SelectionDAG &DAG) const {
10943 SDValue N0 = Op.getOperand(0);
10946 if (Op.getValueType().isVector())
10947 return lowerUINT_TO_FP_vec(Op, DAG);
10949 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10950 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10951 // the optimization here.
10952 if (DAG.SignBitIsZero(N0))
10953 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10955 MVT SrcVT = N0.getSimpleValueType();
10956 MVT DstVT = Op.getSimpleValueType();
10957 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10958 return LowerUINT_TO_FP_i64(Op, DAG);
10959 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10960 return LowerUINT_TO_FP_i32(Op, DAG);
10961 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10964 // Make a 64-bit buffer, and use it to build an FILD.
10965 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10966 if (SrcVT == MVT::i32) {
10967 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10968 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10969 getPointerTy(), StackSlot, WordOff);
10970 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10971 StackSlot, MachinePointerInfo(),
10973 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10974 OffsetSlot, MachinePointerInfo(),
10976 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10980 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10981 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10982 StackSlot, MachinePointerInfo(),
10984 // For i64 source, we need to add the appropriate power of 2 if the input
10985 // was negative. This is the same as the optimization in
10986 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10987 // we must be careful to do the computation in x87 extended precision, not
10988 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10989 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10990 MachineMemOperand *MMO =
10991 DAG.getMachineFunction()
10992 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10993 MachineMemOperand::MOLoad, 8, 8);
10995 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10996 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10997 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11000 APInt FF(32, 0x5F800000ULL);
11002 // Check whether the sign bit is set.
11003 SDValue SignSet = DAG.getSetCC(dl,
11004 getSetCCResultType(*DAG.getContext(), MVT::i64),
11005 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11008 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11009 SDValue FudgePtr = DAG.getConstantPool(
11010 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11013 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11014 SDValue Zero = DAG.getIntPtrConstant(0);
11015 SDValue Four = DAG.getIntPtrConstant(4);
11016 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11018 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11020 // Load the value out, extending it from f32 to f80.
11021 // FIXME: Avoid the extend by constructing the right constant pool?
11022 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11023 FudgePtr, MachinePointerInfo::getConstantPool(),
11024 MVT::f32, false, false, 4);
11025 // Extend everything to 80 bits to force it to be done on x87.
11026 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11027 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11030 std::pair<SDValue,SDValue>
11031 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11032 bool IsSigned, bool IsReplace) const {
11035 EVT DstTy = Op.getValueType();
11037 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11038 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11042 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11043 DstTy.getSimpleVT() >= MVT::i16 &&
11044 "Unknown FP_TO_INT to lower!");
11046 // These are really Legal.
11047 if (DstTy == MVT::i32 &&
11048 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11049 return std::make_pair(SDValue(), SDValue());
11050 if (Subtarget->is64Bit() &&
11051 DstTy == MVT::i64 &&
11052 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11053 return std::make_pair(SDValue(), SDValue());
11055 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11056 // stack slot, or into the FTOL runtime function.
11057 MachineFunction &MF = DAG.getMachineFunction();
11058 unsigned MemSize = DstTy.getSizeInBits()/8;
11059 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11060 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11063 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11064 Opc = X86ISD::WIN_FTOL;
11066 switch (DstTy.getSimpleVT().SimpleTy) {
11067 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11068 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11069 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11070 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11073 SDValue Chain = DAG.getEntryNode();
11074 SDValue Value = Op.getOperand(0);
11075 EVT TheVT = Op.getOperand(0).getValueType();
11076 // FIXME This causes a redundant load/store if the SSE-class value is already
11077 // in memory, such as if it is on the callstack.
11078 if (isScalarFPTypeInSSEReg(TheVT)) {
11079 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11080 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11081 MachinePointerInfo::getFixedStack(SSFI),
11083 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11085 Chain, StackSlot, DAG.getValueType(TheVT)
11088 MachineMemOperand *MMO =
11089 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11090 MachineMemOperand::MOLoad, MemSize, MemSize);
11091 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11092 Chain = Value.getValue(1);
11093 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11094 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11097 MachineMemOperand *MMO =
11098 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11099 MachineMemOperand::MOStore, MemSize, MemSize);
11101 if (Opc != X86ISD::WIN_FTOL) {
11102 // Build the FP_TO_INT*_IN_MEM
11103 SDValue Ops[] = { Chain, Value, StackSlot };
11104 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11106 return std::make_pair(FIST, StackSlot);
11108 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11109 DAG.getVTList(MVT::Other, MVT::Glue),
11111 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11112 MVT::i32, ftol.getValue(1));
11113 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11114 MVT::i32, eax.getValue(2));
11115 SDValue Ops[] = { eax, edx };
11116 SDValue pair = IsReplace
11117 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11118 : DAG.getMergeValues(Ops, DL);
11119 return std::make_pair(pair, SDValue());
11123 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11124 const X86Subtarget *Subtarget) {
11125 MVT VT = Op->getSimpleValueType(0);
11126 SDValue In = Op->getOperand(0);
11127 MVT InVT = In.getSimpleValueType();
11130 // Optimize vectors in AVX mode:
11133 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11134 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11135 // Concat upper and lower parts.
11138 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11139 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11140 // Concat upper and lower parts.
11143 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11144 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11145 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11148 if (Subtarget->hasInt256())
11149 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11151 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11152 SDValue Undef = DAG.getUNDEF(InVT);
11153 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11154 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11155 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11157 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11158 VT.getVectorNumElements()/2);
11160 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11161 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11163 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11166 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11167 SelectionDAG &DAG) {
11168 MVT VT = Op->getSimpleValueType(0);
11169 SDValue In = Op->getOperand(0);
11170 MVT InVT = In.getSimpleValueType();
11172 unsigned int NumElts = VT.getVectorNumElements();
11173 if (NumElts != 8 && NumElts != 16)
11176 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11177 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11179 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11180 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11181 // Now we have only mask extension
11182 assert(InVT.getVectorElementType() == MVT::i1);
11183 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11184 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11185 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11186 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11187 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11188 MachinePointerInfo::getConstantPool(),
11189 false, false, false, Alignment);
11191 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11192 if (VT.is512BitVector())
11194 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11197 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11198 SelectionDAG &DAG) {
11199 if (Subtarget->hasFp256()) {
11200 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11208 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11209 SelectionDAG &DAG) {
11211 MVT VT = Op.getSimpleValueType();
11212 SDValue In = Op.getOperand(0);
11213 MVT SVT = In.getSimpleValueType();
11215 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11216 return LowerZERO_EXTEND_AVX512(Op, DAG);
11218 if (Subtarget->hasFp256()) {
11219 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11224 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11225 VT.getVectorNumElements() != SVT.getVectorNumElements());
11229 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11231 MVT VT = Op.getSimpleValueType();
11232 SDValue In = Op.getOperand(0);
11233 MVT InVT = In.getSimpleValueType();
11235 if (VT == MVT::i1) {
11236 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11237 "Invalid scalar TRUNCATE operation");
11238 if (InVT == MVT::i32)
11240 if (InVT.getSizeInBits() == 64)
11241 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11242 else if (InVT.getSizeInBits() < 32)
11243 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11244 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11246 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11247 "Invalid TRUNCATE operation");
11249 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11250 if (VT.getVectorElementType().getSizeInBits() >=8)
11251 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11253 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11254 unsigned NumElts = InVT.getVectorNumElements();
11255 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11256 if (InVT.getSizeInBits() < 512) {
11257 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11258 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11262 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11263 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11264 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11265 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11266 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11267 MachinePointerInfo::getConstantPool(),
11268 false, false, false, Alignment);
11269 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11270 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11271 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11274 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11275 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11276 if (Subtarget->hasInt256()) {
11277 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11278 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11279 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11281 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11282 DAG.getIntPtrConstant(0));
11285 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11286 DAG.getIntPtrConstant(0));
11287 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11288 DAG.getIntPtrConstant(2));
11289 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11290 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11291 static const int ShufMask[] = {0, 2, 4, 6};
11292 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11295 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11296 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11297 if (Subtarget->hasInt256()) {
11298 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11300 SmallVector<SDValue,32> pshufbMask;
11301 for (unsigned i = 0; i < 2; ++i) {
11302 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11303 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11304 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11305 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11306 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11307 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11308 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11309 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11310 for (unsigned j = 0; j < 8; ++j)
11311 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11313 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11314 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11315 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11317 static const int ShufMask[] = {0, 2, -1, -1};
11318 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11320 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11321 DAG.getIntPtrConstant(0));
11322 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11325 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11326 DAG.getIntPtrConstant(0));
11328 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11329 DAG.getIntPtrConstant(4));
11331 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11332 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11334 // The PSHUFB mask:
11335 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11336 -1, -1, -1, -1, -1, -1, -1, -1};
11338 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11339 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11340 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11342 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11343 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11345 // The MOVLHPS Mask:
11346 static const int ShufMask2[] = {0, 1, 4, 5};
11347 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11348 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11351 // Handle truncation of V256 to V128 using shuffles.
11352 if (!VT.is128BitVector() || !InVT.is256BitVector())
11355 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11357 unsigned NumElems = VT.getVectorNumElements();
11358 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11360 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11361 // Prepare truncation shuffle mask
11362 for (unsigned i = 0; i != NumElems; ++i)
11363 MaskVec[i] = i * 2;
11364 SDValue V = DAG.getVectorShuffle(NVT, DL,
11365 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11366 DAG.getUNDEF(NVT), &MaskVec[0]);
11367 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11368 DAG.getIntPtrConstant(0));
11371 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11372 SelectionDAG &DAG) const {
11373 assert(!Op.getSimpleValueType().isVector());
11375 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11376 /*IsSigned=*/ true, /*IsReplace=*/ false);
11377 SDValue FIST = Vals.first, StackSlot = Vals.second;
11378 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11379 if (!FIST.getNode()) return Op;
11381 if (StackSlot.getNode())
11382 // Load the result.
11383 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11384 FIST, StackSlot, MachinePointerInfo(),
11385 false, false, false, 0);
11387 // The node is the result.
11391 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11392 SelectionDAG &DAG) const {
11393 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11394 /*IsSigned=*/ false, /*IsReplace=*/ false);
11395 SDValue FIST = Vals.first, StackSlot = Vals.second;
11396 assert(FIST.getNode() && "Unexpected failure");
11398 if (StackSlot.getNode())
11399 // Load the result.
11400 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11401 FIST, StackSlot, MachinePointerInfo(),
11402 false, false, false, 0);
11404 // The node is the result.
11408 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11410 MVT VT = Op.getSimpleValueType();
11411 SDValue In = Op.getOperand(0);
11412 MVT SVT = In.getSimpleValueType();
11414 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11416 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11417 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11418 In, DAG.getUNDEF(SVT)));
11421 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11422 LLVMContext *Context = DAG.getContext();
11424 MVT VT = Op.getSimpleValueType();
11426 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11427 if (VT.isVector()) {
11428 EltVT = VT.getVectorElementType();
11429 NumElts = VT.getVectorNumElements();
11432 if (EltVT == MVT::f64)
11433 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11434 APInt(64, ~(1ULL << 63))));
11436 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11437 APInt(32, ~(1U << 31))));
11438 C = ConstantVector::getSplat(NumElts, C);
11439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11440 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11441 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11442 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11443 MachinePointerInfo::getConstantPool(),
11444 false, false, false, Alignment);
11445 if (VT.isVector()) {
11446 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11447 return DAG.getNode(ISD::BITCAST, dl, VT,
11448 DAG.getNode(ISD::AND, dl, ANDVT,
11449 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11451 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11453 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11456 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11457 LLVMContext *Context = DAG.getContext();
11459 MVT VT = Op.getSimpleValueType();
11461 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11462 if (VT.isVector()) {
11463 EltVT = VT.getVectorElementType();
11464 NumElts = VT.getVectorNumElements();
11467 if (EltVT == MVT::f64)
11468 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11469 APInt(64, 1ULL << 63)));
11471 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11472 APInt(32, 1U << 31)));
11473 C = ConstantVector::getSplat(NumElts, C);
11474 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11475 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11476 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11477 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11478 MachinePointerInfo::getConstantPool(),
11479 false, false, false, Alignment);
11480 if (VT.isVector()) {
11481 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11482 return DAG.getNode(ISD::BITCAST, dl, VT,
11483 DAG.getNode(ISD::XOR, dl, XORVT,
11484 DAG.getNode(ISD::BITCAST, dl, XORVT,
11486 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11489 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11492 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11493 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11494 LLVMContext *Context = DAG.getContext();
11495 SDValue Op0 = Op.getOperand(0);
11496 SDValue Op1 = Op.getOperand(1);
11498 MVT VT = Op.getSimpleValueType();
11499 MVT SrcVT = Op1.getSimpleValueType();
11501 // If second operand is smaller, extend it first.
11502 if (SrcVT.bitsLT(VT)) {
11503 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11506 // And if it is bigger, shrink it first.
11507 if (SrcVT.bitsGT(VT)) {
11508 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11512 // At this point the operands and the result should have the same
11513 // type, and that won't be f80 since that is not custom lowered.
11515 // First get the sign bit of second operand.
11516 SmallVector<Constant*,4> CV;
11517 if (SrcVT == MVT::f64) {
11518 const fltSemantics &Sem = APFloat::IEEEdouble;
11519 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11520 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11522 const fltSemantics &Sem = APFloat::IEEEsingle;
11523 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11524 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11525 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11526 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11528 Constant *C = ConstantVector::get(CV);
11529 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11530 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11531 MachinePointerInfo::getConstantPool(),
11532 false, false, false, 16);
11533 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11535 // Shift sign bit right or left if the two operands have different types.
11536 if (SrcVT.bitsGT(VT)) {
11537 // Op0 is MVT::f32, Op1 is MVT::f64.
11538 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11539 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11540 DAG.getConstant(32, MVT::i32));
11541 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11542 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11543 DAG.getIntPtrConstant(0));
11546 // Clear first operand sign bit.
11548 if (VT == MVT::f64) {
11549 const fltSemantics &Sem = APFloat::IEEEdouble;
11550 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11551 APInt(64, ~(1ULL << 63)))));
11552 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11554 const fltSemantics &Sem = APFloat::IEEEsingle;
11555 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11556 APInt(32, ~(1U << 31)))));
11557 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11558 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11559 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11561 C = ConstantVector::get(CV);
11562 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11563 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11564 MachinePointerInfo::getConstantPool(),
11565 false, false, false, 16);
11566 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11568 // Or the value with the sign bit.
11569 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11572 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11573 SDValue N0 = Op.getOperand(0);
11575 MVT VT = Op.getSimpleValueType();
11577 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11578 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11579 DAG.getConstant(1, VT));
11580 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11583 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11585 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11586 SelectionDAG &DAG) {
11587 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11589 if (!Subtarget->hasSSE41())
11592 if (!Op->hasOneUse())
11595 SDNode *N = Op.getNode();
11598 SmallVector<SDValue, 8> Opnds;
11599 DenseMap<SDValue, unsigned> VecInMap;
11600 SmallVector<SDValue, 8> VecIns;
11601 EVT VT = MVT::Other;
11603 // Recognize a special case where a vector is casted into wide integer to
11605 Opnds.push_back(N->getOperand(0));
11606 Opnds.push_back(N->getOperand(1));
11608 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11609 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11610 // BFS traverse all OR'd operands.
11611 if (I->getOpcode() == ISD::OR) {
11612 Opnds.push_back(I->getOperand(0));
11613 Opnds.push_back(I->getOperand(1));
11614 // Re-evaluate the number of nodes to be traversed.
11615 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11619 // Quit if a non-EXTRACT_VECTOR_ELT
11620 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11623 // Quit if without a constant index.
11624 SDValue Idx = I->getOperand(1);
11625 if (!isa<ConstantSDNode>(Idx))
11628 SDValue ExtractedFromVec = I->getOperand(0);
11629 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11630 if (M == VecInMap.end()) {
11631 VT = ExtractedFromVec.getValueType();
11632 // Quit if not 128/256-bit vector.
11633 if (!VT.is128BitVector() && !VT.is256BitVector())
11635 // Quit if not the same type.
11636 if (VecInMap.begin() != VecInMap.end() &&
11637 VT != VecInMap.begin()->first.getValueType())
11639 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11640 VecIns.push_back(ExtractedFromVec);
11642 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11645 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11646 "Not extracted from 128-/256-bit vector.");
11648 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11650 for (DenseMap<SDValue, unsigned>::const_iterator
11651 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11652 // Quit if not all elements are used.
11653 if (I->second != FullMask)
11657 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11659 // Cast all vectors into TestVT for PTEST.
11660 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11661 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11663 // If more than one full vectors are evaluated, OR them first before PTEST.
11664 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11665 // Each iteration will OR 2 nodes and append the result until there is only
11666 // 1 node left, i.e. the final OR'd value of all vectors.
11667 SDValue LHS = VecIns[Slot];
11668 SDValue RHS = VecIns[Slot + 1];
11669 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11672 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11673 VecIns.back(), VecIns.back());
11676 /// \brief return true if \c Op has a use that doesn't just read flags.
11677 static bool hasNonFlagsUse(SDValue Op) {
11678 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11680 SDNode *User = *UI;
11681 unsigned UOpNo = UI.getOperandNo();
11682 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11683 // Look pass truncate.
11684 UOpNo = User->use_begin().getOperandNo();
11685 User = *User->use_begin();
11688 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11689 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11695 /// Emit nodes that will be selected as "test Op0,Op0", or something
11697 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11698 SelectionDAG &DAG) const {
11699 if (Op.getValueType() == MVT::i1)
11700 // KORTEST instruction should be selected
11701 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11702 DAG.getConstant(0, Op.getValueType()));
11704 // CF and OF aren't always set the way we want. Determine which
11705 // of these we need.
11706 bool NeedCF = false;
11707 bool NeedOF = false;
11710 case X86::COND_A: case X86::COND_AE:
11711 case X86::COND_B: case X86::COND_BE:
11714 case X86::COND_G: case X86::COND_GE:
11715 case X86::COND_L: case X86::COND_LE:
11716 case X86::COND_O: case X86::COND_NO: {
11717 // Check if we really need to set the
11718 // Overflow flag. If NoSignedWrap is present
11719 // that is not actually needed.
11720 switch (Op->getOpcode()) {
11725 const BinaryWithFlagsSDNode *BinNode =
11726 cast<BinaryWithFlagsSDNode>(Op.getNode());
11727 if (BinNode->hasNoSignedWrap())
11737 // See if we can use the EFLAGS value from the operand instead of
11738 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11739 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11740 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11741 // Emit a CMP with 0, which is the TEST pattern.
11742 //if (Op.getValueType() == MVT::i1)
11743 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11744 // DAG.getConstant(0, MVT::i1));
11745 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11746 DAG.getConstant(0, Op.getValueType()));
11748 unsigned Opcode = 0;
11749 unsigned NumOperands = 0;
11751 // Truncate operations may prevent the merge of the SETCC instruction
11752 // and the arithmetic instruction before it. Attempt to truncate the operands
11753 // of the arithmetic instruction and use a reduced bit-width instruction.
11754 bool NeedTruncation = false;
11755 SDValue ArithOp = Op;
11756 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11757 SDValue Arith = Op->getOperand(0);
11758 // Both the trunc and the arithmetic op need to have one user each.
11759 if (Arith->hasOneUse())
11760 switch (Arith.getOpcode()) {
11767 NeedTruncation = true;
11773 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11774 // which may be the result of a CAST. We use the variable 'Op', which is the
11775 // non-casted variable when we check for possible users.
11776 switch (ArithOp.getOpcode()) {
11778 // Due to an isel shortcoming, be conservative if this add is likely to be
11779 // selected as part of a load-modify-store instruction. When the root node
11780 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11781 // uses of other nodes in the match, such as the ADD in this case. This
11782 // leads to the ADD being left around and reselected, with the result being
11783 // two adds in the output. Alas, even if none our users are stores, that
11784 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11785 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11786 // climbing the DAG back to the root, and it doesn't seem to be worth the
11788 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11789 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11790 if (UI->getOpcode() != ISD::CopyToReg &&
11791 UI->getOpcode() != ISD::SETCC &&
11792 UI->getOpcode() != ISD::STORE)
11795 if (ConstantSDNode *C =
11796 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11797 // An add of one will be selected as an INC.
11798 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11799 Opcode = X86ISD::INC;
11804 // An add of negative one (subtract of one) will be selected as a DEC.
11805 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11806 Opcode = X86ISD::DEC;
11812 // Otherwise use a regular EFLAGS-setting add.
11813 Opcode = X86ISD::ADD;
11818 // If we have a constant logical shift that's only used in a comparison
11819 // against zero turn it into an equivalent AND. This allows turning it into
11820 // a TEST instruction later.
11821 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11822 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11823 EVT VT = Op.getValueType();
11824 unsigned BitWidth = VT.getSizeInBits();
11825 unsigned ShAmt = Op->getConstantOperandVal(1);
11826 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11828 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11829 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11830 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11831 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11833 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11834 DAG.getConstant(Mask, VT));
11835 DAG.ReplaceAllUsesWith(Op, New);
11841 // If the primary and result isn't used, don't bother using X86ISD::AND,
11842 // because a TEST instruction will be better.
11843 if (!hasNonFlagsUse(Op))
11849 // Due to the ISEL shortcoming noted above, be conservative if this op is
11850 // likely to be selected as part of a load-modify-store instruction.
11851 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11852 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11853 if (UI->getOpcode() == ISD::STORE)
11856 // Otherwise use a regular EFLAGS-setting instruction.
11857 switch (ArithOp.getOpcode()) {
11858 default: llvm_unreachable("unexpected operator!");
11859 case ISD::SUB: Opcode = X86ISD::SUB; break;
11860 case ISD::XOR: Opcode = X86ISD::XOR; break;
11861 case ISD::AND: Opcode = X86ISD::AND; break;
11863 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11864 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11865 if (EFLAGS.getNode())
11868 Opcode = X86ISD::OR;
11882 return SDValue(Op.getNode(), 1);
11888 // If we found that truncation is beneficial, perform the truncation and
11890 if (NeedTruncation) {
11891 EVT VT = Op.getValueType();
11892 SDValue WideVal = Op->getOperand(0);
11893 EVT WideVT = WideVal.getValueType();
11894 unsigned ConvertedOp = 0;
11895 // Use a target machine opcode to prevent further DAGCombine
11896 // optimizations that may separate the arithmetic operations
11897 // from the setcc node.
11898 switch (WideVal.getOpcode()) {
11900 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11901 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11902 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11903 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11904 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11909 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11910 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11911 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11912 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11918 // Emit a CMP with 0, which is the TEST pattern.
11919 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11920 DAG.getConstant(0, Op.getValueType()));
11922 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11923 SmallVector<SDValue, 4> Ops;
11924 for (unsigned i = 0; i != NumOperands; ++i)
11925 Ops.push_back(Op.getOperand(i));
11927 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11928 DAG.ReplaceAllUsesWith(Op, New);
11929 return SDValue(New.getNode(), 1);
11932 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11934 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11935 SDLoc dl, SelectionDAG &DAG) const {
11936 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11937 if (C->getAPIntValue() == 0)
11938 return EmitTest(Op0, X86CC, dl, DAG);
11940 if (Op0.getValueType() == MVT::i1)
11941 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11944 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11945 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11946 // Do the comparison at i32 if it's smaller, besides the Atom case.
11947 // This avoids subregister aliasing issues. Keep the smaller reference
11948 // if we're optimizing for size, however, as that'll allow better folding
11949 // of memory operations.
11950 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11951 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11952 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11953 !Subtarget->isAtom()) {
11954 unsigned ExtendOp =
11955 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11956 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11957 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11959 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11960 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11961 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11963 return SDValue(Sub.getNode(), 1);
11965 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11968 /// Convert a comparison if required by the subtarget.
11969 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11970 SelectionDAG &DAG) const {
11971 // If the subtarget does not support the FUCOMI instruction, floating-point
11972 // comparisons have to be converted.
11973 if (Subtarget->hasCMov() ||
11974 Cmp.getOpcode() != X86ISD::CMP ||
11975 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11976 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11979 // The instruction selector will select an FUCOM instruction instead of
11980 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11981 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11982 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11984 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11985 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11986 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11987 DAG.getConstant(8, MVT::i8));
11988 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11989 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11992 static bool isAllOnes(SDValue V) {
11993 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11994 return C && C->isAllOnesValue();
11997 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11998 /// if it's possible.
11999 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12000 SDLoc dl, SelectionDAG &DAG) const {
12001 SDValue Op0 = And.getOperand(0);
12002 SDValue Op1 = And.getOperand(1);
12003 if (Op0.getOpcode() == ISD::TRUNCATE)
12004 Op0 = Op0.getOperand(0);
12005 if (Op1.getOpcode() == ISD::TRUNCATE)
12006 Op1 = Op1.getOperand(0);
12009 if (Op1.getOpcode() == ISD::SHL)
12010 std::swap(Op0, Op1);
12011 if (Op0.getOpcode() == ISD::SHL) {
12012 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12013 if (And00C->getZExtValue() == 1) {
12014 // If we looked past a truncate, check that it's only truncating away
12016 unsigned BitWidth = Op0.getValueSizeInBits();
12017 unsigned AndBitWidth = And.getValueSizeInBits();
12018 if (BitWidth > AndBitWidth) {
12020 DAG.computeKnownBits(Op0, Zeros, Ones);
12021 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12025 RHS = Op0.getOperand(1);
12027 } else if (Op1.getOpcode() == ISD::Constant) {
12028 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12029 uint64_t AndRHSVal = AndRHS->getZExtValue();
12030 SDValue AndLHS = Op0;
12032 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12033 LHS = AndLHS.getOperand(0);
12034 RHS = AndLHS.getOperand(1);
12037 // Use BT if the immediate can't be encoded in a TEST instruction.
12038 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12040 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12044 if (LHS.getNode()) {
12045 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12046 // instruction. Since the shift amount is in-range-or-undefined, we know
12047 // that doing a bittest on the i32 value is ok. We extend to i32 because
12048 // the encoding for the i16 version is larger than the i32 version.
12049 // Also promote i16 to i32 for performance / code size reason.
12050 if (LHS.getValueType() == MVT::i8 ||
12051 LHS.getValueType() == MVT::i16)
12052 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12054 // If the operand types disagree, extend the shift amount to match. Since
12055 // BT ignores high bits (like shifts) we can use anyextend.
12056 if (LHS.getValueType() != RHS.getValueType())
12057 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12059 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12060 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12061 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12062 DAG.getConstant(Cond, MVT::i8), BT);
12068 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12070 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12075 // SSE Condition code mapping:
12084 switch (SetCCOpcode) {
12085 default: llvm_unreachable("Unexpected SETCC condition");
12087 case ISD::SETEQ: SSECC = 0; break;
12089 case ISD::SETGT: Swap = true; // Fallthrough
12091 case ISD::SETOLT: SSECC = 1; break;
12093 case ISD::SETGE: Swap = true; // Fallthrough
12095 case ISD::SETOLE: SSECC = 2; break;
12096 case ISD::SETUO: SSECC = 3; break;
12098 case ISD::SETNE: SSECC = 4; break;
12099 case ISD::SETULE: Swap = true; // Fallthrough
12100 case ISD::SETUGE: SSECC = 5; break;
12101 case ISD::SETULT: Swap = true; // Fallthrough
12102 case ISD::SETUGT: SSECC = 6; break;
12103 case ISD::SETO: SSECC = 7; break;
12105 case ISD::SETONE: SSECC = 8; break;
12108 std::swap(Op0, Op1);
12113 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12114 // ones, and then concatenate the result back.
12115 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12116 MVT VT = Op.getSimpleValueType();
12118 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12119 "Unsupported value type for operation");
12121 unsigned NumElems = VT.getVectorNumElements();
12123 SDValue CC = Op.getOperand(2);
12125 // Extract the LHS vectors
12126 SDValue LHS = Op.getOperand(0);
12127 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12128 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12130 // Extract the RHS vectors
12131 SDValue RHS = Op.getOperand(1);
12132 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12133 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12135 // Issue the operation on the smaller types and concatenate the result back
12136 MVT EltVT = VT.getVectorElementType();
12137 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12138 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12139 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12140 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12143 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12144 const X86Subtarget *Subtarget) {
12145 SDValue Op0 = Op.getOperand(0);
12146 SDValue Op1 = Op.getOperand(1);
12147 SDValue CC = Op.getOperand(2);
12148 MVT VT = Op.getSimpleValueType();
12151 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12152 Op.getValueType().getScalarType() == MVT::i1 &&
12153 "Cannot set masked compare for this operation");
12155 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12157 bool Unsigned = false;
12160 switch (SetCCOpcode) {
12161 default: llvm_unreachable("Unexpected SETCC condition");
12162 case ISD::SETNE: SSECC = 4; break;
12163 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12164 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12165 case ISD::SETLT: Swap = true; //fall-through
12166 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12167 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12168 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12169 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12170 case ISD::SETULE: Unsigned = true; //fall-through
12171 case ISD::SETLE: SSECC = 2; break;
12175 std::swap(Op0, Op1);
12177 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12178 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12179 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12180 DAG.getConstant(SSECC, MVT::i8));
12183 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12184 /// operand \p Op1. If non-trivial (for example because it's not constant)
12185 /// return an empty value.
12186 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12188 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12192 MVT VT = Op1.getSimpleValueType();
12193 MVT EVT = VT.getVectorElementType();
12194 unsigned n = VT.getVectorNumElements();
12195 SmallVector<SDValue, 8> ULTOp1;
12197 for (unsigned i = 0; i < n; ++i) {
12198 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12199 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12202 // Avoid underflow.
12203 APInt Val = Elt->getAPIntValue();
12207 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12210 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12213 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12214 SelectionDAG &DAG) {
12215 SDValue Op0 = Op.getOperand(0);
12216 SDValue Op1 = Op.getOperand(1);
12217 SDValue CC = Op.getOperand(2);
12218 MVT VT = Op.getSimpleValueType();
12219 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12220 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12225 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12226 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12229 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12230 unsigned Opc = X86ISD::CMPP;
12231 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12232 assert(VT.getVectorNumElements() <= 16);
12233 Opc = X86ISD::CMPM;
12235 // In the two special cases we can't handle, emit two comparisons.
12238 unsigned CombineOpc;
12239 if (SetCCOpcode == ISD::SETUEQ) {
12240 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12242 assert(SetCCOpcode == ISD::SETONE);
12243 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12246 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12247 DAG.getConstant(CC0, MVT::i8));
12248 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12249 DAG.getConstant(CC1, MVT::i8));
12250 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12252 // Handle all other FP comparisons here.
12253 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12254 DAG.getConstant(SSECC, MVT::i8));
12257 // Break 256-bit integer vector compare into smaller ones.
12258 if (VT.is256BitVector() && !Subtarget->hasInt256())
12259 return Lower256IntVSETCC(Op, DAG);
12261 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12262 EVT OpVT = Op1.getValueType();
12263 if (Subtarget->hasAVX512()) {
12264 if (Op1.getValueType().is512BitVector() ||
12265 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12266 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12268 // In AVX-512 architecture setcc returns mask with i1 elements,
12269 // But there is no compare instruction for i8 and i16 elements.
12270 // We are not talking about 512-bit operands in this case, these
12271 // types are illegal.
12273 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12274 OpVT.getVectorElementType().getSizeInBits() >= 8))
12275 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12276 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12279 // We are handling one of the integer comparisons here. Since SSE only has
12280 // GT and EQ comparisons for integer, swapping operands and multiple
12281 // operations may be required for some comparisons.
12283 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12284 bool Subus = false;
12286 switch (SetCCOpcode) {
12287 default: llvm_unreachable("Unexpected SETCC condition");
12288 case ISD::SETNE: Invert = true;
12289 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12290 case ISD::SETLT: Swap = true;
12291 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12292 case ISD::SETGE: Swap = true;
12293 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12294 Invert = true; break;
12295 case ISD::SETULT: Swap = true;
12296 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12297 FlipSigns = true; break;
12298 case ISD::SETUGE: Swap = true;
12299 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12300 FlipSigns = true; Invert = true; break;
12303 // Special case: Use min/max operations for SETULE/SETUGE
12304 MVT VET = VT.getVectorElementType();
12306 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12307 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12310 switch (SetCCOpcode) {
12312 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12313 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12316 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12319 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12320 if (!MinMax && hasSubus) {
12321 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12323 // t = psubus Op0, Op1
12324 // pcmpeq t, <0..0>
12325 switch (SetCCOpcode) {
12327 case ISD::SETULT: {
12328 // If the comparison is against a constant we can turn this into a
12329 // setule. With psubus, setule does not require a swap. This is
12330 // beneficial because the constant in the register is no longer
12331 // destructed as the destination so it can be hoisted out of a loop.
12332 // Only do this pre-AVX since vpcmp* is no longer destructive.
12333 if (Subtarget->hasAVX())
12335 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12336 if (ULEOp1.getNode()) {
12338 Subus = true; Invert = false; Swap = false;
12342 // Psubus is better than flip-sign because it requires no inversion.
12343 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12344 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12348 Opc = X86ISD::SUBUS;
12354 std::swap(Op0, Op1);
12356 // Check that the operation in question is available (most are plain SSE2,
12357 // but PCMPGTQ and PCMPEQQ have different requirements).
12358 if (VT == MVT::v2i64) {
12359 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12360 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12362 // First cast everything to the right type.
12363 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12364 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12366 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12367 // bits of the inputs before performing those operations. The lower
12368 // compare is always unsigned.
12371 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12373 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12374 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12375 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12376 Sign, Zero, Sign, Zero);
12378 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12379 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12381 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12382 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12383 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12385 // Create masks for only the low parts/high parts of the 64 bit integers.
12386 static const int MaskHi[] = { 1, 1, 3, 3 };
12387 static const int MaskLo[] = { 0, 0, 2, 2 };
12388 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12389 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12390 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12392 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12393 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12396 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12398 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12401 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12402 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12403 // pcmpeqd + pshufd + pand.
12404 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12406 // First cast everything to the right type.
12407 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12408 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12411 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12413 // Make sure the lower and upper halves are both all-ones.
12414 static const int Mask[] = { 1, 0, 3, 2 };
12415 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12416 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12419 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12421 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12425 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12426 // bits of the inputs before performing those operations.
12428 EVT EltVT = VT.getVectorElementType();
12429 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12430 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12431 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12434 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12436 // If the logical-not of the result is required, perform that now.
12438 Result = DAG.getNOT(dl, Result, VT);
12441 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12444 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12445 getZeroVector(VT, Subtarget, DAG, dl));
12450 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12452 MVT VT = Op.getSimpleValueType();
12454 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12456 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12457 && "SetCC type must be 8-bit or 1-bit integer");
12458 SDValue Op0 = Op.getOperand(0);
12459 SDValue Op1 = Op.getOperand(1);
12461 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12463 // Optimize to BT if possible.
12464 // Lower (X & (1 << N)) == 0 to BT(X, N).
12465 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12466 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12467 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12468 Op1.getOpcode() == ISD::Constant &&
12469 cast<ConstantSDNode>(Op1)->isNullValue() &&
12470 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12471 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12472 if (NewSetCC.getNode())
12476 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12478 if (Op1.getOpcode() == ISD::Constant &&
12479 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12480 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12481 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12483 // If the input is a setcc, then reuse the input setcc or use a new one with
12484 // the inverted condition.
12485 if (Op0.getOpcode() == X86ISD::SETCC) {
12486 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12487 bool Invert = (CC == ISD::SETNE) ^
12488 cast<ConstantSDNode>(Op1)->isNullValue();
12492 CCode = X86::GetOppositeBranchCondition(CCode);
12493 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12494 DAG.getConstant(CCode, MVT::i8),
12495 Op0.getOperand(1));
12497 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12501 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12502 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12503 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12505 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12506 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12509 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12510 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12511 if (X86CC == X86::COND_INVALID)
12514 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12515 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12516 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12517 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12519 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12523 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12524 static bool isX86LogicalCmp(SDValue Op) {
12525 unsigned Opc = Op.getNode()->getOpcode();
12526 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12527 Opc == X86ISD::SAHF)
12529 if (Op.getResNo() == 1 &&
12530 (Opc == X86ISD::ADD ||
12531 Opc == X86ISD::SUB ||
12532 Opc == X86ISD::ADC ||
12533 Opc == X86ISD::SBB ||
12534 Opc == X86ISD::SMUL ||
12535 Opc == X86ISD::UMUL ||
12536 Opc == X86ISD::INC ||
12537 Opc == X86ISD::DEC ||
12538 Opc == X86ISD::OR ||
12539 Opc == X86ISD::XOR ||
12540 Opc == X86ISD::AND))
12543 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12549 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12550 if (V.getOpcode() != ISD::TRUNCATE)
12553 SDValue VOp0 = V.getOperand(0);
12554 unsigned InBits = VOp0.getValueSizeInBits();
12555 unsigned Bits = V.getValueSizeInBits();
12556 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12559 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12560 bool addTest = true;
12561 SDValue Cond = Op.getOperand(0);
12562 SDValue Op1 = Op.getOperand(1);
12563 SDValue Op2 = Op.getOperand(2);
12565 EVT VT = Op1.getValueType();
12568 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12569 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12570 // sequence later on.
12571 if (Cond.getOpcode() == ISD::SETCC &&
12572 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12573 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12574 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12575 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12576 int SSECC = translateX86FSETCC(
12577 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12580 if (Subtarget->hasAVX512()) {
12581 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12582 DAG.getConstant(SSECC, MVT::i8));
12583 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12585 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12586 DAG.getConstant(SSECC, MVT::i8));
12587 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12588 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12589 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12593 if (Cond.getOpcode() == ISD::SETCC) {
12594 SDValue NewCond = LowerSETCC(Cond, DAG);
12595 if (NewCond.getNode())
12599 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12600 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12601 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12602 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12603 if (Cond.getOpcode() == X86ISD::SETCC &&
12604 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12605 isZero(Cond.getOperand(1).getOperand(1))) {
12606 SDValue Cmp = Cond.getOperand(1);
12608 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12610 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12611 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12612 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12614 SDValue CmpOp0 = Cmp.getOperand(0);
12615 // Apply further optimizations for special cases
12616 // (select (x != 0), -1, 0) -> neg & sbb
12617 // (select (x == 0), 0, -1) -> neg & sbb
12618 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12619 if (YC->isNullValue() &&
12620 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12621 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12622 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12623 DAG.getConstant(0, CmpOp0.getValueType()),
12625 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12626 DAG.getConstant(X86::COND_B, MVT::i8),
12627 SDValue(Neg.getNode(), 1));
12631 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12632 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12633 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12635 SDValue Res = // Res = 0 or -1.
12636 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12637 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12639 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12640 Res = DAG.getNOT(DL, Res, Res.getValueType());
12642 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12643 if (!N2C || !N2C->isNullValue())
12644 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12649 // Look past (and (setcc_carry (cmp ...)), 1).
12650 if (Cond.getOpcode() == ISD::AND &&
12651 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12652 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12653 if (C && C->getAPIntValue() == 1)
12654 Cond = Cond.getOperand(0);
12657 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12658 // setting operand in place of the X86ISD::SETCC.
12659 unsigned CondOpcode = Cond.getOpcode();
12660 if (CondOpcode == X86ISD::SETCC ||
12661 CondOpcode == X86ISD::SETCC_CARRY) {
12662 CC = Cond.getOperand(0);
12664 SDValue Cmp = Cond.getOperand(1);
12665 unsigned Opc = Cmp.getOpcode();
12666 MVT VT = Op.getSimpleValueType();
12668 bool IllegalFPCMov = false;
12669 if (VT.isFloatingPoint() && !VT.isVector() &&
12670 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12671 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12673 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12674 Opc == X86ISD::BT) { // FIXME
12678 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12679 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12680 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12681 Cond.getOperand(0).getValueType() != MVT::i8)) {
12682 SDValue LHS = Cond.getOperand(0);
12683 SDValue RHS = Cond.getOperand(1);
12684 unsigned X86Opcode;
12687 switch (CondOpcode) {
12688 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12689 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12690 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12691 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12692 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12693 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12694 default: llvm_unreachable("unexpected overflowing operator");
12696 if (CondOpcode == ISD::UMULO)
12697 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12700 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12702 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12704 if (CondOpcode == ISD::UMULO)
12705 Cond = X86Op.getValue(2);
12707 Cond = X86Op.getValue(1);
12709 CC = DAG.getConstant(X86Cond, MVT::i8);
12714 // Look pass the truncate if the high bits are known zero.
12715 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12716 Cond = Cond.getOperand(0);
12718 // We know the result of AND is compared against zero. Try to match
12720 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12721 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12722 if (NewSetCC.getNode()) {
12723 CC = NewSetCC.getOperand(0);
12724 Cond = NewSetCC.getOperand(1);
12731 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12732 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12735 // a < b ? -1 : 0 -> RES = ~setcc_carry
12736 // a < b ? 0 : -1 -> RES = setcc_carry
12737 // a >= b ? -1 : 0 -> RES = setcc_carry
12738 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12739 if (Cond.getOpcode() == X86ISD::SUB) {
12740 Cond = ConvertCmpIfNecessary(Cond, DAG);
12741 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12743 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12744 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12745 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12746 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12747 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12748 return DAG.getNOT(DL, Res, Res.getValueType());
12753 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12754 // widen the cmov and push the truncate through. This avoids introducing a new
12755 // branch during isel and doesn't add any extensions.
12756 if (Op.getValueType() == MVT::i8 &&
12757 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12758 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12759 if (T1.getValueType() == T2.getValueType() &&
12760 // Blacklist CopyFromReg to avoid partial register stalls.
12761 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12762 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12763 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12764 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12768 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12769 // condition is true.
12770 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12771 SDValue Ops[] = { Op2, Op1, CC, Cond };
12772 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12775 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12776 MVT VT = Op->getSimpleValueType(0);
12777 SDValue In = Op->getOperand(0);
12778 MVT InVT = In.getSimpleValueType();
12781 unsigned int NumElts = VT.getVectorNumElements();
12782 if (NumElts != 8 && NumElts != 16)
12785 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12786 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12789 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12791 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12792 Constant *C = ConstantInt::get(*DAG.getContext(),
12793 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12795 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12796 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12797 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12798 MachinePointerInfo::getConstantPool(),
12799 false, false, false, Alignment);
12800 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12801 if (VT.is512BitVector())
12803 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12806 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12807 SelectionDAG &DAG) {
12808 MVT VT = Op->getSimpleValueType(0);
12809 SDValue In = Op->getOperand(0);
12810 MVT InVT = In.getSimpleValueType();
12813 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12814 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12816 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12817 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12818 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12821 if (Subtarget->hasInt256())
12822 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12824 // Optimize vectors in AVX mode
12825 // Sign extend v8i16 to v8i32 and
12828 // Divide input vector into two parts
12829 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12830 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12831 // concat the vectors to original VT
12833 unsigned NumElems = InVT.getVectorNumElements();
12834 SDValue Undef = DAG.getUNDEF(InVT);
12836 SmallVector<int,8> ShufMask1(NumElems, -1);
12837 for (unsigned i = 0; i != NumElems/2; ++i)
12840 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12842 SmallVector<int,8> ShufMask2(NumElems, -1);
12843 for (unsigned i = 0; i != NumElems/2; ++i)
12844 ShufMask2[i] = i + NumElems/2;
12846 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12848 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12849 VT.getVectorNumElements()/2);
12851 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12852 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12854 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12857 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
12858 // may emit an illegal shuffle but the expansion is still better than scalar
12859 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
12860 // we'll emit a shuffle and a arithmetic shift.
12861 // TODO: It is possible to support ZExt by zeroing the undef values during
12862 // the shuffle phase or after the shuffle.
12863 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
12864 SelectionDAG &DAG) {
12865 MVT RegVT = Op.getSimpleValueType();
12866 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
12867 assert(RegVT.isInteger() &&
12868 "We only custom lower integer vector sext loads.");
12870 // Nothing useful we can do without SSE2 shuffles.
12871 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
12873 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
12875 EVT MemVT = Ld->getMemoryVT();
12876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12877 unsigned RegSz = RegVT.getSizeInBits();
12879 ISD::LoadExtType Ext = Ld->getExtensionType();
12881 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
12882 && "Only anyext and sext are currently implemented.");
12883 assert(MemVT != RegVT && "Cannot extend to the same type");
12884 assert(MemVT.isVector() && "Must load a vector from memory");
12886 unsigned NumElems = RegVT.getVectorNumElements();
12887 unsigned MemSz = MemVT.getSizeInBits();
12888 assert(RegSz > MemSz && "Register size must be greater than the mem size");
12890 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
12891 // The only way in which we have a legal 256-bit vector result but not the
12892 // integer 256-bit operations needed to directly lower a sextload is if we
12893 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
12894 // a 128-bit vector and a normal sign_extend to 256-bits that should get
12895 // correctly legalized. We do this late to allow the canonical form of
12896 // sextload to persist throughout the rest of the DAG combiner -- it wants
12897 // to fold together any extensions it can, and so will fuse a sign_extend
12898 // of an sextload into an sextload targeting a wider value.
12900 if (MemSz == 128) {
12901 // Just switch this to a normal load.
12902 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
12903 "it must be a legal 128-bit vector "
12905 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
12906 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
12907 Ld->isInvariant(), Ld->getAlignment());
12909 assert(MemSz < 128 &&
12910 "Can't extend a type wider than 128 bits to a 256 bit vector!");
12911 // Do an sext load to a 128-bit vector type. We want to use the same
12912 // number of elements, but elements half as wide. This will end up being
12913 // recursively lowered by this routine, but will succeed as we definitely
12914 // have all the necessary features if we're using AVX1.
12916 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
12917 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
12919 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
12920 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
12921 Ld->isNonTemporal(), Ld->getAlignment());
12924 // Replace chain users with the new chain.
12925 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
12926 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
12928 // Finally, do a normal sign-extend to the desired register.
12929 return DAG.getSExtOrTrunc(Load, dl, RegVT);
12932 // All sizes must be a power of two.
12933 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
12934 "Non-power-of-two elements are not custom lowered!");
12936 // Attempt to load the original value using scalar loads.
12937 // Find the largest scalar type that divides the total loaded size.
12938 MVT SclrLoadTy = MVT::i8;
12939 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
12940 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
12941 MVT Tp = (MVT::SimpleValueType)tp;
12942 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
12947 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
12948 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
12950 SclrLoadTy = MVT::f64;
12952 // Calculate the number of scalar loads that we need to perform
12953 // in order to load our vector from memory.
12954 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
12956 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
12957 "Can only lower sext loads with a single scalar load!");
12959 unsigned loadRegZize = RegSz;
12960 if (Ext == ISD::SEXTLOAD && RegSz == 256)
12963 // Represent our vector as a sequence of elements which are the
12964 // largest scalar that we can load.
12965 EVT LoadUnitVecVT = EVT::getVectorVT(
12966 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
12968 // Represent the data using the same element type that is stored in
12969 // memory. In practice, we ''widen'' MemVT.
12971 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
12972 loadRegZize / MemVT.getScalarType().getSizeInBits());
12974 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
12975 "Invalid vector type");
12977 // We can't shuffle using an illegal type.
12978 assert(TLI.isTypeLegal(WideVecVT) &&
12979 "We only lower types that form legal widened vector types");
12981 SmallVector<SDValue, 8> Chains;
12982 SDValue Ptr = Ld->getBasePtr();
12983 SDValue Increment =
12984 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
12985 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
12987 for (unsigned i = 0; i < NumLoads; ++i) {
12988 // Perform a single load.
12989 SDValue ScalarLoad =
12990 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
12991 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
12992 Ld->getAlignment());
12993 Chains.push_back(ScalarLoad.getValue(1));
12994 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
12995 // another round of DAGCombining.
12997 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
12999 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13000 ScalarLoad, DAG.getIntPtrConstant(i));
13002 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13005 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13007 // Bitcast the loaded value to a vector of the original element type, in
13008 // the size of the target vector type.
13009 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13010 unsigned SizeRatio = RegSz / MemSz;
13012 if (Ext == ISD::SEXTLOAD) {
13013 // If we have SSE4.1 we can directly emit a VSEXT node.
13014 if (Subtarget->hasSSE41()) {
13015 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13016 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13020 // Otherwise we'll shuffle the small elements in the high bits of the
13021 // larger type and perform an arithmetic shift. If the shift is not legal
13022 // it's better to scalarize.
13023 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13024 "We can't implement an sext load without a arithmetic right shift!");
13026 // Redistribute the loaded elements into the different locations.
13027 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13028 for (unsigned i = 0; i != NumElems; ++i)
13029 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13031 SDValue Shuff = DAG.getVectorShuffle(
13032 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13034 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13036 // Build the arithmetic shift.
13037 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13038 MemVT.getVectorElementType().getSizeInBits();
13040 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13042 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13046 // Redistribute the loaded elements into the different locations.
13047 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13048 for (unsigned i = 0; i != NumElems; ++i)
13049 ShuffleVec[i * SizeRatio] = i;
13051 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13052 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13054 // Bitcast to the requested type.
13055 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13056 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13060 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13061 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13062 // from the AND / OR.
13063 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13064 Opc = Op.getOpcode();
13065 if (Opc != ISD::OR && Opc != ISD::AND)
13067 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13068 Op.getOperand(0).hasOneUse() &&
13069 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13070 Op.getOperand(1).hasOneUse());
13073 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13074 // 1 and that the SETCC node has a single use.
13075 static bool isXor1OfSetCC(SDValue Op) {
13076 if (Op.getOpcode() != ISD::XOR)
13078 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13079 if (N1C && N1C->getAPIntValue() == 1) {
13080 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13081 Op.getOperand(0).hasOneUse();
13086 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13087 bool addTest = true;
13088 SDValue Chain = Op.getOperand(0);
13089 SDValue Cond = Op.getOperand(1);
13090 SDValue Dest = Op.getOperand(2);
13093 bool Inverted = false;
13095 if (Cond.getOpcode() == ISD::SETCC) {
13096 // Check for setcc([su]{add,sub,mul}o == 0).
13097 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13098 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13099 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13100 Cond.getOperand(0).getResNo() == 1 &&
13101 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13102 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13103 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13104 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13105 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13106 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13108 Cond = Cond.getOperand(0);
13110 SDValue NewCond = LowerSETCC(Cond, DAG);
13111 if (NewCond.getNode())
13116 // FIXME: LowerXALUO doesn't handle these!!
13117 else if (Cond.getOpcode() == X86ISD::ADD ||
13118 Cond.getOpcode() == X86ISD::SUB ||
13119 Cond.getOpcode() == X86ISD::SMUL ||
13120 Cond.getOpcode() == X86ISD::UMUL)
13121 Cond = LowerXALUO(Cond, DAG);
13124 // Look pass (and (setcc_carry (cmp ...)), 1).
13125 if (Cond.getOpcode() == ISD::AND &&
13126 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13127 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13128 if (C && C->getAPIntValue() == 1)
13129 Cond = Cond.getOperand(0);
13132 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13133 // setting operand in place of the X86ISD::SETCC.
13134 unsigned CondOpcode = Cond.getOpcode();
13135 if (CondOpcode == X86ISD::SETCC ||
13136 CondOpcode == X86ISD::SETCC_CARRY) {
13137 CC = Cond.getOperand(0);
13139 SDValue Cmp = Cond.getOperand(1);
13140 unsigned Opc = Cmp.getOpcode();
13141 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13142 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13146 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13150 // These can only come from an arithmetic instruction with overflow,
13151 // e.g. SADDO, UADDO.
13152 Cond = Cond.getNode()->getOperand(1);
13158 CondOpcode = Cond.getOpcode();
13159 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13160 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13161 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13162 Cond.getOperand(0).getValueType() != MVT::i8)) {
13163 SDValue LHS = Cond.getOperand(0);
13164 SDValue RHS = Cond.getOperand(1);
13165 unsigned X86Opcode;
13168 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13169 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13171 switch (CondOpcode) {
13172 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13176 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13179 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13180 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13184 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13187 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13188 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13189 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13190 default: llvm_unreachable("unexpected overflowing operator");
13193 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13194 if (CondOpcode == ISD::UMULO)
13195 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13198 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13200 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13202 if (CondOpcode == ISD::UMULO)
13203 Cond = X86Op.getValue(2);
13205 Cond = X86Op.getValue(1);
13207 CC = DAG.getConstant(X86Cond, MVT::i8);
13211 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13212 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13213 if (CondOpc == ISD::OR) {
13214 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13215 // two branches instead of an explicit OR instruction with a
13217 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13218 isX86LogicalCmp(Cmp)) {
13219 CC = Cond.getOperand(0).getOperand(0);
13220 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13221 Chain, Dest, CC, Cmp);
13222 CC = Cond.getOperand(1).getOperand(0);
13226 } else { // ISD::AND
13227 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13228 // two branches instead of an explicit AND instruction with a
13229 // separate test. However, we only do this if this block doesn't
13230 // have a fall-through edge, because this requires an explicit
13231 // jmp when the condition is false.
13232 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13233 isX86LogicalCmp(Cmp) &&
13234 Op.getNode()->hasOneUse()) {
13235 X86::CondCode CCode =
13236 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13237 CCode = X86::GetOppositeBranchCondition(CCode);
13238 CC = DAG.getConstant(CCode, MVT::i8);
13239 SDNode *User = *Op.getNode()->use_begin();
13240 // Look for an unconditional branch following this conditional branch.
13241 // We need this because we need to reverse the successors in order
13242 // to implement FCMP_OEQ.
13243 if (User->getOpcode() == ISD::BR) {
13244 SDValue FalseBB = User->getOperand(1);
13246 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13247 assert(NewBR == User);
13251 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13252 Chain, Dest, CC, Cmp);
13253 X86::CondCode CCode =
13254 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13255 CCode = X86::GetOppositeBranchCondition(CCode);
13256 CC = DAG.getConstant(CCode, MVT::i8);
13262 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13263 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13264 // It should be transformed during dag combiner except when the condition
13265 // is set by a arithmetics with overflow node.
13266 X86::CondCode CCode =
13267 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13268 CCode = X86::GetOppositeBranchCondition(CCode);
13269 CC = DAG.getConstant(CCode, MVT::i8);
13270 Cond = Cond.getOperand(0).getOperand(1);
13272 } else if (Cond.getOpcode() == ISD::SETCC &&
13273 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13274 // For FCMP_OEQ, we can emit
13275 // two branches instead of an explicit AND instruction with a
13276 // separate test. However, we only do this if this block doesn't
13277 // have a fall-through edge, because this requires an explicit
13278 // jmp when the condition is false.
13279 if (Op.getNode()->hasOneUse()) {
13280 SDNode *User = *Op.getNode()->use_begin();
13281 // Look for an unconditional branch following this conditional branch.
13282 // We need this because we need to reverse the successors in order
13283 // to implement FCMP_OEQ.
13284 if (User->getOpcode() == ISD::BR) {
13285 SDValue FalseBB = User->getOperand(1);
13287 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13288 assert(NewBR == User);
13292 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13293 Cond.getOperand(0), Cond.getOperand(1));
13294 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13295 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13296 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13297 Chain, Dest, CC, Cmp);
13298 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13303 } else if (Cond.getOpcode() == ISD::SETCC &&
13304 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13305 // For FCMP_UNE, we can emit
13306 // two branches instead of an explicit AND instruction with a
13307 // separate test. However, we only do this if this block doesn't
13308 // have a fall-through edge, because this requires an explicit
13309 // jmp when the condition is false.
13310 if (Op.getNode()->hasOneUse()) {
13311 SDNode *User = *Op.getNode()->use_begin();
13312 // Look for an unconditional branch following this conditional branch.
13313 // We need this because we need to reverse the successors in order
13314 // to implement FCMP_UNE.
13315 if (User->getOpcode() == ISD::BR) {
13316 SDValue FalseBB = User->getOperand(1);
13318 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13319 assert(NewBR == User);
13322 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13323 Cond.getOperand(0), Cond.getOperand(1));
13324 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13325 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13326 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13327 Chain, Dest, CC, Cmp);
13328 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13338 // Look pass the truncate if the high bits are known zero.
13339 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13340 Cond = Cond.getOperand(0);
13342 // We know the result of AND is compared against zero. Try to match
13344 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13345 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13346 if (NewSetCC.getNode()) {
13347 CC = NewSetCC.getOperand(0);
13348 Cond = NewSetCC.getOperand(1);
13355 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13356 CC = DAG.getConstant(X86Cond, MVT::i8);
13357 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13359 Cond = ConvertCmpIfNecessary(Cond, DAG);
13360 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13361 Chain, Dest, CC, Cond);
13364 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13365 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13366 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13367 // that the guard pages used by the OS virtual memory manager are allocated in
13368 // correct sequence.
13370 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13371 SelectionDAG &DAG) const {
13372 MachineFunction &MF = DAG.getMachineFunction();
13373 bool SplitStack = MF.shouldSplitStack();
13374 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13379 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13380 SDNode* Node = Op.getNode();
13382 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13383 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13384 " not tell us which reg is the stack pointer!");
13385 EVT VT = Node->getValueType(0);
13386 SDValue Tmp1 = SDValue(Node, 0);
13387 SDValue Tmp2 = SDValue(Node, 1);
13388 SDValue Tmp3 = Node->getOperand(2);
13389 SDValue Chain = Tmp1.getOperand(0);
13391 // Chain the dynamic stack allocation so that it doesn't modify the stack
13392 // pointer when other instructions are using the stack.
13393 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13396 SDValue Size = Tmp2.getOperand(1);
13397 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13398 Chain = SP.getValue(1);
13399 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13400 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13401 unsigned StackAlign = TFI.getStackAlignment();
13402 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13403 if (Align > StackAlign)
13404 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13405 DAG.getConstant(-(uint64_t)Align, VT));
13406 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13408 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13409 DAG.getIntPtrConstant(0, true), SDValue(),
13412 SDValue Ops[2] = { Tmp1, Tmp2 };
13413 return DAG.getMergeValues(Ops, dl);
13417 SDValue Chain = Op.getOperand(0);
13418 SDValue Size = Op.getOperand(1);
13419 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13420 EVT VT = Op.getNode()->getValueType(0);
13422 bool Is64Bit = Subtarget->is64Bit();
13423 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13426 MachineRegisterInfo &MRI = MF.getRegInfo();
13429 // The 64 bit implementation of segmented stacks needs to clobber both r10
13430 // r11. This makes it impossible to use it along with nested parameters.
13431 const Function *F = MF.getFunction();
13433 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13435 if (I->hasNestAttr())
13436 report_fatal_error("Cannot use segmented stacks with functions that "
13437 "have nested arguments.");
13440 const TargetRegisterClass *AddrRegClass =
13441 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13442 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13443 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13444 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13445 DAG.getRegister(Vreg, SPTy));
13446 SDValue Ops1[2] = { Value, Chain };
13447 return DAG.getMergeValues(Ops1, dl);
13450 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13452 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13453 Flag = Chain.getValue(1);
13454 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13456 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13458 const X86RegisterInfo *RegInfo =
13459 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13460 unsigned SPReg = RegInfo->getStackRegister();
13461 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13462 Chain = SP.getValue(1);
13465 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13466 DAG.getConstant(-(uint64_t)Align, VT));
13467 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13470 SDValue Ops1[2] = { SP, Chain };
13471 return DAG.getMergeValues(Ops1, dl);
13475 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13476 MachineFunction &MF = DAG.getMachineFunction();
13477 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13479 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13482 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13483 // vastart just stores the address of the VarArgsFrameIndex slot into the
13484 // memory location argument.
13485 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13487 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13488 MachinePointerInfo(SV), false, false, 0);
13492 // gp_offset (0 - 6 * 8)
13493 // fp_offset (48 - 48 + 8 * 16)
13494 // overflow_arg_area (point to parameters coming in memory).
13496 SmallVector<SDValue, 8> MemOps;
13497 SDValue FIN = Op.getOperand(1);
13499 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13500 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13502 FIN, MachinePointerInfo(SV), false, false, 0);
13503 MemOps.push_back(Store);
13506 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13507 FIN, DAG.getIntPtrConstant(4));
13508 Store = DAG.getStore(Op.getOperand(0), DL,
13509 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13511 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13512 MemOps.push_back(Store);
13514 // Store ptr to overflow_arg_area
13515 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13516 FIN, DAG.getIntPtrConstant(4));
13517 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13519 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13520 MachinePointerInfo(SV, 8),
13522 MemOps.push_back(Store);
13524 // Store ptr to reg_save_area.
13525 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13526 FIN, DAG.getIntPtrConstant(8));
13527 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13529 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13530 MachinePointerInfo(SV, 16), false, false, 0);
13531 MemOps.push_back(Store);
13532 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13535 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13536 assert(Subtarget->is64Bit() &&
13537 "LowerVAARG only handles 64-bit va_arg!");
13538 assert((Subtarget->isTargetLinux() ||
13539 Subtarget->isTargetDarwin()) &&
13540 "Unhandled target in LowerVAARG");
13541 assert(Op.getNode()->getNumOperands() == 4);
13542 SDValue Chain = Op.getOperand(0);
13543 SDValue SrcPtr = Op.getOperand(1);
13544 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13545 unsigned Align = Op.getConstantOperandVal(3);
13548 EVT ArgVT = Op.getNode()->getValueType(0);
13549 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13550 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13553 // Decide which area this value should be read from.
13554 // TODO: Implement the AMD64 ABI in its entirety. This simple
13555 // selection mechanism works only for the basic types.
13556 if (ArgVT == MVT::f80) {
13557 llvm_unreachable("va_arg for f80 not yet implemented");
13558 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13559 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13560 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13561 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13563 llvm_unreachable("Unhandled argument type in LowerVAARG");
13566 if (ArgMode == 2) {
13567 // Sanity Check: Make sure using fp_offset makes sense.
13568 assert(!DAG.getTarget().Options.UseSoftFloat &&
13569 !(DAG.getMachineFunction()
13570 .getFunction()->getAttributes()
13571 .hasAttribute(AttributeSet::FunctionIndex,
13572 Attribute::NoImplicitFloat)) &&
13573 Subtarget->hasSSE1());
13576 // Insert VAARG_64 node into the DAG
13577 // VAARG_64 returns two values: Variable Argument Address, Chain
13578 SmallVector<SDValue, 11> InstOps;
13579 InstOps.push_back(Chain);
13580 InstOps.push_back(SrcPtr);
13581 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13582 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13583 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13584 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13585 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13586 VTs, InstOps, MVT::i64,
13587 MachinePointerInfo(SV),
13589 /*Volatile=*/false,
13591 /*WriteMem=*/true);
13592 Chain = VAARG.getValue(1);
13594 // Load the next argument and return it
13595 return DAG.getLoad(ArgVT, dl,
13598 MachinePointerInfo(),
13599 false, false, false, 0);
13602 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13603 SelectionDAG &DAG) {
13604 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13605 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13606 SDValue Chain = Op.getOperand(0);
13607 SDValue DstPtr = Op.getOperand(1);
13608 SDValue SrcPtr = Op.getOperand(2);
13609 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13610 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13613 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13614 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13616 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13619 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13620 // amount is a constant. Takes immediate version of shift as input.
13621 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13622 SDValue SrcOp, uint64_t ShiftAmt,
13623 SelectionDAG &DAG) {
13624 MVT ElementType = VT.getVectorElementType();
13626 // Fold this packed shift into its first operand if ShiftAmt is 0.
13630 // Check for ShiftAmt >= element width
13631 if (ShiftAmt >= ElementType.getSizeInBits()) {
13632 if (Opc == X86ISD::VSRAI)
13633 ShiftAmt = ElementType.getSizeInBits() - 1;
13635 return DAG.getConstant(0, VT);
13638 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13639 && "Unknown target vector shift-by-constant node");
13641 // Fold this packed vector shift into a build vector if SrcOp is a
13642 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13643 if (VT == SrcOp.getSimpleValueType() &&
13644 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13645 SmallVector<SDValue, 8> Elts;
13646 unsigned NumElts = SrcOp->getNumOperands();
13647 ConstantSDNode *ND;
13650 default: llvm_unreachable(nullptr);
13651 case X86ISD::VSHLI:
13652 for (unsigned i=0; i!=NumElts; ++i) {
13653 SDValue CurrentOp = SrcOp->getOperand(i);
13654 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13655 Elts.push_back(CurrentOp);
13658 ND = cast<ConstantSDNode>(CurrentOp);
13659 const APInt &C = ND->getAPIntValue();
13660 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13663 case X86ISD::VSRLI:
13664 for (unsigned i=0; i!=NumElts; ++i) {
13665 SDValue CurrentOp = SrcOp->getOperand(i);
13666 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13667 Elts.push_back(CurrentOp);
13670 ND = cast<ConstantSDNode>(CurrentOp);
13671 const APInt &C = ND->getAPIntValue();
13672 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13675 case X86ISD::VSRAI:
13676 for (unsigned i=0; i!=NumElts; ++i) {
13677 SDValue CurrentOp = SrcOp->getOperand(i);
13678 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13679 Elts.push_back(CurrentOp);
13682 ND = cast<ConstantSDNode>(CurrentOp);
13683 const APInt &C = ND->getAPIntValue();
13684 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13689 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13692 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13695 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13696 // may or may not be a constant. Takes immediate version of shift as input.
13697 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13698 SDValue SrcOp, SDValue ShAmt,
13699 SelectionDAG &DAG) {
13700 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13702 // Catch shift-by-constant.
13703 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13704 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13705 CShAmt->getZExtValue(), DAG);
13707 // Change opcode to non-immediate version
13709 default: llvm_unreachable("Unknown target vector shift node");
13710 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13711 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13712 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13715 // Need to build a vector containing shift amount
13716 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13719 ShOps[1] = DAG.getConstant(0, MVT::i32);
13720 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13721 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13723 // The return type has to be a 128-bit type with the same element
13724 // type as the input type.
13725 MVT EltVT = VT.getVectorElementType();
13726 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13728 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13729 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13732 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13734 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13736 default: return SDValue(); // Don't custom lower most intrinsics.
13737 // Comparison intrinsics.
13738 case Intrinsic::x86_sse_comieq_ss:
13739 case Intrinsic::x86_sse_comilt_ss:
13740 case Intrinsic::x86_sse_comile_ss:
13741 case Intrinsic::x86_sse_comigt_ss:
13742 case Intrinsic::x86_sse_comige_ss:
13743 case Intrinsic::x86_sse_comineq_ss:
13744 case Intrinsic::x86_sse_ucomieq_ss:
13745 case Intrinsic::x86_sse_ucomilt_ss:
13746 case Intrinsic::x86_sse_ucomile_ss:
13747 case Intrinsic::x86_sse_ucomigt_ss:
13748 case Intrinsic::x86_sse_ucomige_ss:
13749 case Intrinsic::x86_sse_ucomineq_ss:
13750 case Intrinsic::x86_sse2_comieq_sd:
13751 case Intrinsic::x86_sse2_comilt_sd:
13752 case Intrinsic::x86_sse2_comile_sd:
13753 case Intrinsic::x86_sse2_comigt_sd:
13754 case Intrinsic::x86_sse2_comige_sd:
13755 case Intrinsic::x86_sse2_comineq_sd:
13756 case Intrinsic::x86_sse2_ucomieq_sd:
13757 case Intrinsic::x86_sse2_ucomilt_sd:
13758 case Intrinsic::x86_sse2_ucomile_sd:
13759 case Intrinsic::x86_sse2_ucomigt_sd:
13760 case Intrinsic::x86_sse2_ucomige_sd:
13761 case Intrinsic::x86_sse2_ucomineq_sd: {
13765 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13766 case Intrinsic::x86_sse_comieq_ss:
13767 case Intrinsic::x86_sse2_comieq_sd:
13768 Opc = X86ISD::COMI;
13771 case Intrinsic::x86_sse_comilt_ss:
13772 case Intrinsic::x86_sse2_comilt_sd:
13773 Opc = X86ISD::COMI;
13776 case Intrinsic::x86_sse_comile_ss:
13777 case Intrinsic::x86_sse2_comile_sd:
13778 Opc = X86ISD::COMI;
13781 case Intrinsic::x86_sse_comigt_ss:
13782 case Intrinsic::x86_sse2_comigt_sd:
13783 Opc = X86ISD::COMI;
13786 case Intrinsic::x86_sse_comige_ss:
13787 case Intrinsic::x86_sse2_comige_sd:
13788 Opc = X86ISD::COMI;
13791 case Intrinsic::x86_sse_comineq_ss:
13792 case Intrinsic::x86_sse2_comineq_sd:
13793 Opc = X86ISD::COMI;
13796 case Intrinsic::x86_sse_ucomieq_ss:
13797 case Intrinsic::x86_sse2_ucomieq_sd:
13798 Opc = X86ISD::UCOMI;
13801 case Intrinsic::x86_sse_ucomilt_ss:
13802 case Intrinsic::x86_sse2_ucomilt_sd:
13803 Opc = X86ISD::UCOMI;
13806 case Intrinsic::x86_sse_ucomile_ss:
13807 case Intrinsic::x86_sse2_ucomile_sd:
13808 Opc = X86ISD::UCOMI;
13811 case Intrinsic::x86_sse_ucomigt_ss:
13812 case Intrinsic::x86_sse2_ucomigt_sd:
13813 Opc = X86ISD::UCOMI;
13816 case Intrinsic::x86_sse_ucomige_ss:
13817 case Intrinsic::x86_sse2_ucomige_sd:
13818 Opc = X86ISD::UCOMI;
13821 case Intrinsic::x86_sse_ucomineq_ss:
13822 case Intrinsic::x86_sse2_ucomineq_sd:
13823 Opc = X86ISD::UCOMI;
13828 SDValue LHS = Op.getOperand(1);
13829 SDValue RHS = Op.getOperand(2);
13830 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13831 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13832 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13833 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13834 DAG.getConstant(X86CC, MVT::i8), Cond);
13835 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13838 // Arithmetic intrinsics.
13839 case Intrinsic::x86_sse2_pmulu_dq:
13840 case Intrinsic::x86_avx2_pmulu_dq:
13841 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13842 Op.getOperand(1), Op.getOperand(2));
13844 case Intrinsic::x86_sse41_pmuldq:
13845 case Intrinsic::x86_avx2_pmul_dq:
13846 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13847 Op.getOperand(1), Op.getOperand(2));
13849 case Intrinsic::x86_sse2_pmulhu_w:
13850 case Intrinsic::x86_avx2_pmulhu_w:
13851 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13852 Op.getOperand(1), Op.getOperand(2));
13854 case Intrinsic::x86_sse2_pmulh_w:
13855 case Intrinsic::x86_avx2_pmulh_w:
13856 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13857 Op.getOperand(1), Op.getOperand(2));
13859 // SSE2/AVX2 sub with unsigned saturation intrinsics
13860 case Intrinsic::x86_sse2_psubus_b:
13861 case Intrinsic::x86_sse2_psubus_w:
13862 case Intrinsic::x86_avx2_psubus_b:
13863 case Intrinsic::x86_avx2_psubus_w:
13864 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13865 Op.getOperand(1), Op.getOperand(2));
13867 // SSE3/AVX horizontal add/sub intrinsics
13868 case Intrinsic::x86_sse3_hadd_ps:
13869 case Intrinsic::x86_sse3_hadd_pd:
13870 case Intrinsic::x86_avx_hadd_ps_256:
13871 case Intrinsic::x86_avx_hadd_pd_256:
13872 case Intrinsic::x86_sse3_hsub_ps:
13873 case Intrinsic::x86_sse3_hsub_pd:
13874 case Intrinsic::x86_avx_hsub_ps_256:
13875 case Intrinsic::x86_avx_hsub_pd_256:
13876 case Intrinsic::x86_ssse3_phadd_w_128:
13877 case Intrinsic::x86_ssse3_phadd_d_128:
13878 case Intrinsic::x86_avx2_phadd_w:
13879 case Intrinsic::x86_avx2_phadd_d:
13880 case Intrinsic::x86_ssse3_phsub_w_128:
13881 case Intrinsic::x86_ssse3_phsub_d_128:
13882 case Intrinsic::x86_avx2_phsub_w:
13883 case Intrinsic::x86_avx2_phsub_d: {
13886 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13887 case Intrinsic::x86_sse3_hadd_ps:
13888 case Intrinsic::x86_sse3_hadd_pd:
13889 case Intrinsic::x86_avx_hadd_ps_256:
13890 case Intrinsic::x86_avx_hadd_pd_256:
13891 Opcode = X86ISD::FHADD;
13893 case Intrinsic::x86_sse3_hsub_ps:
13894 case Intrinsic::x86_sse3_hsub_pd:
13895 case Intrinsic::x86_avx_hsub_ps_256:
13896 case Intrinsic::x86_avx_hsub_pd_256:
13897 Opcode = X86ISD::FHSUB;
13899 case Intrinsic::x86_ssse3_phadd_w_128:
13900 case Intrinsic::x86_ssse3_phadd_d_128:
13901 case Intrinsic::x86_avx2_phadd_w:
13902 case Intrinsic::x86_avx2_phadd_d:
13903 Opcode = X86ISD::HADD;
13905 case Intrinsic::x86_ssse3_phsub_w_128:
13906 case Intrinsic::x86_ssse3_phsub_d_128:
13907 case Intrinsic::x86_avx2_phsub_w:
13908 case Intrinsic::x86_avx2_phsub_d:
13909 Opcode = X86ISD::HSUB;
13912 return DAG.getNode(Opcode, dl, Op.getValueType(),
13913 Op.getOperand(1), Op.getOperand(2));
13916 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13917 case Intrinsic::x86_sse2_pmaxu_b:
13918 case Intrinsic::x86_sse41_pmaxuw:
13919 case Intrinsic::x86_sse41_pmaxud:
13920 case Intrinsic::x86_avx2_pmaxu_b:
13921 case Intrinsic::x86_avx2_pmaxu_w:
13922 case Intrinsic::x86_avx2_pmaxu_d:
13923 case Intrinsic::x86_sse2_pminu_b:
13924 case Intrinsic::x86_sse41_pminuw:
13925 case Intrinsic::x86_sse41_pminud:
13926 case Intrinsic::x86_avx2_pminu_b:
13927 case Intrinsic::x86_avx2_pminu_w:
13928 case Intrinsic::x86_avx2_pminu_d:
13929 case Intrinsic::x86_sse41_pmaxsb:
13930 case Intrinsic::x86_sse2_pmaxs_w:
13931 case Intrinsic::x86_sse41_pmaxsd:
13932 case Intrinsic::x86_avx2_pmaxs_b:
13933 case Intrinsic::x86_avx2_pmaxs_w:
13934 case Intrinsic::x86_avx2_pmaxs_d:
13935 case Intrinsic::x86_sse41_pminsb:
13936 case Intrinsic::x86_sse2_pmins_w:
13937 case Intrinsic::x86_sse41_pminsd:
13938 case Intrinsic::x86_avx2_pmins_b:
13939 case Intrinsic::x86_avx2_pmins_w:
13940 case Intrinsic::x86_avx2_pmins_d: {
13943 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13944 case Intrinsic::x86_sse2_pmaxu_b:
13945 case Intrinsic::x86_sse41_pmaxuw:
13946 case Intrinsic::x86_sse41_pmaxud:
13947 case Intrinsic::x86_avx2_pmaxu_b:
13948 case Intrinsic::x86_avx2_pmaxu_w:
13949 case Intrinsic::x86_avx2_pmaxu_d:
13950 Opcode = X86ISD::UMAX;
13952 case Intrinsic::x86_sse2_pminu_b:
13953 case Intrinsic::x86_sse41_pminuw:
13954 case Intrinsic::x86_sse41_pminud:
13955 case Intrinsic::x86_avx2_pminu_b:
13956 case Intrinsic::x86_avx2_pminu_w:
13957 case Intrinsic::x86_avx2_pminu_d:
13958 Opcode = X86ISD::UMIN;
13960 case Intrinsic::x86_sse41_pmaxsb:
13961 case Intrinsic::x86_sse2_pmaxs_w:
13962 case Intrinsic::x86_sse41_pmaxsd:
13963 case Intrinsic::x86_avx2_pmaxs_b:
13964 case Intrinsic::x86_avx2_pmaxs_w:
13965 case Intrinsic::x86_avx2_pmaxs_d:
13966 Opcode = X86ISD::SMAX;
13968 case Intrinsic::x86_sse41_pminsb:
13969 case Intrinsic::x86_sse2_pmins_w:
13970 case Intrinsic::x86_sse41_pminsd:
13971 case Intrinsic::x86_avx2_pmins_b:
13972 case Intrinsic::x86_avx2_pmins_w:
13973 case Intrinsic::x86_avx2_pmins_d:
13974 Opcode = X86ISD::SMIN;
13977 return DAG.getNode(Opcode, dl, Op.getValueType(),
13978 Op.getOperand(1), Op.getOperand(2));
13981 // SSE/SSE2/AVX floating point max/min intrinsics.
13982 case Intrinsic::x86_sse_max_ps:
13983 case Intrinsic::x86_sse2_max_pd:
13984 case Intrinsic::x86_avx_max_ps_256:
13985 case Intrinsic::x86_avx_max_pd_256:
13986 case Intrinsic::x86_sse_min_ps:
13987 case Intrinsic::x86_sse2_min_pd:
13988 case Intrinsic::x86_avx_min_ps_256:
13989 case Intrinsic::x86_avx_min_pd_256: {
13992 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13993 case Intrinsic::x86_sse_max_ps:
13994 case Intrinsic::x86_sse2_max_pd:
13995 case Intrinsic::x86_avx_max_ps_256:
13996 case Intrinsic::x86_avx_max_pd_256:
13997 Opcode = X86ISD::FMAX;
13999 case Intrinsic::x86_sse_min_ps:
14000 case Intrinsic::x86_sse2_min_pd:
14001 case Intrinsic::x86_avx_min_ps_256:
14002 case Intrinsic::x86_avx_min_pd_256:
14003 Opcode = X86ISD::FMIN;
14006 return DAG.getNode(Opcode, dl, Op.getValueType(),
14007 Op.getOperand(1), Op.getOperand(2));
14010 // AVX2 variable shift intrinsics
14011 case Intrinsic::x86_avx2_psllv_d:
14012 case Intrinsic::x86_avx2_psllv_q:
14013 case Intrinsic::x86_avx2_psllv_d_256:
14014 case Intrinsic::x86_avx2_psllv_q_256:
14015 case Intrinsic::x86_avx2_psrlv_d:
14016 case Intrinsic::x86_avx2_psrlv_q:
14017 case Intrinsic::x86_avx2_psrlv_d_256:
14018 case Intrinsic::x86_avx2_psrlv_q_256:
14019 case Intrinsic::x86_avx2_psrav_d:
14020 case Intrinsic::x86_avx2_psrav_d_256: {
14023 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14024 case Intrinsic::x86_avx2_psllv_d:
14025 case Intrinsic::x86_avx2_psllv_q:
14026 case Intrinsic::x86_avx2_psllv_d_256:
14027 case Intrinsic::x86_avx2_psllv_q_256:
14030 case Intrinsic::x86_avx2_psrlv_d:
14031 case Intrinsic::x86_avx2_psrlv_q:
14032 case Intrinsic::x86_avx2_psrlv_d_256:
14033 case Intrinsic::x86_avx2_psrlv_q_256:
14036 case Intrinsic::x86_avx2_psrav_d:
14037 case Intrinsic::x86_avx2_psrav_d_256:
14041 return DAG.getNode(Opcode, dl, Op.getValueType(),
14042 Op.getOperand(1), Op.getOperand(2));
14045 case Intrinsic::x86_sse2_packssdw_128:
14046 case Intrinsic::x86_sse2_packsswb_128:
14047 case Intrinsic::x86_avx2_packssdw:
14048 case Intrinsic::x86_avx2_packsswb:
14049 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14050 Op.getOperand(1), Op.getOperand(2));
14052 case Intrinsic::x86_sse2_packuswb_128:
14053 case Intrinsic::x86_sse41_packusdw:
14054 case Intrinsic::x86_avx2_packuswb:
14055 case Intrinsic::x86_avx2_packusdw:
14056 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14057 Op.getOperand(1), Op.getOperand(2));
14059 case Intrinsic::x86_ssse3_pshuf_b_128:
14060 case Intrinsic::x86_avx2_pshuf_b:
14061 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14062 Op.getOperand(1), Op.getOperand(2));
14064 case Intrinsic::x86_sse2_pshuf_d:
14065 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14066 Op.getOperand(1), Op.getOperand(2));
14068 case Intrinsic::x86_sse2_pshufl_w:
14069 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14070 Op.getOperand(1), Op.getOperand(2));
14072 case Intrinsic::x86_sse2_pshufh_w:
14073 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14074 Op.getOperand(1), Op.getOperand(2));
14076 case Intrinsic::x86_ssse3_psign_b_128:
14077 case Intrinsic::x86_ssse3_psign_w_128:
14078 case Intrinsic::x86_ssse3_psign_d_128:
14079 case Intrinsic::x86_avx2_psign_b:
14080 case Intrinsic::x86_avx2_psign_w:
14081 case Intrinsic::x86_avx2_psign_d:
14082 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14083 Op.getOperand(1), Op.getOperand(2));
14085 case Intrinsic::x86_sse41_insertps:
14086 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14087 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14089 case Intrinsic::x86_avx_vperm2f128_ps_256:
14090 case Intrinsic::x86_avx_vperm2f128_pd_256:
14091 case Intrinsic::x86_avx_vperm2f128_si_256:
14092 case Intrinsic::x86_avx2_vperm2i128:
14093 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14094 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14096 case Intrinsic::x86_avx2_permd:
14097 case Intrinsic::x86_avx2_permps:
14098 // Operands intentionally swapped. Mask is last operand to intrinsic,
14099 // but second operand for node/instruction.
14100 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14101 Op.getOperand(2), Op.getOperand(1));
14103 case Intrinsic::x86_sse_sqrt_ps:
14104 case Intrinsic::x86_sse2_sqrt_pd:
14105 case Intrinsic::x86_avx_sqrt_ps_256:
14106 case Intrinsic::x86_avx_sqrt_pd_256:
14107 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14109 // ptest and testp intrinsics. The intrinsic these come from are designed to
14110 // return an integer value, not just an instruction so lower it to the ptest
14111 // or testp pattern and a setcc for the result.
14112 case Intrinsic::x86_sse41_ptestz:
14113 case Intrinsic::x86_sse41_ptestc:
14114 case Intrinsic::x86_sse41_ptestnzc:
14115 case Intrinsic::x86_avx_ptestz_256:
14116 case Intrinsic::x86_avx_ptestc_256:
14117 case Intrinsic::x86_avx_ptestnzc_256:
14118 case Intrinsic::x86_avx_vtestz_ps:
14119 case Intrinsic::x86_avx_vtestc_ps:
14120 case Intrinsic::x86_avx_vtestnzc_ps:
14121 case Intrinsic::x86_avx_vtestz_pd:
14122 case Intrinsic::x86_avx_vtestc_pd:
14123 case Intrinsic::x86_avx_vtestnzc_pd:
14124 case Intrinsic::x86_avx_vtestz_ps_256:
14125 case Intrinsic::x86_avx_vtestc_ps_256:
14126 case Intrinsic::x86_avx_vtestnzc_ps_256:
14127 case Intrinsic::x86_avx_vtestz_pd_256:
14128 case Intrinsic::x86_avx_vtestc_pd_256:
14129 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14130 bool IsTestPacked = false;
14133 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14134 case Intrinsic::x86_avx_vtestz_ps:
14135 case Intrinsic::x86_avx_vtestz_pd:
14136 case Intrinsic::x86_avx_vtestz_ps_256:
14137 case Intrinsic::x86_avx_vtestz_pd_256:
14138 IsTestPacked = true; // Fallthrough
14139 case Intrinsic::x86_sse41_ptestz:
14140 case Intrinsic::x86_avx_ptestz_256:
14142 X86CC = X86::COND_E;
14144 case Intrinsic::x86_avx_vtestc_ps:
14145 case Intrinsic::x86_avx_vtestc_pd:
14146 case Intrinsic::x86_avx_vtestc_ps_256:
14147 case Intrinsic::x86_avx_vtestc_pd_256:
14148 IsTestPacked = true; // Fallthrough
14149 case Intrinsic::x86_sse41_ptestc:
14150 case Intrinsic::x86_avx_ptestc_256:
14152 X86CC = X86::COND_B;
14154 case Intrinsic::x86_avx_vtestnzc_ps:
14155 case Intrinsic::x86_avx_vtestnzc_pd:
14156 case Intrinsic::x86_avx_vtestnzc_ps_256:
14157 case Intrinsic::x86_avx_vtestnzc_pd_256:
14158 IsTestPacked = true; // Fallthrough
14159 case Intrinsic::x86_sse41_ptestnzc:
14160 case Intrinsic::x86_avx_ptestnzc_256:
14162 X86CC = X86::COND_A;
14166 SDValue LHS = Op.getOperand(1);
14167 SDValue RHS = Op.getOperand(2);
14168 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14169 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14170 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14171 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14172 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14174 case Intrinsic::x86_avx512_kortestz_w:
14175 case Intrinsic::x86_avx512_kortestc_w: {
14176 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14177 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14178 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14179 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14180 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14181 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14182 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14185 // SSE/AVX shift intrinsics
14186 case Intrinsic::x86_sse2_psll_w:
14187 case Intrinsic::x86_sse2_psll_d:
14188 case Intrinsic::x86_sse2_psll_q:
14189 case Intrinsic::x86_avx2_psll_w:
14190 case Intrinsic::x86_avx2_psll_d:
14191 case Intrinsic::x86_avx2_psll_q:
14192 case Intrinsic::x86_sse2_psrl_w:
14193 case Intrinsic::x86_sse2_psrl_d:
14194 case Intrinsic::x86_sse2_psrl_q:
14195 case Intrinsic::x86_avx2_psrl_w:
14196 case Intrinsic::x86_avx2_psrl_d:
14197 case Intrinsic::x86_avx2_psrl_q:
14198 case Intrinsic::x86_sse2_psra_w:
14199 case Intrinsic::x86_sse2_psra_d:
14200 case Intrinsic::x86_avx2_psra_w:
14201 case Intrinsic::x86_avx2_psra_d: {
14204 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14205 case Intrinsic::x86_sse2_psll_w:
14206 case Intrinsic::x86_sse2_psll_d:
14207 case Intrinsic::x86_sse2_psll_q:
14208 case Intrinsic::x86_avx2_psll_w:
14209 case Intrinsic::x86_avx2_psll_d:
14210 case Intrinsic::x86_avx2_psll_q:
14211 Opcode = X86ISD::VSHL;
14213 case Intrinsic::x86_sse2_psrl_w:
14214 case Intrinsic::x86_sse2_psrl_d:
14215 case Intrinsic::x86_sse2_psrl_q:
14216 case Intrinsic::x86_avx2_psrl_w:
14217 case Intrinsic::x86_avx2_psrl_d:
14218 case Intrinsic::x86_avx2_psrl_q:
14219 Opcode = X86ISD::VSRL;
14221 case Intrinsic::x86_sse2_psra_w:
14222 case Intrinsic::x86_sse2_psra_d:
14223 case Intrinsic::x86_avx2_psra_w:
14224 case Intrinsic::x86_avx2_psra_d:
14225 Opcode = X86ISD::VSRA;
14228 return DAG.getNode(Opcode, dl, Op.getValueType(),
14229 Op.getOperand(1), Op.getOperand(2));
14232 // SSE/AVX immediate shift intrinsics
14233 case Intrinsic::x86_sse2_pslli_w:
14234 case Intrinsic::x86_sse2_pslli_d:
14235 case Intrinsic::x86_sse2_pslli_q:
14236 case Intrinsic::x86_avx2_pslli_w:
14237 case Intrinsic::x86_avx2_pslli_d:
14238 case Intrinsic::x86_avx2_pslli_q:
14239 case Intrinsic::x86_sse2_psrli_w:
14240 case Intrinsic::x86_sse2_psrli_d:
14241 case Intrinsic::x86_sse2_psrli_q:
14242 case Intrinsic::x86_avx2_psrli_w:
14243 case Intrinsic::x86_avx2_psrli_d:
14244 case Intrinsic::x86_avx2_psrli_q:
14245 case Intrinsic::x86_sse2_psrai_w:
14246 case Intrinsic::x86_sse2_psrai_d:
14247 case Intrinsic::x86_avx2_psrai_w:
14248 case Intrinsic::x86_avx2_psrai_d: {
14251 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14252 case Intrinsic::x86_sse2_pslli_w:
14253 case Intrinsic::x86_sse2_pslli_d:
14254 case Intrinsic::x86_sse2_pslli_q:
14255 case Intrinsic::x86_avx2_pslli_w:
14256 case Intrinsic::x86_avx2_pslli_d:
14257 case Intrinsic::x86_avx2_pslli_q:
14258 Opcode = X86ISD::VSHLI;
14260 case Intrinsic::x86_sse2_psrli_w:
14261 case Intrinsic::x86_sse2_psrli_d:
14262 case Intrinsic::x86_sse2_psrli_q:
14263 case Intrinsic::x86_avx2_psrli_w:
14264 case Intrinsic::x86_avx2_psrli_d:
14265 case Intrinsic::x86_avx2_psrli_q:
14266 Opcode = X86ISD::VSRLI;
14268 case Intrinsic::x86_sse2_psrai_w:
14269 case Intrinsic::x86_sse2_psrai_d:
14270 case Intrinsic::x86_avx2_psrai_w:
14271 case Intrinsic::x86_avx2_psrai_d:
14272 Opcode = X86ISD::VSRAI;
14275 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14276 Op.getOperand(1), Op.getOperand(2), DAG);
14279 case Intrinsic::x86_sse42_pcmpistria128:
14280 case Intrinsic::x86_sse42_pcmpestria128:
14281 case Intrinsic::x86_sse42_pcmpistric128:
14282 case Intrinsic::x86_sse42_pcmpestric128:
14283 case Intrinsic::x86_sse42_pcmpistrio128:
14284 case Intrinsic::x86_sse42_pcmpestrio128:
14285 case Intrinsic::x86_sse42_pcmpistris128:
14286 case Intrinsic::x86_sse42_pcmpestris128:
14287 case Intrinsic::x86_sse42_pcmpistriz128:
14288 case Intrinsic::x86_sse42_pcmpestriz128: {
14292 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14293 case Intrinsic::x86_sse42_pcmpistria128:
14294 Opcode = X86ISD::PCMPISTRI;
14295 X86CC = X86::COND_A;
14297 case Intrinsic::x86_sse42_pcmpestria128:
14298 Opcode = X86ISD::PCMPESTRI;
14299 X86CC = X86::COND_A;
14301 case Intrinsic::x86_sse42_pcmpistric128:
14302 Opcode = X86ISD::PCMPISTRI;
14303 X86CC = X86::COND_B;
14305 case Intrinsic::x86_sse42_pcmpestric128:
14306 Opcode = X86ISD::PCMPESTRI;
14307 X86CC = X86::COND_B;
14309 case Intrinsic::x86_sse42_pcmpistrio128:
14310 Opcode = X86ISD::PCMPISTRI;
14311 X86CC = X86::COND_O;
14313 case Intrinsic::x86_sse42_pcmpestrio128:
14314 Opcode = X86ISD::PCMPESTRI;
14315 X86CC = X86::COND_O;
14317 case Intrinsic::x86_sse42_pcmpistris128:
14318 Opcode = X86ISD::PCMPISTRI;
14319 X86CC = X86::COND_S;
14321 case Intrinsic::x86_sse42_pcmpestris128:
14322 Opcode = X86ISD::PCMPESTRI;
14323 X86CC = X86::COND_S;
14325 case Intrinsic::x86_sse42_pcmpistriz128:
14326 Opcode = X86ISD::PCMPISTRI;
14327 X86CC = X86::COND_E;
14329 case Intrinsic::x86_sse42_pcmpestriz128:
14330 Opcode = X86ISD::PCMPESTRI;
14331 X86CC = X86::COND_E;
14334 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14335 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14336 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14337 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14338 DAG.getConstant(X86CC, MVT::i8),
14339 SDValue(PCMP.getNode(), 1));
14340 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14343 case Intrinsic::x86_sse42_pcmpistri128:
14344 case Intrinsic::x86_sse42_pcmpestri128: {
14346 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14347 Opcode = X86ISD::PCMPISTRI;
14349 Opcode = X86ISD::PCMPESTRI;
14351 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14352 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14353 return DAG.getNode(Opcode, dl, VTs, NewOps);
14355 case Intrinsic::x86_fma_vfmadd_ps:
14356 case Intrinsic::x86_fma_vfmadd_pd:
14357 case Intrinsic::x86_fma_vfmsub_ps:
14358 case Intrinsic::x86_fma_vfmsub_pd:
14359 case Intrinsic::x86_fma_vfnmadd_ps:
14360 case Intrinsic::x86_fma_vfnmadd_pd:
14361 case Intrinsic::x86_fma_vfnmsub_ps:
14362 case Intrinsic::x86_fma_vfnmsub_pd:
14363 case Intrinsic::x86_fma_vfmaddsub_ps:
14364 case Intrinsic::x86_fma_vfmaddsub_pd:
14365 case Intrinsic::x86_fma_vfmsubadd_ps:
14366 case Intrinsic::x86_fma_vfmsubadd_pd:
14367 case Intrinsic::x86_fma_vfmadd_ps_256:
14368 case Intrinsic::x86_fma_vfmadd_pd_256:
14369 case Intrinsic::x86_fma_vfmsub_ps_256:
14370 case Intrinsic::x86_fma_vfmsub_pd_256:
14371 case Intrinsic::x86_fma_vfnmadd_ps_256:
14372 case Intrinsic::x86_fma_vfnmadd_pd_256:
14373 case Intrinsic::x86_fma_vfnmsub_ps_256:
14374 case Intrinsic::x86_fma_vfnmsub_pd_256:
14375 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14376 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14377 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14378 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14379 case Intrinsic::x86_fma_vfmadd_ps_512:
14380 case Intrinsic::x86_fma_vfmadd_pd_512:
14381 case Intrinsic::x86_fma_vfmsub_ps_512:
14382 case Intrinsic::x86_fma_vfmsub_pd_512:
14383 case Intrinsic::x86_fma_vfnmadd_ps_512:
14384 case Intrinsic::x86_fma_vfnmadd_pd_512:
14385 case Intrinsic::x86_fma_vfnmsub_ps_512:
14386 case Intrinsic::x86_fma_vfnmsub_pd_512:
14387 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14388 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14389 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14390 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14393 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14394 case Intrinsic::x86_fma_vfmadd_ps:
14395 case Intrinsic::x86_fma_vfmadd_pd:
14396 case Intrinsic::x86_fma_vfmadd_ps_256:
14397 case Intrinsic::x86_fma_vfmadd_pd_256:
14398 case Intrinsic::x86_fma_vfmadd_ps_512:
14399 case Intrinsic::x86_fma_vfmadd_pd_512:
14400 Opc = X86ISD::FMADD;
14402 case Intrinsic::x86_fma_vfmsub_ps:
14403 case Intrinsic::x86_fma_vfmsub_pd:
14404 case Intrinsic::x86_fma_vfmsub_ps_256:
14405 case Intrinsic::x86_fma_vfmsub_pd_256:
14406 case Intrinsic::x86_fma_vfmsub_ps_512:
14407 case Intrinsic::x86_fma_vfmsub_pd_512:
14408 Opc = X86ISD::FMSUB;
14410 case Intrinsic::x86_fma_vfnmadd_ps:
14411 case Intrinsic::x86_fma_vfnmadd_pd:
14412 case Intrinsic::x86_fma_vfnmadd_ps_256:
14413 case Intrinsic::x86_fma_vfnmadd_pd_256:
14414 case Intrinsic::x86_fma_vfnmadd_ps_512:
14415 case Intrinsic::x86_fma_vfnmadd_pd_512:
14416 Opc = X86ISD::FNMADD;
14418 case Intrinsic::x86_fma_vfnmsub_ps:
14419 case Intrinsic::x86_fma_vfnmsub_pd:
14420 case Intrinsic::x86_fma_vfnmsub_ps_256:
14421 case Intrinsic::x86_fma_vfnmsub_pd_256:
14422 case Intrinsic::x86_fma_vfnmsub_ps_512:
14423 case Intrinsic::x86_fma_vfnmsub_pd_512:
14424 Opc = X86ISD::FNMSUB;
14426 case Intrinsic::x86_fma_vfmaddsub_ps:
14427 case Intrinsic::x86_fma_vfmaddsub_pd:
14428 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14429 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14430 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14431 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14432 Opc = X86ISD::FMADDSUB;
14434 case Intrinsic::x86_fma_vfmsubadd_ps:
14435 case Intrinsic::x86_fma_vfmsubadd_pd:
14436 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14437 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14438 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14439 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14440 Opc = X86ISD::FMSUBADD;
14444 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14445 Op.getOperand(2), Op.getOperand(3));
14450 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14451 SDValue Src, SDValue Mask, SDValue Base,
14452 SDValue Index, SDValue ScaleOp, SDValue Chain,
14453 const X86Subtarget * Subtarget) {
14455 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14456 assert(C && "Invalid scale type");
14457 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14458 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14459 Index.getSimpleValueType().getVectorNumElements());
14461 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14463 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14465 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14466 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14467 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14468 SDValue Segment = DAG.getRegister(0, MVT::i32);
14469 if (Src.getOpcode() == ISD::UNDEF)
14470 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14471 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14472 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14473 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14474 return DAG.getMergeValues(RetOps, dl);
14477 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14478 SDValue Src, SDValue Mask, SDValue Base,
14479 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14481 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14482 assert(C && "Invalid scale type");
14483 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14484 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14485 SDValue Segment = DAG.getRegister(0, MVT::i32);
14486 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14487 Index.getSimpleValueType().getVectorNumElements());
14489 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14491 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14493 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14494 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14495 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14496 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14497 return SDValue(Res, 1);
14500 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14501 SDValue Mask, SDValue Base, SDValue Index,
14502 SDValue ScaleOp, SDValue Chain) {
14504 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14505 assert(C && "Invalid scale type");
14506 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14507 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14508 SDValue Segment = DAG.getRegister(0, MVT::i32);
14510 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14512 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14514 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14516 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14517 //SDVTList VTs = DAG.getVTList(MVT::Other);
14518 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14519 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14520 return SDValue(Res, 0);
14523 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14524 // read performance monitor counters (x86_rdpmc).
14525 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14526 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14527 SmallVectorImpl<SDValue> &Results) {
14528 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14529 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14532 // The ECX register is used to select the index of the performance counter
14534 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14536 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14538 // Reads the content of a 64-bit performance counter and returns it in the
14539 // registers EDX:EAX.
14540 if (Subtarget->is64Bit()) {
14541 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14542 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14545 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14546 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14549 Chain = HI.getValue(1);
14551 if (Subtarget->is64Bit()) {
14552 // The EAX register is loaded with the low-order 32 bits. The EDX register
14553 // is loaded with the supported high-order bits of the counter.
14554 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14555 DAG.getConstant(32, MVT::i8));
14556 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14557 Results.push_back(Chain);
14561 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14562 SDValue Ops[] = { LO, HI };
14563 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14564 Results.push_back(Pair);
14565 Results.push_back(Chain);
14568 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14569 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14570 // also used to custom lower READCYCLECOUNTER nodes.
14571 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14572 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14573 SmallVectorImpl<SDValue> &Results) {
14574 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14575 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14578 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14579 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14580 // and the EAX register is loaded with the low-order 32 bits.
14581 if (Subtarget->is64Bit()) {
14582 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14583 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14586 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14587 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14590 SDValue Chain = HI.getValue(1);
14592 if (Opcode == X86ISD::RDTSCP_DAG) {
14593 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14595 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14596 // the ECX register. Add 'ecx' explicitly to the chain.
14597 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14599 // Explicitly store the content of ECX at the location passed in input
14600 // to the 'rdtscp' intrinsic.
14601 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14602 MachinePointerInfo(), false, false, 0);
14605 if (Subtarget->is64Bit()) {
14606 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14607 // the EAX register is loaded with the low-order 32 bits.
14608 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14609 DAG.getConstant(32, MVT::i8));
14610 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14611 Results.push_back(Chain);
14615 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14616 SDValue Ops[] = { LO, HI };
14617 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14618 Results.push_back(Pair);
14619 Results.push_back(Chain);
14622 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14623 SelectionDAG &DAG) {
14624 SmallVector<SDValue, 2> Results;
14626 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14628 return DAG.getMergeValues(Results, DL);
14631 enum IntrinsicType {
14632 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14635 struct IntrinsicData {
14636 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14637 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14638 IntrinsicType Type;
14643 std::map < unsigned, IntrinsicData> IntrMap;
14644 static void InitIntinsicsMap() {
14645 static bool Initialized = false;
14648 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14649 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14650 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14651 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14652 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14653 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14654 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14655 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14656 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14657 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14658 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14659 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14660 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14661 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14662 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14663 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14664 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14665 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14667 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14668 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14669 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14670 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14671 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14672 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14673 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14674 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14675 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14676 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14677 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14678 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14679 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14680 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14681 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14682 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14684 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14685 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14686 X86::VGATHERPF1QPSm)));
14687 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14688 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14689 X86::VGATHERPF1QPDm)));
14690 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14691 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14692 X86::VGATHERPF1DPDm)));
14693 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14694 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14695 X86::VGATHERPF1DPSm)));
14696 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14697 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14698 X86::VSCATTERPF1QPSm)));
14699 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14700 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14701 X86::VSCATTERPF1QPDm)));
14702 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14703 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14704 X86::VSCATTERPF1DPDm)));
14705 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14706 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14707 X86::VSCATTERPF1DPSm)));
14708 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14709 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14710 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14711 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14712 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14713 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14714 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14715 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14716 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14717 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14718 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14719 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14720 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14721 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14722 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14723 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14724 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14725 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14726 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14727 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14728 Initialized = true;
14731 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14732 SelectionDAG &DAG) {
14733 InitIntinsicsMap();
14734 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14735 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14736 if (itr == IntrMap.end())
14740 IntrinsicData Intr = itr->second;
14741 switch(Intr.Type) {
14744 // Emit the node with the right value type.
14745 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14746 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14748 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14749 // Otherwise return the value from Rand, which is always 0, casted to i32.
14750 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14751 DAG.getConstant(1, Op->getValueType(1)),
14752 DAG.getConstant(X86::COND_B, MVT::i32),
14753 SDValue(Result.getNode(), 1) };
14754 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14755 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14758 // Return { result, isValid, chain }.
14759 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14760 SDValue(Result.getNode(), 2));
14763 //gather(v1, mask, index, base, scale);
14764 SDValue Chain = Op.getOperand(0);
14765 SDValue Src = Op.getOperand(2);
14766 SDValue Base = Op.getOperand(3);
14767 SDValue Index = Op.getOperand(4);
14768 SDValue Mask = Op.getOperand(5);
14769 SDValue Scale = Op.getOperand(6);
14770 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14774 //scatter(base, mask, index, v1, scale);
14775 SDValue Chain = Op.getOperand(0);
14776 SDValue Base = Op.getOperand(2);
14777 SDValue Mask = Op.getOperand(3);
14778 SDValue Index = Op.getOperand(4);
14779 SDValue Src = Op.getOperand(5);
14780 SDValue Scale = Op.getOperand(6);
14781 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14784 SDValue Hint = Op.getOperand(6);
14786 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14787 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14788 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14789 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14790 SDValue Chain = Op.getOperand(0);
14791 SDValue Mask = Op.getOperand(2);
14792 SDValue Index = Op.getOperand(3);
14793 SDValue Base = Op.getOperand(4);
14794 SDValue Scale = Op.getOperand(5);
14795 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14797 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14799 SmallVector<SDValue, 2> Results;
14800 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14801 return DAG.getMergeValues(Results, dl);
14803 // Read Performance Monitoring Counters.
14805 SmallVector<SDValue, 2> Results;
14806 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14807 return DAG.getMergeValues(Results, dl);
14809 // XTEST intrinsics.
14811 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14812 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14813 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14814 DAG.getConstant(X86::COND_NE, MVT::i8),
14816 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14817 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14818 Ret, SDValue(InTrans.getNode(), 1));
14821 llvm_unreachable("Unknown Intrinsic Type");
14824 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14825 SelectionDAG &DAG) const {
14826 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14827 MFI->setReturnAddressIsTaken(true);
14829 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14832 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14834 EVT PtrVT = getPointerTy();
14837 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14838 const X86RegisterInfo *RegInfo =
14839 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14840 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14841 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14842 DAG.getNode(ISD::ADD, dl, PtrVT,
14843 FrameAddr, Offset),
14844 MachinePointerInfo(), false, false, false, 0);
14847 // Just load the return address.
14848 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14849 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14850 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14853 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14854 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14855 MFI->setFrameAddressIsTaken(true);
14857 EVT VT = Op.getValueType();
14858 SDLoc dl(Op); // FIXME probably not meaningful
14859 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14860 const X86RegisterInfo *RegInfo =
14861 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14862 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14863 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14864 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14865 "Invalid Frame Register!");
14866 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14868 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14869 MachinePointerInfo(),
14870 false, false, false, 0);
14874 // FIXME? Maybe this could be a TableGen attribute on some registers and
14875 // this table could be generated automatically from RegInfo.
14876 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14878 unsigned Reg = StringSwitch<unsigned>(RegName)
14879 .Case("esp", X86::ESP)
14880 .Case("rsp", X86::RSP)
14884 report_fatal_error("Invalid register name global variable");
14887 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14888 SelectionDAG &DAG) const {
14889 const X86RegisterInfo *RegInfo =
14890 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14891 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14894 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14895 SDValue Chain = Op.getOperand(0);
14896 SDValue Offset = Op.getOperand(1);
14897 SDValue Handler = Op.getOperand(2);
14900 EVT PtrVT = getPointerTy();
14901 const X86RegisterInfo *RegInfo =
14902 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14903 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14904 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14905 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14906 "Invalid Frame Register!");
14907 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14908 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14910 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14911 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14912 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14913 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14915 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14917 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14918 DAG.getRegister(StoreAddrReg, PtrVT));
14921 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14922 SelectionDAG &DAG) const {
14924 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14925 DAG.getVTList(MVT::i32, MVT::Other),
14926 Op.getOperand(0), Op.getOperand(1));
14929 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14930 SelectionDAG &DAG) const {
14932 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14933 Op.getOperand(0), Op.getOperand(1));
14936 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14937 return Op.getOperand(0);
14940 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14941 SelectionDAG &DAG) const {
14942 SDValue Root = Op.getOperand(0);
14943 SDValue Trmp = Op.getOperand(1); // trampoline
14944 SDValue FPtr = Op.getOperand(2); // nested function
14945 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14948 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14949 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14951 if (Subtarget->is64Bit()) {
14952 SDValue OutChains[6];
14954 // Large code-model.
14955 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14956 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14958 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14959 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14961 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14963 // Load the pointer to the nested function into R11.
14964 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14965 SDValue Addr = Trmp;
14966 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14967 Addr, MachinePointerInfo(TrmpAddr),
14970 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14971 DAG.getConstant(2, MVT::i64));
14972 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14973 MachinePointerInfo(TrmpAddr, 2),
14976 // Load the 'nest' parameter value into R10.
14977 // R10 is specified in X86CallingConv.td
14978 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14979 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14980 DAG.getConstant(10, MVT::i64));
14981 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14982 Addr, MachinePointerInfo(TrmpAddr, 10),
14985 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14986 DAG.getConstant(12, MVT::i64));
14987 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14988 MachinePointerInfo(TrmpAddr, 12),
14991 // Jump to the nested function.
14992 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14993 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14994 DAG.getConstant(20, MVT::i64));
14995 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14996 Addr, MachinePointerInfo(TrmpAddr, 20),
14999 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15000 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15001 DAG.getConstant(22, MVT::i64));
15002 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15003 MachinePointerInfo(TrmpAddr, 22),
15006 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15008 const Function *Func =
15009 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15010 CallingConv::ID CC = Func->getCallingConv();
15015 llvm_unreachable("Unsupported calling convention");
15016 case CallingConv::C:
15017 case CallingConv::X86_StdCall: {
15018 // Pass 'nest' parameter in ECX.
15019 // Must be kept in sync with X86CallingConv.td
15020 NestReg = X86::ECX;
15022 // Check that ECX wasn't needed by an 'inreg' parameter.
15023 FunctionType *FTy = Func->getFunctionType();
15024 const AttributeSet &Attrs = Func->getAttributes();
15026 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15027 unsigned InRegCount = 0;
15030 for (FunctionType::param_iterator I = FTy->param_begin(),
15031 E = FTy->param_end(); I != E; ++I, ++Idx)
15032 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15033 // FIXME: should only count parameters that are lowered to integers.
15034 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15036 if (InRegCount > 2) {
15037 report_fatal_error("Nest register in use - reduce number of inreg"
15043 case CallingConv::X86_FastCall:
15044 case CallingConv::X86_ThisCall:
15045 case CallingConv::Fast:
15046 // Pass 'nest' parameter in EAX.
15047 // Must be kept in sync with X86CallingConv.td
15048 NestReg = X86::EAX;
15052 SDValue OutChains[4];
15053 SDValue Addr, Disp;
15055 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15056 DAG.getConstant(10, MVT::i32));
15057 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15059 // This is storing the opcode for MOV32ri.
15060 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15061 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15062 OutChains[0] = DAG.getStore(Root, dl,
15063 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15064 Trmp, MachinePointerInfo(TrmpAddr),
15067 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15068 DAG.getConstant(1, MVT::i32));
15069 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15070 MachinePointerInfo(TrmpAddr, 1),
15073 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15074 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15075 DAG.getConstant(5, MVT::i32));
15076 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15077 MachinePointerInfo(TrmpAddr, 5),
15080 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15081 DAG.getConstant(6, MVT::i32));
15082 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15083 MachinePointerInfo(TrmpAddr, 6),
15086 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15090 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15091 SelectionDAG &DAG) const {
15093 The rounding mode is in bits 11:10 of FPSR, and has the following
15095 00 Round to nearest
15100 FLT_ROUNDS, on the other hand, expects the following:
15107 To perform the conversion, we do:
15108 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15111 MachineFunction &MF = DAG.getMachineFunction();
15112 const TargetMachine &TM = MF.getTarget();
15113 const TargetFrameLowering &TFI = *TM.getFrameLowering();
15114 unsigned StackAlignment = TFI.getStackAlignment();
15115 MVT VT = Op.getSimpleValueType();
15118 // Save FP Control Word to stack slot
15119 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15120 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15122 MachineMemOperand *MMO =
15123 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15124 MachineMemOperand::MOStore, 2, 2);
15126 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15127 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15128 DAG.getVTList(MVT::Other),
15129 Ops, MVT::i16, MMO);
15131 // Load FP Control Word from stack slot
15132 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15133 MachinePointerInfo(), false, false, false, 0);
15135 // Transform as necessary
15137 DAG.getNode(ISD::SRL, DL, MVT::i16,
15138 DAG.getNode(ISD::AND, DL, MVT::i16,
15139 CWD, DAG.getConstant(0x800, MVT::i16)),
15140 DAG.getConstant(11, MVT::i8));
15142 DAG.getNode(ISD::SRL, DL, MVT::i16,
15143 DAG.getNode(ISD::AND, DL, MVT::i16,
15144 CWD, DAG.getConstant(0x400, MVT::i16)),
15145 DAG.getConstant(9, MVT::i8));
15148 DAG.getNode(ISD::AND, DL, MVT::i16,
15149 DAG.getNode(ISD::ADD, DL, MVT::i16,
15150 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15151 DAG.getConstant(1, MVT::i16)),
15152 DAG.getConstant(3, MVT::i16));
15154 return DAG.getNode((VT.getSizeInBits() < 16 ?
15155 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15158 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15159 MVT VT = Op.getSimpleValueType();
15161 unsigned NumBits = VT.getSizeInBits();
15164 Op = Op.getOperand(0);
15165 if (VT == MVT::i8) {
15166 // Zero extend to i32 since there is not an i8 bsr.
15168 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15171 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15172 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15173 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15175 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15178 DAG.getConstant(NumBits+NumBits-1, OpVT),
15179 DAG.getConstant(X86::COND_E, MVT::i8),
15182 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15184 // Finally xor with NumBits-1.
15185 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15188 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15192 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15193 MVT VT = Op.getSimpleValueType();
15195 unsigned NumBits = VT.getSizeInBits();
15198 Op = Op.getOperand(0);
15199 if (VT == MVT::i8) {
15200 // Zero extend to i32 since there is not an i8 bsr.
15202 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15205 // Issue a bsr (scan bits in reverse).
15206 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15207 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15209 // And xor with NumBits-1.
15210 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15213 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15217 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15218 MVT VT = Op.getSimpleValueType();
15219 unsigned NumBits = VT.getSizeInBits();
15221 Op = Op.getOperand(0);
15223 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15224 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15225 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15227 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15230 DAG.getConstant(NumBits, VT),
15231 DAG.getConstant(X86::COND_E, MVT::i8),
15234 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15237 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15238 // ones, and then concatenate the result back.
15239 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15240 MVT VT = Op.getSimpleValueType();
15242 assert(VT.is256BitVector() && VT.isInteger() &&
15243 "Unsupported value type for operation");
15245 unsigned NumElems = VT.getVectorNumElements();
15248 // Extract the LHS vectors
15249 SDValue LHS = Op.getOperand(0);
15250 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15251 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15253 // Extract the RHS vectors
15254 SDValue RHS = Op.getOperand(1);
15255 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15256 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15258 MVT EltVT = VT.getVectorElementType();
15259 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15261 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15262 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15263 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15266 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15267 assert(Op.getSimpleValueType().is256BitVector() &&
15268 Op.getSimpleValueType().isInteger() &&
15269 "Only handle AVX 256-bit vector integer operation");
15270 return Lower256IntArith(Op, DAG);
15273 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15274 assert(Op.getSimpleValueType().is256BitVector() &&
15275 Op.getSimpleValueType().isInteger() &&
15276 "Only handle AVX 256-bit vector integer operation");
15277 return Lower256IntArith(Op, DAG);
15280 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15281 SelectionDAG &DAG) {
15283 MVT VT = Op.getSimpleValueType();
15285 // Decompose 256-bit ops into smaller 128-bit ops.
15286 if (VT.is256BitVector() && !Subtarget->hasInt256())
15287 return Lower256IntArith(Op, DAG);
15289 SDValue A = Op.getOperand(0);
15290 SDValue B = Op.getOperand(1);
15292 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15293 if (VT == MVT::v4i32) {
15294 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15295 "Should not custom lower when pmuldq is available!");
15297 // Extract the odd parts.
15298 static const int UnpackMask[] = { 1, -1, 3, -1 };
15299 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15300 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15302 // Multiply the even parts.
15303 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15304 // Now multiply odd parts.
15305 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15307 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15308 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15310 // Merge the two vectors back together with a shuffle. This expands into 2
15312 static const int ShufMask[] = { 0, 4, 2, 6 };
15313 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15316 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15317 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15319 // Ahi = psrlqi(a, 32);
15320 // Bhi = psrlqi(b, 32);
15322 // AloBlo = pmuludq(a, b);
15323 // AloBhi = pmuludq(a, Bhi);
15324 // AhiBlo = pmuludq(Ahi, b);
15326 // AloBhi = psllqi(AloBhi, 32);
15327 // AhiBlo = psllqi(AhiBlo, 32);
15328 // return AloBlo + AloBhi + AhiBlo;
15330 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15331 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15333 // Bit cast to 32-bit vectors for MULUDQ
15334 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15335 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15336 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15337 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15338 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15339 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15341 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15342 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15343 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15345 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15346 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15348 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15349 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15352 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15353 assert(Subtarget->isTargetWin64() && "Unexpected target");
15354 EVT VT = Op.getValueType();
15355 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15356 "Unexpected return type for lowering");
15360 switch (Op->getOpcode()) {
15361 default: llvm_unreachable("Unexpected request for libcall!");
15362 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15363 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15364 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15365 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15366 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15367 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15371 SDValue InChain = DAG.getEntryNode();
15373 TargetLowering::ArgListTy Args;
15374 TargetLowering::ArgListEntry Entry;
15375 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15376 EVT ArgVT = Op->getOperand(i).getValueType();
15377 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15378 "Unexpected argument type for lowering");
15379 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15380 Entry.Node = StackPtr;
15381 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15383 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15384 Entry.Ty = PointerType::get(ArgTy,0);
15385 Entry.isSExt = false;
15386 Entry.isZExt = false;
15387 Args.push_back(Entry);
15390 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15393 TargetLowering::CallLoweringInfo CLI(DAG);
15394 CLI.setDebugLoc(dl).setChain(InChain)
15395 .setCallee(getLibcallCallingConv(LC),
15396 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15397 Callee, std::move(Args), 0)
15398 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15400 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15401 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15404 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15405 SelectionDAG &DAG) {
15406 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15407 EVT VT = Op0.getValueType();
15410 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15411 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15413 // PMULxD operations multiply each even value (starting at 0) of LHS with
15414 // the related value of RHS and produce a widen result.
15415 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15416 // => <2 x i64> <ae|cg>
15418 // In other word, to have all the results, we need to perform two PMULxD:
15419 // 1. one with the even values.
15420 // 2. one with the odd values.
15421 // To achieve #2, with need to place the odd values at an even position.
15423 // Place the odd value at an even position (basically, shift all values 1
15424 // step to the left):
15425 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15426 // <a|b|c|d> => <b|undef|d|undef>
15427 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15428 // <e|f|g|h> => <f|undef|h|undef>
15429 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15431 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15433 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15434 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15436 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15437 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15438 // => <2 x i64> <ae|cg>
15439 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15440 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15441 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15442 // => <2 x i64> <bf|dh>
15443 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15444 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15446 // Shuffle it back into the right order.
15447 // The internal representation is big endian.
15448 // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15449 // and its low part at index 1.
15450 // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15451 // Vector index 0 1 ; 2 3
15452 // We want <ae|bf|cg|dh>
15453 // Vector index 0 2 1 3
15454 // Since each element is seen as 2 x i32, we get:
15455 // high_mask[i] = 2 x vector_index[i]
15456 // low_mask[i] = 2 x vector_index[i] + 1
15457 // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15458 // Size/2 - 1, Size/2 + Size/2 - 1}
15459 // where Size is the number of element of the final vector.
15460 SDValue Highs, Lows;
15461 if (VT == MVT::v8i32) {
15462 const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15463 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15464 const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15465 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15467 const int HighMask[] = {0, 4, 2, 6};
15468 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15469 const int LowMask[] = {1, 5, 3, 7};
15470 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15473 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15474 // unsigned multiply.
15475 if (IsSigned && !Subtarget->hasSSE41()) {
15477 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15478 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15479 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15480 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15481 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15483 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15484 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15487 // THe first result of MUL_LOHI is actually the high value, followed by the
15489 SDValue Ops[] = {Highs, Lows};
15490 return DAG.getMergeValues(Ops, dl);
15493 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15494 const X86Subtarget *Subtarget) {
15495 MVT VT = Op.getSimpleValueType();
15497 SDValue R = Op.getOperand(0);
15498 SDValue Amt = Op.getOperand(1);
15500 // Optimize shl/srl/sra with constant shift amount.
15501 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15502 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15503 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15505 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15506 (Subtarget->hasInt256() &&
15507 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15508 (Subtarget->hasAVX512() &&
15509 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15510 if (Op.getOpcode() == ISD::SHL)
15511 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15513 if (Op.getOpcode() == ISD::SRL)
15514 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15516 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15517 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15521 if (VT == MVT::v16i8) {
15522 if (Op.getOpcode() == ISD::SHL) {
15523 // Make a large shift.
15524 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15525 MVT::v8i16, R, ShiftAmt,
15527 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15528 // Zero out the rightmost bits.
15529 SmallVector<SDValue, 16> V(16,
15530 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15532 return DAG.getNode(ISD::AND, dl, VT, SHL,
15533 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15535 if (Op.getOpcode() == ISD::SRL) {
15536 // Make a large shift.
15537 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15538 MVT::v8i16, R, ShiftAmt,
15540 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15541 // Zero out the leftmost bits.
15542 SmallVector<SDValue, 16> V(16,
15543 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15545 return DAG.getNode(ISD::AND, dl, VT, SRL,
15546 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15548 if (Op.getOpcode() == ISD::SRA) {
15549 if (ShiftAmt == 7) {
15550 // R s>> 7 === R s< 0
15551 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15552 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15555 // R s>> a === ((R u>> a) ^ m) - m
15556 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15557 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15559 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15560 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15561 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15564 llvm_unreachable("Unknown shift opcode.");
15567 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15568 if (Op.getOpcode() == ISD::SHL) {
15569 // Make a large shift.
15570 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15571 MVT::v16i16, R, ShiftAmt,
15573 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15574 // Zero out the rightmost bits.
15575 SmallVector<SDValue, 32> V(32,
15576 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15578 return DAG.getNode(ISD::AND, dl, VT, SHL,
15579 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15581 if (Op.getOpcode() == ISD::SRL) {
15582 // Make a large shift.
15583 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15584 MVT::v16i16, R, ShiftAmt,
15586 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15587 // Zero out the leftmost bits.
15588 SmallVector<SDValue, 32> V(32,
15589 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15591 return DAG.getNode(ISD::AND, dl, VT, SRL,
15592 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15594 if (Op.getOpcode() == ISD::SRA) {
15595 if (ShiftAmt == 7) {
15596 // R s>> 7 === R s< 0
15597 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15598 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15601 // R s>> a === ((R u>> a) ^ m) - m
15602 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15603 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15605 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15606 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15607 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15610 llvm_unreachable("Unknown shift opcode.");
15615 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15616 if (!Subtarget->is64Bit() &&
15617 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15618 Amt.getOpcode() == ISD::BITCAST &&
15619 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15620 Amt = Amt.getOperand(0);
15621 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15622 VT.getVectorNumElements();
15623 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15624 uint64_t ShiftAmt = 0;
15625 for (unsigned i = 0; i != Ratio; ++i) {
15626 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15630 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15632 // Check remaining shift amounts.
15633 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15634 uint64_t ShAmt = 0;
15635 for (unsigned j = 0; j != Ratio; ++j) {
15636 ConstantSDNode *C =
15637 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15641 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15643 if (ShAmt != ShiftAmt)
15646 switch (Op.getOpcode()) {
15648 llvm_unreachable("Unknown shift opcode!");
15650 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15653 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15656 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15664 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15665 const X86Subtarget* Subtarget) {
15666 MVT VT = Op.getSimpleValueType();
15668 SDValue R = Op.getOperand(0);
15669 SDValue Amt = Op.getOperand(1);
15671 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15672 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15673 (Subtarget->hasInt256() &&
15674 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15675 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15676 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15678 EVT EltVT = VT.getVectorElementType();
15680 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15681 unsigned NumElts = VT.getVectorNumElements();
15683 for (i = 0; i != NumElts; ++i) {
15684 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15688 for (j = i; j != NumElts; ++j) {
15689 SDValue Arg = Amt.getOperand(j);
15690 if (Arg.getOpcode() == ISD::UNDEF) continue;
15691 if (Arg != Amt.getOperand(i))
15694 if (i != NumElts && j == NumElts)
15695 BaseShAmt = Amt.getOperand(i);
15697 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15698 Amt = Amt.getOperand(0);
15699 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15700 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15701 SDValue InVec = Amt.getOperand(0);
15702 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15703 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15705 for (; i != NumElts; ++i) {
15706 SDValue Arg = InVec.getOperand(i);
15707 if (Arg.getOpcode() == ISD::UNDEF) continue;
15711 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15712 if (ConstantSDNode *C =
15713 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15714 unsigned SplatIdx =
15715 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15716 if (C->getZExtValue() == SplatIdx)
15717 BaseShAmt = InVec.getOperand(1);
15720 if (!BaseShAmt.getNode())
15721 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15722 DAG.getIntPtrConstant(0));
15726 if (BaseShAmt.getNode()) {
15727 if (EltVT.bitsGT(MVT::i32))
15728 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15729 else if (EltVT.bitsLT(MVT::i32))
15730 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15732 switch (Op.getOpcode()) {
15734 llvm_unreachable("Unknown shift opcode!");
15736 switch (VT.SimpleTy) {
15737 default: return SDValue();
15746 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15749 switch (VT.SimpleTy) {
15750 default: return SDValue();
15757 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15760 switch (VT.SimpleTy) {
15761 default: return SDValue();
15770 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15776 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15777 if (!Subtarget->is64Bit() &&
15778 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15779 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15780 Amt.getOpcode() == ISD::BITCAST &&
15781 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15782 Amt = Amt.getOperand(0);
15783 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15784 VT.getVectorNumElements();
15785 std::vector<SDValue> Vals(Ratio);
15786 for (unsigned i = 0; i != Ratio; ++i)
15787 Vals[i] = Amt.getOperand(i);
15788 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15789 for (unsigned j = 0; j != Ratio; ++j)
15790 if (Vals[j] != Amt.getOperand(i + j))
15793 switch (Op.getOpcode()) {
15795 llvm_unreachable("Unknown shift opcode!");
15797 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15799 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15801 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15808 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15809 SelectionDAG &DAG) {
15810 MVT VT = Op.getSimpleValueType();
15812 SDValue R = Op.getOperand(0);
15813 SDValue Amt = Op.getOperand(1);
15816 assert(VT.isVector() && "Custom lowering only for vector shifts!");
15817 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15819 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15823 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15827 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15829 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15830 if (Subtarget->hasInt256()) {
15831 if (Op.getOpcode() == ISD::SRL &&
15832 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15833 VT == MVT::v4i64 || VT == MVT::v8i32))
15835 if (Op.getOpcode() == ISD::SHL &&
15836 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15837 VT == MVT::v4i64 || VT == MVT::v8i32))
15839 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15843 // If possible, lower this packed shift into a vector multiply instead of
15844 // expanding it into a sequence of scalar shifts.
15845 // Do this only if the vector shift count is a constant build_vector.
15846 if (Op.getOpcode() == ISD::SHL &&
15847 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15848 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15849 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15850 SmallVector<SDValue, 8> Elts;
15851 EVT SVT = VT.getScalarType();
15852 unsigned SVTBits = SVT.getSizeInBits();
15853 const APInt &One = APInt(SVTBits, 1);
15854 unsigned NumElems = VT.getVectorNumElements();
15856 for (unsigned i=0; i !=NumElems; ++i) {
15857 SDValue Op = Amt->getOperand(i);
15858 if (Op->getOpcode() == ISD::UNDEF) {
15859 Elts.push_back(Op);
15863 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15864 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15865 uint64_t ShAmt = C.getZExtValue();
15866 if (ShAmt >= SVTBits) {
15867 Elts.push_back(DAG.getUNDEF(SVT));
15870 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15872 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15873 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15876 // Lower SHL with variable shift amount.
15877 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15878 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15880 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15881 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15882 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15883 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15886 // If possible, lower this shift as a sequence of two shifts by
15887 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15889 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15891 // Could be rewritten as:
15892 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15894 // The advantage is that the two shifts from the example would be
15895 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15896 // the vector shift into four scalar shifts plus four pairs of vector
15898 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15899 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15900 unsigned TargetOpcode = X86ISD::MOVSS;
15901 bool CanBeSimplified;
15902 // The splat value for the first packed shift (the 'X' from the example).
15903 SDValue Amt1 = Amt->getOperand(0);
15904 // The splat value for the second packed shift (the 'Y' from the example).
15905 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15906 Amt->getOperand(2);
15908 // See if it is possible to replace this node with a sequence of
15909 // two shifts followed by a MOVSS/MOVSD
15910 if (VT == MVT::v4i32) {
15911 // Check if it is legal to use a MOVSS.
15912 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15913 Amt2 == Amt->getOperand(3);
15914 if (!CanBeSimplified) {
15915 // Otherwise, check if we can still simplify this node using a MOVSD.
15916 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15917 Amt->getOperand(2) == Amt->getOperand(3);
15918 TargetOpcode = X86ISD::MOVSD;
15919 Amt2 = Amt->getOperand(2);
15922 // Do similar checks for the case where the machine value type
15924 CanBeSimplified = Amt1 == Amt->getOperand(1);
15925 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15926 CanBeSimplified = Amt2 == Amt->getOperand(i);
15928 if (!CanBeSimplified) {
15929 TargetOpcode = X86ISD::MOVSD;
15930 CanBeSimplified = true;
15931 Amt2 = Amt->getOperand(4);
15932 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15933 CanBeSimplified = Amt1 == Amt->getOperand(i);
15934 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15935 CanBeSimplified = Amt2 == Amt->getOperand(j);
15939 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15940 isa<ConstantSDNode>(Amt2)) {
15941 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15942 EVT CastVT = MVT::v4i32;
15944 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15945 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15947 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15948 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15949 if (TargetOpcode == X86ISD::MOVSD)
15950 CastVT = MVT::v2i64;
15951 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15952 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15953 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15955 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15959 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15960 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15963 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15964 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15966 // Turn 'a' into a mask suitable for VSELECT
15967 SDValue VSelM = DAG.getConstant(0x80, VT);
15968 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15969 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15971 SDValue CM1 = DAG.getConstant(0x0f, VT);
15972 SDValue CM2 = DAG.getConstant(0x3f, VT);
15974 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15975 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15976 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15977 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15978 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15981 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15982 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15983 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15985 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15986 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15987 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15988 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15989 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15992 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15993 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15994 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15996 // return VSELECT(r, r+r, a);
15997 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15998 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16002 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16003 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16004 // solution better.
16005 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16006 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16008 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16009 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16010 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16011 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16012 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16015 // Decompose 256-bit shifts into smaller 128-bit shifts.
16016 if (VT.is256BitVector()) {
16017 unsigned NumElems = VT.getVectorNumElements();
16018 MVT EltVT = VT.getVectorElementType();
16019 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16021 // Extract the two vectors
16022 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16023 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16025 // Recreate the shift amount vectors
16026 SDValue Amt1, Amt2;
16027 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16028 // Constant shift amount
16029 SmallVector<SDValue, 4> Amt1Csts;
16030 SmallVector<SDValue, 4> Amt2Csts;
16031 for (unsigned i = 0; i != NumElems/2; ++i)
16032 Amt1Csts.push_back(Amt->getOperand(i));
16033 for (unsigned i = NumElems/2; i != NumElems; ++i)
16034 Amt2Csts.push_back(Amt->getOperand(i));
16036 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16037 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16039 // Variable shift amount
16040 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16041 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16044 // Issue new vector shifts for the smaller types
16045 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16046 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16048 // Concatenate the result back
16049 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16055 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16056 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16057 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16058 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16059 // has only one use.
16060 SDNode *N = Op.getNode();
16061 SDValue LHS = N->getOperand(0);
16062 SDValue RHS = N->getOperand(1);
16063 unsigned BaseOp = 0;
16066 switch (Op.getOpcode()) {
16067 default: llvm_unreachable("Unknown ovf instruction!");
16069 // A subtract of one will be selected as a INC. Note that INC doesn't
16070 // set CF, so we can't do this for UADDO.
16071 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16073 BaseOp = X86ISD::INC;
16074 Cond = X86::COND_O;
16077 BaseOp = X86ISD::ADD;
16078 Cond = X86::COND_O;
16081 BaseOp = X86ISD::ADD;
16082 Cond = X86::COND_B;
16085 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16086 // set CF, so we can't do this for USUBO.
16087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16089 BaseOp = X86ISD::DEC;
16090 Cond = X86::COND_O;
16093 BaseOp = X86ISD::SUB;
16094 Cond = X86::COND_O;
16097 BaseOp = X86ISD::SUB;
16098 Cond = X86::COND_B;
16101 BaseOp = X86ISD::SMUL;
16102 Cond = X86::COND_O;
16104 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16105 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16107 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16110 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16111 DAG.getConstant(X86::COND_O, MVT::i32),
16112 SDValue(Sum.getNode(), 2));
16114 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16118 // Also sets EFLAGS.
16119 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16120 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16123 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16124 DAG.getConstant(Cond, MVT::i32),
16125 SDValue(Sum.getNode(), 1));
16127 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16130 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16131 SelectionDAG &DAG) const {
16133 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16134 MVT VT = Op.getSimpleValueType();
16136 if (!Subtarget->hasSSE2() || !VT.isVector())
16139 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16140 ExtraVT.getScalarType().getSizeInBits();
16142 switch (VT.SimpleTy) {
16143 default: return SDValue();
16146 if (!Subtarget->hasFp256())
16148 if (!Subtarget->hasInt256()) {
16149 // needs to be split
16150 unsigned NumElems = VT.getVectorNumElements();
16152 // Extract the LHS vectors
16153 SDValue LHS = Op.getOperand(0);
16154 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16155 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16157 MVT EltVT = VT.getVectorElementType();
16158 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16160 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16161 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16162 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16164 SDValue Extra = DAG.getValueType(ExtraVT);
16166 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16167 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16169 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16174 SDValue Op0 = Op.getOperand(0);
16175 SDValue Op00 = Op0.getOperand(0);
16177 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16178 if (Op0.getOpcode() == ISD::BITCAST &&
16179 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16180 // (sext (vzext x)) -> (vsext x)
16181 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16182 if (Tmp1.getNode()) {
16183 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16184 // This folding is only valid when the in-reg type is a vector of i8,
16186 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16187 ExtraEltVT == MVT::i32) {
16188 SDValue Tmp1Op0 = Tmp1.getOperand(0);
16189 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16190 "This optimization is invalid without a VZEXT.");
16191 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16197 // If the above didn't work, then just use Shift-Left + Shift-Right.
16198 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16200 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16206 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16207 SelectionDAG &DAG) {
16209 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16210 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16211 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16212 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16214 // The only fence that needs an instruction is a sequentially-consistent
16215 // cross-thread fence.
16216 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16217 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16218 // no-sse2). There isn't any reason to disable it if the target processor
16220 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16221 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16223 SDValue Chain = Op.getOperand(0);
16224 SDValue Zero = DAG.getConstant(0, MVT::i32);
16226 DAG.getRegister(X86::ESP, MVT::i32), // Base
16227 DAG.getTargetConstant(1, MVT::i8), // Scale
16228 DAG.getRegister(0, MVT::i32), // Index
16229 DAG.getTargetConstant(0, MVT::i32), // Disp
16230 DAG.getRegister(0, MVT::i32), // Segment.
16234 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16235 return SDValue(Res, 0);
16238 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16239 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16242 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16243 SelectionDAG &DAG) {
16244 MVT T = Op.getSimpleValueType();
16248 switch(T.SimpleTy) {
16249 default: llvm_unreachable("Invalid value type!");
16250 case MVT::i8: Reg = X86::AL; size = 1; break;
16251 case MVT::i16: Reg = X86::AX; size = 2; break;
16252 case MVT::i32: Reg = X86::EAX; size = 4; break;
16254 assert(Subtarget->is64Bit() && "Node not type legal!");
16255 Reg = X86::RAX; size = 8;
16258 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16259 Op.getOperand(2), SDValue());
16260 SDValue Ops[] = { cpIn.getValue(0),
16263 DAG.getTargetConstant(size, MVT::i8),
16264 cpIn.getValue(1) };
16265 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16266 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16267 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16271 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16272 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16273 MVT::i32, cpOut.getValue(2));
16274 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16275 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16277 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16278 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16279 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16283 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16284 SelectionDAG &DAG) {
16285 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16286 MVT DstVT = Op.getSimpleValueType();
16288 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16289 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16290 if (DstVT != MVT::f64)
16291 // This conversion needs to be expanded.
16294 SDValue InVec = Op->getOperand(0);
16296 unsigned NumElts = SrcVT.getVectorNumElements();
16297 EVT SVT = SrcVT.getVectorElementType();
16299 // Widen the vector in input in the case of MVT::v2i32.
16300 // Example: from MVT::v2i32 to MVT::v4i32.
16301 SmallVector<SDValue, 16> Elts;
16302 for (unsigned i = 0, e = NumElts; i != e; ++i)
16303 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16304 DAG.getIntPtrConstant(i)));
16306 // Explicitly mark the extra elements as Undef.
16307 SDValue Undef = DAG.getUNDEF(SVT);
16308 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16309 Elts.push_back(Undef);
16311 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16312 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16313 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16314 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16315 DAG.getIntPtrConstant(0));
16318 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16319 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16320 assert((DstVT == MVT::i64 ||
16321 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16322 "Unexpected custom BITCAST");
16323 // i64 <=> MMX conversions are Legal.
16324 if (SrcVT==MVT::i64 && DstVT.isVector())
16326 if (DstVT==MVT::i64 && SrcVT.isVector())
16328 // MMX <=> MMX conversions are Legal.
16329 if (SrcVT.isVector() && DstVT.isVector())
16331 // All other conversions need to be expanded.
16335 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16336 SDNode *Node = Op.getNode();
16338 EVT T = Node->getValueType(0);
16339 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16340 DAG.getConstant(0, T), Node->getOperand(2));
16341 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16342 cast<AtomicSDNode>(Node)->getMemoryVT(),
16343 Node->getOperand(0),
16344 Node->getOperand(1), negOp,
16345 cast<AtomicSDNode>(Node)->getMemOperand(),
16346 cast<AtomicSDNode>(Node)->getOrdering(),
16347 cast<AtomicSDNode>(Node)->getSynchScope());
16350 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16351 SDNode *Node = Op.getNode();
16353 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16355 // Convert seq_cst store -> xchg
16356 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16357 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16358 // (The only way to get a 16-byte store is cmpxchg16b)
16359 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16360 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16361 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16362 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16363 cast<AtomicSDNode>(Node)->getMemoryVT(),
16364 Node->getOperand(0),
16365 Node->getOperand(1), Node->getOperand(2),
16366 cast<AtomicSDNode>(Node)->getMemOperand(),
16367 cast<AtomicSDNode>(Node)->getOrdering(),
16368 cast<AtomicSDNode>(Node)->getSynchScope());
16369 return Swap.getValue(1);
16371 // Other atomic stores have a simple pattern.
16375 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16376 EVT VT = Op.getNode()->getSimpleValueType(0);
16378 // Let legalize expand this if it isn't a legal type yet.
16379 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16382 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16385 bool ExtraOp = false;
16386 switch (Op.getOpcode()) {
16387 default: llvm_unreachable("Invalid code");
16388 case ISD::ADDC: Opc = X86ISD::ADD; break;
16389 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16390 case ISD::SUBC: Opc = X86ISD::SUB; break;
16391 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16395 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16397 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16398 Op.getOperand(1), Op.getOperand(2));
16401 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16402 SelectionDAG &DAG) {
16403 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16405 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16406 // which returns the values as { float, float } (in XMM0) or
16407 // { double, double } (which is returned in XMM0, XMM1).
16409 SDValue Arg = Op.getOperand(0);
16410 EVT ArgVT = Arg.getValueType();
16411 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16413 TargetLowering::ArgListTy Args;
16414 TargetLowering::ArgListEntry Entry;
16418 Entry.isSExt = false;
16419 Entry.isZExt = false;
16420 Args.push_back(Entry);
16422 bool isF64 = ArgVT == MVT::f64;
16423 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16424 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16425 // the results are returned via SRet in memory.
16426 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16427 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16428 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16430 Type *RetTy = isF64
16431 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16432 : (Type*)VectorType::get(ArgTy, 4);
16434 TargetLowering::CallLoweringInfo CLI(DAG);
16435 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16436 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16438 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16441 // Returned in xmm0 and xmm1.
16442 return CallResult.first;
16444 // Returned in bits 0:31 and 32:64 xmm0.
16445 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16446 CallResult.first, DAG.getIntPtrConstant(0));
16447 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16448 CallResult.first, DAG.getIntPtrConstant(1));
16449 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16450 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16453 /// LowerOperation - Provide custom lowering hooks for some operations.
16455 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16456 switch (Op.getOpcode()) {
16457 default: llvm_unreachable("Should not custom lower this!");
16458 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16459 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16460 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16461 return LowerCMP_SWAP(Op, Subtarget, DAG);
16462 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16463 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16464 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16465 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16466 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16467 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16468 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16469 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16470 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16471 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16472 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16473 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16474 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16475 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16476 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16477 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16478 case ISD::SHL_PARTS:
16479 case ISD::SRA_PARTS:
16480 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16481 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16482 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16483 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16484 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16485 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16486 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16487 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16488 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16489 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16490 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16491 case ISD::FABS: return LowerFABS(Op, DAG);
16492 case ISD::FNEG: return LowerFNEG(Op, DAG);
16493 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16494 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16495 case ISD::SETCC: return LowerSETCC(Op, DAG);
16496 case ISD::SELECT: return LowerSELECT(Op, DAG);
16497 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16498 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16499 case ISD::VASTART: return LowerVASTART(Op, DAG);
16500 case ISD::VAARG: return LowerVAARG(Op, DAG);
16501 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16502 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16503 case ISD::INTRINSIC_VOID:
16504 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16505 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16506 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16507 case ISD::FRAME_TO_ARGS_OFFSET:
16508 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16509 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16510 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16511 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16512 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16513 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16514 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16515 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16516 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16517 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16518 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16519 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16520 case ISD::UMUL_LOHI:
16521 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16524 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16530 case ISD::UMULO: return LowerXALUO(Op, DAG);
16531 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16532 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16536 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16537 case ISD::ADD: return LowerADD(Op, DAG);
16538 case ISD::SUB: return LowerSUB(Op, DAG);
16539 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16543 static void ReplaceATOMIC_LOAD(SDNode *Node,
16544 SmallVectorImpl<SDValue> &Results,
16545 SelectionDAG &DAG) {
16547 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16549 // Convert wide load -> cmpxchg8b/cmpxchg16b
16550 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16551 // (The only way to get a 16-byte load is cmpxchg16b)
16552 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16553 SDValue Zero = DAG.getConstant(0, VT);
16554 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16556 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16557 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16558 cast<AtomicSDNode>(Node)->getMemOperand(),
16559 cast<AtomicSDNode>(Node)->getOrdering(),
16560 cast<AtomicSDNode>(Node)->getOrdering(),
16561 cast<AtomicSDNode>(Node)->getSynchScope());
16562 Results.push_back(Swap.getValue(0));
16563 Results.push_back(Swap.getValue(2));
16566 /// ReplaceNodeResults - Replace a node with an illegal result type
16567 /// with a new node built out of custom code.
16568 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16569 SmallVectorImpl<SDValue>&Results,
16570 SelectionDAG &DAG) const {
16572 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16573 switch (N->getOpcode()) {
16575 llvm_unreachable("Do not know how to custom type legalize this operation!");
16576 case ISD::SIGN_EXTEND_INREG:
16581 // We don't want to expand or promote these.
16588 case ISD::UDIVREM: {
16589 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16590 Results.push_back(V);
16593 case ISD::FP_TO_SINT:
16594 case ISD::FP_TO_UINT: {
16595 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16597 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16600 std::pair<SDValue,SDValue> Vals =
16601 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16602 SDValue FIST = Vals.first, StackSlot = Vals.second;
16603 if (FIST.getNode()) {
16604 EVT VT = N->getValueType(0);
16605 // Return a load from the stack slot.
16606 if (StackSlot.getNode())
16607 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16608 MachinePointerInfo(),
16609 false, false, false, 0));
16611 Results.push_back(FIST);
16615 case ISD::UINT_TO_FP: {
16616 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16617 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16618 N->getValueType(0) != MVT::v2f32)
16620 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16622 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16624 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16625 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16626 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16627 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16628 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16629 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16632 case ISD::FP_ROUND: {
16633 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16635 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16636 Results.push_back(V);
16639 case ISD::INTRINSIC_W_CHAIN: {
16640 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16642 default : llvm_unreachable("Do not know how to custom type "
16643 "legalize this intrinsic operation!");
16644 case Intrinsic::x86_rdtsc:
16645 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16647 case Intrinsic::x86_rdtscp:
16648 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16650 case Intrinsic::x86_rdpmc:
16651 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16654 case ISD::READCYCLECOUNTER: {
16655 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16658 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16659 EVT T = N->getValueType(0);
16660 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16661 bool Regs64bit = T == MVT::i128;
16662 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16663 SDValue cpInL, cpInH;
16664 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16665 DAG.getConstant(0, HalfT));
16666 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16667 DAG.getConstant(1, HalfT));
16668 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16669 Regs64bit ? X86::RAX : X86::EAX,
16671 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16672 Regs64bit ? X86::RDX : X86::EDX,
16673 cpInH, cpInL.getValue(1));
16674 SDValue swapInL, swapInH;
16675 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16676 DAG.getConstant(0, HalfT));
16677 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16678 DAG.getConstant(1, HalfT));
16679 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16680 Regs64bit ? X86::RBX : X86::EBX,
16681 swapInL, cpInH.getValue(1));
16682 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16683 Regs64bit ? X86::RCX : X86::ECX,
16684 swapInH, swapInL.getValue(1));
16685 SDValue Ops[] = { swapInH.getValue(0),
16687 swapInH.getValue(1) };
16688 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16689 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16690 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16691 X86ISD::LCMPXCHG8_DAG;
16692 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16693 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16694 Regs64bit ? X86::RAX : X86::EAX,
16695 HalfT, Result.getValue(1));
16696 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16697 Regs64bit ? X86::RDX : X86::EDX,
16698 HalfT, cpOutL.getValue(2));
16699 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16701 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16702 MVT::i32, cpOutH.getValue(2));
16704 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16705 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16706 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16708 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16709 Results.push_back(Success);
16710 Results.push_back(EFLAGS.getValue(1));
16713 case ISD::ATOMIC_SWAP:
16714 case ISD::ATOMIC_LOAD_ADD:
16715 case ISD::ATOMIC_LOAD_SUB:
16716 case ISD::ATOMIC_LOAD_AND:
16717 case ISD::ATOMIC_LOAD_OR:
16718 case ISD::ATOMIC_LOAD_XOR:
16719 case ISD::ATOMIC_LOAD_NAND:
16720 case ISD::ATOMIC_LOAD_MIN:
16721 case ISD::ATOMIC_LOAD_MAX:
16722 case ISD::ATOMIC_LOAD_UMIN:
16723 case ISD::ATOMIC_LOAD_UMAX:
16724 // Delegate to generic TypeLegalization. Situations we can really handle
16725 // should have already been dealt with by X86AtomicExpand.cpp.
16727 case ISD::ATOMIC_LOAD: {
16728 ReplaceATOMIC_LOAD(N, Results, DAG);
16731 case ISD::BITCAST: {
16732 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16733 EVT DstVT = N->getValueType(0);
16734 EVT SrcVT = N->getOperand(0)->getValueType(0);
16736 if (SrcVT != MVT::f64 ||
16737 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16740 unsigned NumElts = DstVT.getVectorNumElements();
16741 EVT SVT = DstVT.getVectorElementType();
16742 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16743 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16744 MVT::v2f64, N->getOperand(0));
16745 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16747 if (ExperimentalVectorWideningLegalization) {
16748 // If we are legalizing vectors by widening, we already have the desired
16749 // legal vector type, just return it.
16750 Results.push_back(ToVecInt);
16754 SmallVector<SDValue, 8> Elts;
16755 for (unsigned i = 0, e = NumElts; i != e; ++i)
16756 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16757 ToVecInt, DAG.getIntPtrConstant(i)));
16759 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16764 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16766 default: return nullptr;
16767 case X86ISD::BSF: return "X86ISD::BSF";
16768 case X86ISD::BSR: return "X86ISD::BSR";
16769 case X86ISD::SHLD: return "X86ISD::SHLD";
16770 case X86ISD::SHRD: return "X86ISD::SHRD";
16771 case X86ISD::FAND: return "X86ISD::FAND";
16772 case X86ISD::FANDN: return "X86ISD::FANDN";
16773 case X86ISD::FOR: return "X86ISD::FOR";
16774 case X86ISD::FXOR: return "X86ISD::FXOR";
16775 case X86ISD::FSRL: return "X86ISD::FSRL";
16776 case X86ISD::FILD: return "X86ISD::FILD";
16777 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16778 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16779 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16780 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16781 case X86ISD::FLD: return "X86ISD::FLD";
16782 case X86ISD::FST: return "X86ISD::FST";
16783 case X86ISD::CALL: return "X86ISD::CALL";
16784 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16785 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16786 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16787 case X86ISD::BT: return "X86ISD::BT";
16788 case X86ISD::CMP: return "X86ISD::CMP";
16789 case X86ISD::COMI: return "X86ISD::COMI";
16790 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16791 case X86ISD::CMPM: return "X86ISD::CMPM";
16792 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16793 case X86ISD::SETCC: return "X86ISD::SETCC";
16794 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16795 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16796 case X86ISD::CMOV: return "X86ISD::CMOV";
16797 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16798 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16799 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16800 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16801 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16802 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16803 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16804 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16805 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16806 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16807 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16808 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16809 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16810 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16811 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16812 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16813 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16814 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16815 case X86ISD::HADD: return "X86ISD::HADD";
16816 case X86ISD::HSUB: return "X86ISD::HSUB";
16817 case X86ISD::FHADD: return "X86ISD::FHADD";
16818 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16819 case X86ISD::UMAX: return "X86ISD::UMAX";
16820 case X86ISD::UMIN: return "X86ISD::UMIN";
16821 case X86ISD::SMAX: return "X86ISD::SMAX";
16822 case X86ISD::SMIN: return "X86ISD::SMIN";
16823 case X86ISD::FMAX: return "X86ISD::FMAX";
16824 case X86ISD::FMIN: return "X86ISD::FMIN";
16825 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16826 case X86ISD::FMINC: return "X86ISD::FMINC";
16827 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16828 case X86ISD::FRCP: return "X86ISD::FRCP";
16829 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16830 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16831 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16832 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16833 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16834 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16835 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16836 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16837 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16838 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16839 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16840 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16841 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16842 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16843 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16844 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16845 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16846 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16847 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16848 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16849 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16850 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16851 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16852 case X86ISD::VSHL: return "X86ISD::VSHL";
16853 case X86ISD::VSRL: return "X86ISD::VSRL";
16854 case X86ISD::VSRA: return "X86ISD::VSRA";
16855 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16856 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16857 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16858 case X86ISD::CMPP: return "X86ISD::CMPP";
16859 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16860 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16861 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16862 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16863 case X86ISD::ADD: return "X86ISD::ADD";
16864 case X86ISD::SUB: return "X86ISD::SUB";
16865 case X86ISD::ADC: return "X86ISD::ADC";
16866 case X86ISD::SBB: return "X86ISD::SBB";
16867 case X86ISD::SMUL: return "X86ISD::SMUL";
16868 case X86ISD::UMUL: return "X86ISD::UMUL";
16869 case X86ISD::INC: return "X86ISD::INC";
16870 case X86ISD::DEC: return "X86ISD::DEC";
16871 case X86ISD::OR: return "X86ISD::OR";
16872 case X86ISD::XOR: return "X86ISD::XOR";
16873 case X86ISD::AND: return "X86ISD::AND";
16874 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16875 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16876 case X86ISD::PTEST: return "X86ISD::PTEST";
16877 case X86ISD::TESTP: return "X86ISD::TESTP";
16878 case X86ISD::TESTM: return "X86ISD::TESTM";
16879 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16880 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16881 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16882 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16883 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16884 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16885 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16886 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16887 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16888 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16889 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16890 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16891 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16892 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16893 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16894 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16895 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16896 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16897 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16898 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16899 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16900 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16901 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16902 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16903 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16904 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16905 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16906 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16907 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16908 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16909 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16910 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16911 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16912 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16913 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16914 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16915 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16916 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16917 case X86ISD::SAHF: return "X86ISD::SAHF";
16918 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16919 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16920 case X86ISD::FMADD: return "X86ISD::FMADD";
16921 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16922 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16923 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16924 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16925 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16926 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16927 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16928 case X86ISD::XTEST: return "X86ISD::XTEST";
16932 // isLegalAddressingMode - Return true if the addressing mode represented
16933 // by AM is legal for this target, for a load/store of the specified type.
16934 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16936 // X86 supports extremely general addressing modes.
16937 CodeModel::Model M = getTargetMachine().getCodeModel();
16938 Reloc::Model R = getTargetMachine().getRelocationModel();
16940 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16941 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16946 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16948 // If a reference to this global requires an extra load, we can't fold it.
16949 if (isGlobalStubReference(GVFlags))
16952 // If BaseGV requires a register for the PIC base, we cannot also have a
16953 // BaseReg specified.
16954 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16957 // If lower 4G is not available, then we must use rip-relative addressing.
16958 if ((M != CodeModel::Small || R != Reloc::Static) &&
16959 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16963 switch (AM.Scale) {
16969 // These scales always work.
16974 // These scales are formed with basereg+scalereg. Only accept if there is
16979 default: // Other stuff never works.
16986 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16987 unsigned Bits = Ty->getScalarSizeInBits();
16989 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16990 // particularly cheaper than those without.
16994 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16995 // variable shifts just as cheap as scalar ones.
16996 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16999 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17000 // fully general vector.
17004 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17005 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17007 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17008 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17009 return NumBits1 > NumBits2;
17012 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17013 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17016 if (!isTypeLegal(EVT::getEVT(Ty1)))
17019 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17021 // Assuming the caller doesn't have a zeroext or signext return parameter,
17022 // truncation all the way down to i1 is valid.
17026 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17027 return isInt<32>(Imm);
17030 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17031 // Can also use sub to handle negated immediates.
17032 return isInt<32>(Imm);
17035 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17036 if (!VT1.isInteger() || !VT2.isInteger())
17038 unsigned NumBits1 = VT1.getSizeInBits();
17039 unsigned NumBits2 = VT2.getSizeInBits();
17040 return NumBits1 > NumBits2;
17043 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17044 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17045 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17048 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17049 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17050 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17053 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17054 EVT VT1 = Val.getValueType();
17055 if (isZExtFree(VT1, VT2))
17058 if (Val.getOpcode() != ISD::LOAD)
17061 if (!VT1.isSimple() || !VT1.isInteger() ||
17062 !VT2.isSimple() || !VT2.isInteger())
17065 switch (VT1.getSimpleVT().SimpleTy) {
17070 // X86 has 8, 16, and 32-bit zero-extending loads.
17078 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17079 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17082 VT = VT.getScalarType();
17084 if (!VT.isSimple())
17087 switch (VT.getSimpleVT().SimpleTy) {
17098 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17099 // i16 instructions are longer (0x66 prefix) and potentially slower.
17100 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17103 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17104 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17105 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17106 /// are assumed to be legal.
17108 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17110 if (!VT.isSimple())
17113 MVT SVT = VT.getSimpleVT();
17115 // Very little shuffling can be done for 64-bit vectors right now.
17116 if (VT.getSizeInBits() == 64)
17119 // If this is a single-input shuffle with no 128 bit lane crossings we can
17120 // lower it into pshufb.
17121 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17122 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17123 bool isLegal = true;
17124 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17125 if (M[I] >= (int)SVT.getVectorNumElements() ||
17126 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17135 // FIXME: blends, shifts.
17136 return (SVT.getVectorNumElements() == 2 ||
17137 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17138 isMOVLMask(M, SVT) ||
17139 isMOVHLPSMask(M, SVT) ||
17140 isSHUFPMask(M, SVT) ||
17141 isPSHUFDMask(M, SVT) ||
17142 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17143 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17144 isPALIGNRMask(M, SVT, Subtarget) ||
17145 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17146 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17147 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17148 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17149 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17153 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17155 if (!VT.isSimple())
17158 MVT SVT = VT.getSimpleVT();
17159 unsigned NumElts = SVT.getVectorNumElements();
17160 // FIXME: This collection of masks seems suspect.
17163 if (NumElts == 4 && SVT.is128BitVector()) {
17164 return (isMOVLMask(Mask, SVT) ||
17165 isCommutedMOVLMask(Mask, SVT, true) ||
17166 isSHUFPMask(Mask, SVT) ||
17167 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17172 //===----------------------------------------------------------------------===//
17173 // X86 Scheduler Hooks
17174 //===----------------------------------------------------------------------===//
17176 /// Utility function to emit xbegin specifying the start of an RTM region.
17177 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17178 const TargetInstrInfo *TII) {
17179 DebugLoc DL = MI->getDebugLoc();
17181 const BasicBlock *BB = MBB->getBasicBlock();
17182 MachineFunction::iterator I = MBB;
17185 // For the v = xbegin(), we generate
17196 MachineBasicBlock *thisMBB = MBB;
17197 MachineFunction *MF = MBB->getParent();
17198 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17199 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17200 MF->insert(I, mainMBB);
17201 MF->insert(I, sinkMBB);
17203 // Transfer the remainder of BB and its successor edges to sinkMBB.
17204 sinkMBB->splice(sinkMBB->begin(), MBB,
17205 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17206 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17210 // # fallthrough to mainMBB
17211 // # abortion to sinkMBB
17212 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17213 thisMBB->addSuccessor(mainMBB);
17214 thisMBB->addSuccessor(sinkMBB);
17218 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17219 mainMBB->addSuccessor(sinkMBB);
17222 // EAX is live into the sinkMBB
17223 sinkMBB->addLiveIn(X86::EAX);
17224 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17225 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17228 MI->eraseFromParent();
17232 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17233 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17234 // in the .td file.
17235 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17236 const TargetInstrInfo *TII) {
17238 switch (MI->getOpcode()) {
17239 default: llvm_unreachable("illegal opcode!");
17240 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17241 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17242 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17243 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17244 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17245 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17246 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17247 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17250 DebugLoc dl = MI->getDebugLoc();
17251 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17253 unsigned NumArgs = MI->getNumOperands();
17254 for (unsigned i = 1; i < NumArgs; ++i) {
17255 MachineOperand &Op = MI->getOperand(i);
17256 if (!(Op.isReg() && Op.isImplicit()))
17257 MIB.addOperand(Op);
17259 if (MI->hasOneMemOperand())
17260 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17262 BuildMI(*BB, MI, dl,
17263 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17264 .addReg(X86::XMM0);
17266 MI->eraseFromParent();
17270 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17271 // defs in an instruction pattern
17272 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17273 const TargetInstrInfo *TII) {
17275 switch (MI->getOpcode()) {
17276 default: llvm_unreachable("illegal opcode!");
17277 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17278 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17279 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17280 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17281 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17282 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17283 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17284 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17287 DebugLoc dl = MI->getDebugLoc();
17288 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17290 unsigned NumArgs = MI->getNumOperands(); // remove the results
17291 for (unsigned i = 1; i < NumArgs; ++i) {
17292 MachineOperand &Op = MI->getOperand(i);
17293 if (!(Op.isReg() && Op.isImplicit()))
17294 MIB.addOperand(Op);
17296 if (MI->hasOneMemOperand())
17297 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17299 BuildMI(*BB, MI, dl,
17300 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17303 MI->eraseFromParent();
17307 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17308 const TargetInstrInfo *TII,
17309 const X86Subtarget* Subtarget) {
17310 DebugLoc dl = MI->getDebugLoc();
17312 // Address into RAX/EAX, other two args into ECX, EDX.
17313 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17314 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17315 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17316 for (int i = 0; i < X86::AddrNumOperands; ++i)
17317 MIB.addOperand(MI->getOperand(i));
17319 unsigned ValOps = X86::AddrNumOperands;
17320 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17321 .addReg(MI->getOperand(ValOps).getReg());
17322 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17323 .addReg(MI->getOperand(ValOps+1).getReg());
17325 // The instruction doesn't actually take any operands though.
17326 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17328 MI->eraseFromParent(); // The pseudo is gone now.
17332 MachineBasicBlock *
17333 X86TargetLowering::EmitVAARG64WithCustomInserter(
17335 MachineBasicBlock *MBB) const {
17336 // Emit va_arg instruction on X86-64.
17338 // Operands to this pseudo-instruction:
17339 // 0 ) Output : destination address (reg)
17340 // 1-5) Input : va_list address (addr, i64mem)
17341 // 6 ) ArgSize : Size (in bytes) of vararg type
17342 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17343 // 8 ) Align : Alignment of type
17344 // 9 ) EFLAGS (implicit-def)
17346 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17347 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17349 unsigned DestReg = MI->getOperand(0).getReg();
17350 MachineOperand &Base = MI->getOperand(1);
17351 MachineOperand &Scale = MI->getOperand(2);
17352 MachineOperand &Index = MI->getOperand(3);
17353 MachineOperand &Disp = MI->getOperand(4);
17354 MachineOperand &Segment = MI->getOperand(5);
17355 unsigned ArgSize = MI->getOperand(6).getImm();
17356 unsigned ArgMode = MI->getOperand(7).getImm();
17357 unsigned Align = MI->getOperand(8).getImm();
17359 // Memory Reference
17360 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17361 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17362 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17364 // Machine Information
17365 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17366 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17367 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17368 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17369 DebugLoc DL = MI->getDebugLoc();
17371 // struct va_list {
17374 // i64 overflow_area (address)
17375 // i64 reg_save_area (address)
17377 // sizeof(va_list) = 24
17378 // alignment(va_list) = 8
17380 unsigned TotalNumIntRegs = 6;
17381 unsigned TotalNumXMMRegs = 8;
17382 bool UseGPOffset = (ArgMode == 1);
17383 bool UseFPOffset = (ArgMode == 2);
17384 unsigned MaxOffset = TotalNumIntRegs * 8 +
17385 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17387 /* Align ArgSize to a multiple of 8 */
17388 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17389 bool NeedsAlign = (Align > 8);
17391 MachineBasicBlock *thisMBB = MBB;
17392 MachineBasicBlock *overflowMBB;
17393 MachineBasicBlock *offsetMBB;
17394 MachineBasicBlock *endMBB;
17396 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17397 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17398 unsigned OffsetReg = 0;
17400 if (!UseGPOffset && !UseFPOffset) {
17401 // If we only pull from the overflow region, we don't create a branch.
17402 // We don't need to alter control flow.
17403 OffsetDestReg = 0; // unused
17404 OverflowDestReg = DestReg;
17406 offsetMBB = nullptr;
17407 overflowMBB = thisMBB;
17410 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17411 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17412 // If not, pull from overflow_area. (branch to overflowMBB)
17417 // offsetMBB overflowMBB
17422 // Registers for the PHI in endMBB
17423 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17424 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17426 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17427 MachineFunction *MF = MBB->getParent();
17428 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17429 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17430 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17432 MachineFunction::iterator MBBIter = MBB;
17435 // Insert the new basic blocks
17436 MF->insert(MBBIter, offsetMBB);
17437 MF->insert(MBBIter, overflowMBB);
17438 MF->insert(MBBIter, endMBB);
17440 // Transfer the remainder of MBB and its successor edges to endMBB.
17441 endMBB->splice(endMBB->begin(), thisMBB,
17442 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17443 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17445 // Make offsetMBB and overflowMBB successors of thisMBB
17446 thisMBB->addSuccessor(offsetMBB);
17447 thisMBB->addSuccessor(overflowMBB);
17449 // endMBB is a successor of both offsetMBB and overflowMBB
17450 offsetMBB->addSuccessor(endMBB);
17451 overflowMBB->addSuccessor(endMBB);
17453 // Load the offset value into a register
17454 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17455 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17459 .addDisp(Disp, UseFPOffset ? 4 : 0)
17460 .addOperand(Segment)
17461 .setMemRefs(MMOBegin, MMOEnd);
17463 // Check if there is enough room left to pull this argument.
17464 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17466 .addImm(MaxOffset + 8 - ArgSizeA8);
17468 // Branch to "overflowMBB" if offset >= max
17469 // Fall through to "offsetMBB" otherwise
17470 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17471 .addMBB(overflowMBB);
17474 // In offsetMBB, emit code to use the reg_save_area.
17476 assert(OffsetReg != 0);
17478 // Read the reg_save_area address.
17479 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17480 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17485 .addOperand(Segment)
17486 .setMemRefs(MMOBegin, MMOEnd);
17488 // Zero-extend the offset
17489 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17490 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17493 .addImm(X86::sub_32bit);
17495 // Add the offset to the reg_save_area to get the final address.
17496 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17497 .addReg(OffsetReg64)
17498 .addReg(RegSaveReg);
17500 // Compute the offset for the next argument
17501 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17502 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17504 .addImm(UseFPOffset ? 16 : 8);
17506 // Store it back into the va_list.
17507 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17511 .addDisp(Disp, UseFPOffset ? 4 : 0)
17512 .addOperand(Segment)
17513 .addReg(NextOffsetReg)
17514 .setMemRefs(MMOBegin, MMOEnd);
17517 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17522 // Emit code to use overflow area
17525 // Load the overflow_area address into a register.
17526 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17527 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17532 .addOperand(Segment)
17533 .setMemRefs(MMOBegin, MMOEnd);
17535 // If we need to align it, do so. Otherwise, just copy the address
17536 // to OverflowDestReg.
17538 // Align the overflow address
17539 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17540 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17542 // aligned_addr = (addr + (align-1)) & ~(align-1)
17543 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17544 .addReg(OverflowAddrReg)
17547 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17549 .addImm(~(uint64_t)(Align-1));
17551 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17552 .addReg(OverflowAddrReg);
17555 // Compute the next overflow address after this argument.
17556 // (the overflow address should be kept 8-byte aligned)
17557 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17558 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17559 .addReg(OverflowDestReg)
17560 .addImm(ArgSizeA8);
17562 // Store the new overflow address.
17563 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17568 .addOperand(Segment)
17569 .addReg(NextAddrReg)
17570 .setMemRefs(MMOBegin, MMOEnd);
17572 // If we branched, emit the PHI to the front of endMBB.
17574 BuildMI(*endMBB, endMBB->begin(), DL,
17575 TII->get(X86::PHI), DestReg)
17576 .addReg(OffsetDestReg).addMBB(offsetMBB)
17577 .addReg(OverflowDestReg).addMBB(overflowMBB);
17580 // Erase the pseudo instruction
17581 MI->eraseFromParent();
17586 MachineBasicBlock *
17587 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17589 MachineBasicBlock *MBB) const {
17590 // Emit code to save XMM registers to the stack. The ABI says that the
17591 // number of registers to save is given in %al, so it's theoretically
17592 // possible to do an indirect jump trick to avoid saving all of them,
17593 // however this code takes a simpler approach and just executes all
17594 // of the stores if %al is non-zero. It's less code, and it's probably
17595 // easier on the hardware branch predictor, and stores aren't all that
17596 // expensive anyway.
17598 // Create the new basic blocks. One block contains all the XMM stores,
17599 // and one block is the final destination regardless of whether any
17600 // stores were performed.
17601 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17602 MachineFunction *F = MBB->getParent();
17603 MachineFunction::iterator MBBIter = MBB;
17605 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17606 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17607 F->insert(MBBIter, XMMSaveMBB);
17608 F->insert(MBBIter, EndMBB);
17610 // Transfer the remainder of MBB and its successor edges to EndMBB.
17611 EndMBB->splice(EndMBB->begin(), MBB,
17612 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17613 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17615 // The original block will now fall through to the XMM save block.
17616 MBB->addSuccessor(XMMSaveMBB);
17617 // The XMMSaveMBB will fall through to the end block.
17618 XMMSaveMBB->addSuccessor(EndMBB);
17620 // Now add the instructions.
17621 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17622 DebugLoc DL = MI->getDebugLoc();
17624 unsigned CountReg = MI->getOperand(0).getReg();
17625 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17626 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17628 if (!Subtarget->isTargetWin64()) {
17629 // If %al is 0, branch around the XMM save block.
17630 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17631 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17632 MBB->addSuccessor(EndMBB);
17635 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17636 // that was just emitted, but clearly shouldn't be "saved".
17637 assert((MI->getNumOperands() <= 3 ||
17638 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17639 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17640 && "Expected last argument to be EFLAGS");
17641 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17642 // In the XMM save block, save all the XMM argument registers.
17643 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17644 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17645 MachineMemOperand *MMO =
17646 F->getMachineMemOperand(
17647 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17648 MachineMemOperand::MOStore,
17649 /*Size=*/16, /*Align=*/16);
17650 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17651 .addFrameIndex(RegSaveFrameIndex)
17652 .addImm(/*Scale=*/1)
17653 .addReg(/*IndexReg=*/0)
17654 .addImm(/*Disp=*/Offset)
17655 .addReg(/*Segment=*/0)
17656 .addReg(MI->getOperand(i).getReg())
17657 .addMemOperand(MMO);
17660 MI->eraseFromParent(); // The pseudo instruction is gone now.
17665 // The EFLAGS operand of SelectItr might be missing a kill marker
17666 // because there were multiple uses of EFLAGS, and ISel didn't know
17667 // which to mark. Figure out whether SelectItr should have had a
17668 // kill marker, and set it if it should. Returns the correct kill
17670 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17671 MachineBasicBlock* BB,
17672 const TargetRegisterInfo* TRI) {
17673 // Scan forward through BB for a use/def of EFLAGS.
17674 MachineBasicBlock::iterator miI(std::next(SelectItr));
17675 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17676 const MachineInstr& mi = *miI;
17677 if (mi.readsRegister(X86::EFLAGS))
17679 if (mi.definesRegister(X86::EFLAGS))
17680 break; // Should have kill-flag - update below.
17683 // If we hit the end of the block, check whether EFLAGS is live into a
17685 if (miI == BB->end()) {
17686 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17687 sEnd = BB->succ_end();
17688 sItr != sEnd; ++sItr) {
17689 MachineBasicBlock* succ = *sItr;
17690 if (succ->isLiveIn(X86::EFLAGS))
17695 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17696 // out. SelectMI should have a kill flag on EFLAGS.
17697 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17701 MachineBasicBlock *
17702 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17703 MachineBasicBlock *BB) const {
17704 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17705 DebugLoc DL = MI->getDebugLoc();
17707 // To "insert" a SELECT_CC instruction, we actually have to insert the
17708 // diamond control-flow pattern. The incoming instruction knows the
17709 // destination vreg to set, the condition code register to branch on, the
17710 // true/false values to select between, and a branch opcode to use.
17711 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17712 MachineFunction::iterator It = BB;
17718 // cmpTY ccX, r1, r2
17720 // fallthrough --> copy0MBB
17721 MachineBasicBlock *thisMBB = BB;
17722 MachineFunction *F = BB->getParent();
17723 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17724 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17725 F->insert(It, copy0MBB);
17726 F->insert(It, sinkMBB);
17728 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17729 // live into the sink and copy blocks.
17730 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17731 if (!MI->killsRegister(X86::EFLAGS) &&
17732 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17733 copy0MBB->addLiveIn(X86::EFLAGS);
17734 sinkMBB->addLiveIn(X86::EFLAGS);
17737 // Transfer the remainder of BB and its successor edges to sinkMBB.
17738 sinkMBB->splice(sinkMBB->begin(), BB,
17739 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17740 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17742 // Add the true and fallthrough blocks as its successors.
17743 BB->addSuccessor(copy0MBB);
17744 BB->addSuccessor(sinkMBB);
17746 // Create the conditional branch instruction.
17748 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17749 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17752 // %FalseValue = ...
17753 // # fallthrough to sinkMBB
17754 copy0MBB->addSuccessor(sinkMBB);
17757 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17759 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17760 TII->get(X86::PHI), MI->getOperand(0).getReg())
17761 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17762 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17764 MI->eraseFromParent(); // The pseudo instruction is gone now.
17768 MachineBasicBlock *
17769 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17770 bool Is64Bit) const {
17771 MachineFunction *MF = BB->getParent();
17772 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17773 DebugLoc DL = MI->getDebugLoc();
17774 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17776 assert(MF->shouldSplitStack());
17778 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17779 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17782 // ... [Till the alloca]
17783 // If stacklet is not large enough, jump to mallocMBB
17786 // Allocate by subtracting from RSP
17787 // Jump to continueMBB
17790 // Allocate by call to runtime
17794 // [rest of original BB]
17797 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17798 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17799 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17801 MachineRegisterInfo &MRI = MF->getRegInfo();
17802 const TargetRegisterClass *AddrRegClass =
17803 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17805 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17806 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17807 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17808 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17809 sizeVReg = MI->getOperand(1).getReg(),
17810 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17812 MachineFunction::iterator MBBIter = BB;
17815 MF->insert(MBBIter, bumpMBB);
17816 MF->insert(MBBIter, mallocMBB);
17817 MF->insert(MBBIter, continueMBB);
17819 continueMBB->splice(continueMBB->begin(), BB,
17820 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17821 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17823 // Add code to the main basic block to check if the stack limit has been hit,
17824 // and if so, jump to mallocMBB otherwise to bumpMBB.
17825 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17826 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17827 .addReg(tmpSPVReg).addReg(sizeVReg);
17828 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17829 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17830 .addReg(SPLimitVReg);
17831 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17833 // bumpMBB simply decreases the stack pointer, since we know the current
17834 // stacklet has enough space.
17835 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17836 .addReg(SPLimitVReg);
17837 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17838 .addReg(SPLimitVReg);
17839 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17841 // Calls into a routine in libgcc to allocate more space from the heap.
17842 const uint32_t *RegMask =
17843 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17845 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17847 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17848 .addExternalSymbol("__morestack_allocate_stack_space")
17849 .addRegMask(RegMask)
17850 .addReg(X86::RDI, RegState::Implicit)
17851 .addReg(X86::RAX, RegState::ImplicitDefine);
17853 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17855 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17856 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17857 .addExternalSymbol("__morestack_allocate_stack_space")
17858 .addRegMask(RegMask)
17859 .addReg(X86::EAX, RegState::ImplicitDefine);
17863 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17866 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17867 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17868 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17870 // Set up the CFG correctly.
17871 BB->addSuccessor(bumpMBB);
17872 BB->addSuccessor(mallocMBB);
17873 mallocMBB->addSuccessor(continueMBB);
17874 bumpMBB->addSuccessor(continueMBB);
17876 // Take care of the PHI nodes.
17877 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17878 MI->getOperand(0).getReg())
17879 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17880 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17882 // Delete the original pseudo instruction.
17883 MI->eraseFromParent();
17886 return continueMBB;
17889 MachineBasicBlock *
17890 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17891 MachineBasicBlock *BB) const {
17892 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17893 DebugLoc DL = MI->getDebugLoc();
17895 assert(!Subtarget->isTargetMacho());
17897 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17898 // non-trivial part is impdef of ESP.
17900 if (Subtarget->isTargetWin64()) {
17901 if (Subtarget->isTargetCygMing()) {
17902 // ___chkstk(Mingw64):
17903 // Clobbers R10, R11, RAX and EFLAGS.
17905 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17906 .addExternalSymbol("___chkstk")
17907 .addReg(X86::RAX, RegState::Implicit)
17908 .addReg(X86::RSP, RegState::Implicit)
17909 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17910 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17911 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17913 // __chkstk(MSVCRT): does not update stack pointer.
17914 // Clobbers R10, R11 and EFLAGS.
17915 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17916 .addExternalSymbol("__chkstk")
17917 .addReg(X86::RAX, RegState::Implicit)
17918 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17919 // RAX has the offset to be subtracted from RSP.
17920 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17925 const char *StackProbeSymbol =
17926 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17928 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17929 .addExternalSymbol(StackProbeSymbol)
17930 .addReg(X86::EAX, RegState::Implicit)
17931 .addReg(X86::ESP, RegState::Implicit)
17932 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17933 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17934 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17937 MI->eraseFromParent(); // The pseudo instruction is gone now.
17941 MachineBasicBlock *
17942 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17943 MachineBasicBlock *BB) const {
17944 // This is pretty easy. We're taking the value that we received from
17945 // our load from the relocation, sticking it in either RDI (x86-64)
17946 // or EAX and doing an indirect call. The return value will then
17947 // be in the normal return register.
17948 MachineFunction *F = BB->getParent();
17949 const X86InstrInfo *TII
17950 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17951 DebugLoc DL = MI->getDebugLoc();
17953 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17954 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17956 // Get a register mask for the lowered call.
17957 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17958 // proper register mask.
17959 const uint32_t *RegMask =
17960 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17961 if (Subtarget->is64Bit()) {
17962 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17963 TII->get(X86::MOV64rm), X86::RDI)
17965 .addImm(0).addReg(0)
17966 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17967 MI->getOperand(3).getTargetFlags())
17969 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17970 addDirectMem(MIB, X86::RDI);
17971 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17972 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17973 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17974 TII->get(X86::MOV32rm), X86::EAX)
17976 .addImm(0).addReg(0)
17977 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17978 MI->getOperand(3).getTargetFlags())
17980 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17981 addDirectMem(MIB, X86::EAX);
17982 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17984 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17985 TII->get(X86::MOV32rm), X86::EAX)
17986 .addReg(TII->getGlobalBaseReg(F))
17987 .addImm(0).addReg(0)
17988 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17989 MI->getOperand(3).getTargetFlags())
17991 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17992 addDirectMem(MIB, X86::EAX);
17993 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17996 MI->eraseFromParent(); // The pseudo instruction is gone now.
18000 MachineBasicBlock *
18001 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18002 MachineBasicBlock *MBB) const {
18003 DebugLoc DL = MI->getDebugLoc();
18004 MachineFunction *MF = MBB->getParent();
18005 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18006 MachineRegisterInfo &MRI = MF->getRegInfo();
18008 const BasicBlock *BB = MBB->getBasicBlock();
18009 MachineFunction::iterator I = MBB;
18012 // Memory Reference
18013 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18014 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18017 unsigned MemOpndSlot = 0;
18019 unsigned CurOp = 0;
18021 DstReg = MI->getOperand(CurOp++).getReg();
18022 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18023 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18024 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18025 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18027 MemOpndSlot = CurOp;
18029 MVT PVT = getPointerTy();
18030 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18031 "Invalid Pointer Size!");
18033 // For v = setjmp(buf), we generate
18036 // buf[LabelOffset] = restoreMBB
18037 // SjLjSetup restoreMBB
18043 // v = phi(main, restore)
18048 MachineBasicBlock *thisMBB = MBB;
18049 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18050 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18051 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18052 MF->insert(I, mainMBB);
18053 MF->insert(I, sinkMBB);
18054 MF->push_back(restoreMBB);
18056 MachineInstrBuilder MIB;
18058 // Transfer the remainder of BB and its successor edges to sinkMBB.
18059 sinkMBB->splice(sinkMBB->begin(), MBB,
18060 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18061 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18064 unsigned PtrStoreOpc = 0;
18065 unsigned LabelReg = 0;
18066 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18067 Reloc::Model RM = MF->getTarget().getRelocationModel();
18068 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18069 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18071 // Prepare IP either in reg or imm.
18072 if (!UseImmLabel) {
18073 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18074 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18075 LabelReg = MRI.createVirtualRegister(PtrRC);
18076 if (Subtarget->is64Bit()) {
18077 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18081 .addMBB(restoreMBB)
18084 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18085 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18086 .addReg(XII->getGlobalBaseReg(MF))
18089 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18093 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18095 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18096 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18097 if (i == X86::AddrDisp)
18098 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18100 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18103 MIB.addReg(LabelReg);
18105 MIB.addMBB(restoreMBB);
18106 MIB.setMemRefs(MMOBegin, MMOEnd);
18108 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18109 .addMBB(restoreMBB);
18111 const X86RegisterInfo *RegInfo =
18112 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18113 MIB.addRegMask(RegInfo->getNoPreservedMask());
18114 thisMBB->addSuccessor(mainMBB);
18115 thisMBB->addSuccessor(restoreMBB);
18119 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18120 mainMBB->addSuccessor(sinkMBB);
18123 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18124 TII->get(X86::PHI), DstReg)
18125 .addReg(mainDstReg).addMBB(mainMBB)
18126 .addReg(restoreDstReg).addMBB(restoreMBB);
18129 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18130 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18131 restoreMBB->addSuccessor(sinkMBB);
18133 MI->eraseFromParent();
18137 MachineBasicBlock *
18138 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18139 MachineBasicBlock *MBB) const {
18140 DebugLoc DL = MI->getDebugLoc();
18141 MachineFunction *MF = MBB->getParent();
18142 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18143 MachineRegisterInfo &MRI = MF->getRegInfo();
18145 // Memory Reference
18146 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18147 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18149 MVT PVT = getPointerTy();
18150 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18151 "Invalid Pointer Size!");
18153 const TargetRegisterClass *RC =
18154 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18155 unsigned Tmp = MRI.createVirtualRegister(RC);
18156 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18157 const X86RegisterInfo *RegInfo =
18158 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18159 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18160 unsigned SP = RegInfo->getStackRegister();
18162 MachineInstrBuilder MIB;
18164 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18165 const int64_t SPOffset = 2 * PVT.getStoreSize();
18167 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18168 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18171 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18172 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18173 MIB.addOperand(MI->getOperand(i));
18174 MIB.setMemRefs(MMOBegin, MMOEnd);
18176 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18177 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18178 if (i == X86::AddrDisp)
18179 MIB.addDisp(MI->getOperand(i), LabelOffset);
18181 MIB.addOperand(MI->getOperand(i));
18183 MIB.setMemRefs(MMOBegin, MMOEnd);
18185 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18186 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18187 if (i == X86::AddrDisp)
18188 MIB.addDisp(MI->getOperand(i), SPOffset);
18190 MIB.addOperand(MI->getOperand(i));
18192 MIB.setMemRefs(MMOBegin, MMOEnd);
18194 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18196 MI->eraseFromParent();
18200 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18201 // accumulator loops. Writing back to the accumulator allows the coalescer
18202 // to remove extra copies in the loop.
18203 MachineBasicBlock *
18204 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18205 MachineBasicBlock *MBB) const {
18206 MachineOperand &AddendOp = MI->getOperand(3);
18208 // Bail out early if the addend isn't a register - we can't switch these.
18209 if (!AddendOp.isReg())
18212 MachineFunction &MF = *MBB->getParent();
18213 MachineRegisterInfo &MRI = MF.getRegInfo();
18215 // Check whether the addend is defined by a PHI:
18216 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18217 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18218 if (!AddendDef.isPHI())
18221 // Look for the following pattern:
18223 // %addend = phi [%entry, 0], [%loop, %result]
18225 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18229 // %addend = phi [%entry, 0], [%loop, %result]
18231 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18233 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18234 assert(AddendDef.getOperand(i).isReg());
18235 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18236 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18237 if (&PHISrcInst == MI) {
18238 // Found a matching instruction.
18239 unsigned NewFMAOpc = 0;
18240 switch (MI->getOpcode()) {
18241 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18242 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18243 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18244 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18245 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18246 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18247 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18248 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18249 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18250 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18251 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18252 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18253 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18254 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18255 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18256 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18257 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18258 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18259 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18260 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18261 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18262 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18263 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18264 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18265 default: llvm_unreachable("Unrecognized FMA variant.");
18268 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18269 MachineInstrBuilder MIB =
18270 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18271 .addOperand(MI->getOperand(0))
18272 .addOperand(MI->getOperand(3))
18273 .addOperand(MI->getOperand(2))
18274 .addOperand(MI->getOperand(1));
18275 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18276 MI->eraseFromParent();
18283 MachineBasicBlock *
18284 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18285 MachineBasicBlock *BB) const {
18286 switch (MI->getOpcode()) {
18287 default: llvm_unreachable("Unexpected instr type to insert");
18288 case X86::TAILJMPd64:
18289 case X86::TAILJMPr64:
18290 case X86::TAILJMPm64:
18291 llvm_unreachable("TAILJMP64 would not be touched here.");
18292 case X86::TCRETURNdi64:
18293 case X86::TCRETURNri64:
18294 case X86::TCRETURNmi64:
18296 case X86::WIN_ALLOCA:
18297 return EmitLoweredWinAlloca(MI, BB);
18298 case X86::SEG_ALLOCA_32:
18299 return EmitLoweredSegAlloca(MI, BB, false);
18300 case X86::SEG_ALLOCA_64:
18301 return EmitLoweredSegAlloca(MI, BB, true);
18302 case X86::TLSCall_32:
18303 case X86::TLSCall_64:
18304 return EmitLoweredTLSCall(MI, BB);
18305 case X86::CMOV_GR8:
18306 case X86::CMOV_FR32:
18307 case X86::CMOV_FR64:
18308 case X86::CMOV_V4F32:
18309 case X86::CMOV_V2F64:
18310 case X86::CMOV_V2I64:
18311 case X86::CMOV_V8F32:
18312 case X86::CMOV_V4F64:
18313 case X86::CMOV_V4I64:
18314 case X86::CMOV_V16F32:
18315 case X86::CMOV_V8F64:
18316 case X86::CMOV_V8I64:
18317 case X86::CMOV_GR16:
18318 case X86::CMOV_GR32:
18319 case X86::CMOV_RFP32:
18320 case X86::CMOV_RFP64:
18321 case X86::CMOV_RFP80:
18322 return EmitLoweredSelect(MI, BB);
18324 case X86::FP32_TO_INT16_IN_MEM:
18325 case X86::FP32_TO_INT32_IN_MEM:
18326 case X86::FP32_TO_INT64_IN_MEM:
18327 case X86::FP64_TO_INT16_IN_MEM:
18328 case X86::FP64_TO_INT32_IN_MEM:
18329 case X86::FP64_TO_INT64_IN_MEM:
18330 case X86::FP80_TO_INT16_IN_MEM:
18331 case X86::FP80_TO_INT32_IN_MEM:
18332 case X86::FP80_TO_INT64_IN_MEM: {
18333 MachineFunction *F = BB->getParent();
18334 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18335 DebugLoc DL = MI->getDebugLoc();
18337 // Change the floating point control register to use "round towards zero"
18338 // mode when truncating to an integer value.
18339 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18340 addFrameReference(BuildMI(*BB, MI, DL,
18341 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18343 // Load the old value of the high byte of the control word...
18345 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18346 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18349 // Set the high part to be round to zero...
18350 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18353 // Reload the modified control word now...
18354 addFrameReference(BuildMI(*BB, MI, DL,
18355 TII->get(X86::FLDCW16m)), CWFrameIdx);
18357 // Restore the memory image of control word to original value
18358 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18361 // Get the X86 opcode to use.
18363 switch (MI->getOpcode()) {
18364 default: llvm_unreachable("illegal opcode!");
18365 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18366 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18367 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18368 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18369 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18370 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18371 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18372 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18373 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18377 MachineOperand &Op = MI->getOperand(0);
18379 AM.BaseType = X86AddressMode::RegBase;
18380 AM.Base.Reg = Op.getReg();
18382 AM.BaseType = X86AddressMode::FrameIndexBase;
18383 AM.Base.FrameIndex = Op.getIndex();
18385 Op = MI->getOperand(1);
18387 AM.Scale = Op.getImm();
18388 Op = MI->getOperand(2);
18390 AM.IndexReg = Op.getImm();
18391 Op = MI->getOperand(3);
18392 if (Op.isGlobal()) {
18393 AM.GV = Op.getGlobal();
18395 AM.Disp = Op.getImm();
18397 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18398 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18400 // Reload the original control word now.
18401 addFrameReference(BuildMI(*BB, MI, DL,
18402 TII->get(X86::FLDCW16m)), CWFrameIdx);
18404 MI->eraseFromParent(); // The pseudo instruction is gone now.
18407 // String/text processing lowering.
18408 case X86::PCMPISTRM128REG:
18409 case X86::VPCMPISTRM128REG:
18410 case X86::PCMPISTRM128MEM:
18411 case X86::VPCMPISTRM128MEM:
18412 case X86::PCMPESTRM128REG:
18413 case X86::VPCMPESTRM128REG:
18414 case X86::PCMPESTRM128MEM:
18415 case X86::VPCMPESTRM128MEM:
18416 assert(Subtarget->hasSSE42() &&
18417 "Target must have SSE4.2 or AVX features enabled");
18418 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18420 // String/text processing lowering.
18421 case X86::PCMPISTRIREG:
18422 case X86::VPCMPISTRIREG:
18423 case X86::PCMPISTRIMEM:
18424 case X86::VPCMPISTRIMEM:
18425 case X86::PCMPESTRIREG:
18426 case X86::VPCMPESTRIREG:
18427 case X86::PCMPESTRIMEM:
18428 case X86::VPCMPESTRIMEM:
18429 assert(Subtarget->hasSSE42() &&
18430 "Target must have SSE4.2 or AVX features enabled");
18431 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18433 // Thread synchronization.
18435 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18439 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18441 case X86::VASTART_SAVE_XMM_REGS:
18442 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18444 case X86::VAARG_64:
18445 return EmitVAARG64WithCustomInserter(MI, BB);
18447 case X86::EH_SjLj_SetJmp32:
18448 case X86::EH_SjLj_SetJmp64:
18449 return emitEHSjLjSetJmp(MI, BB);
18451 case X86::EH_SjLj_LongJmp32:
18452 case X86::EH_SjLj_LongJmp64:
18453 return emitEHSjLjLongJmp(MI, BB);
18455 case TargetOpcode::STACKMAP:
18456 case TargetOpcode::PATCHPOINT:
18457 return emitPatchPoint(MI, BB);
18459 case X86::VFMADDPDr213r:
18460 case X86::VFMADDPSr213r:
18461 case X86::VFMADDSDr213r:
18462 case X86::VFMADDSSr213r:
18463 case X86::VFMSUBPDr213r:
18464 case X86::VFMSUBPSr213r:
18465 case X86::VFMSUBSDr213r:
18466 case X86::VFMSUBSSr213r:
18467 case X86::VFNMADDPDr213r:
18468 case X86::VFNMADDPSr213r:
18469 case X86::VFNMADDSDr213r:
18470 case X86::VFNMADDSSr213r:
18471 case X86::VFNMSUBPDr213r:
18472 case X86::VFNMSUBPSr213r:
18473 case X86::VFNMSUBSDr213r:
18474 case X86::VFNMSUBSSr213r:
18475 case X86::VFMADDPDr213rY:
18476 case X86::VFMADDPSr213rY:
18477 case X86::VFMSUBPDr213rY:
18478 case X86::VFMSUBPSr213rY:
18479 case X86::VFNMADDPDr213rY:
18480 case X86::VFNMADDPSr213rY:
18481 case X86::VFNMSUBPDr213rY:
18482 case X86::VFNMSUBPSr213rY:
18483 return emitFMA3Instr(MI, BB);
18487 //===----------------------------------------------------------------------===//
18488 // X86 Optimization Hooks
18489 //===----------------------------------------------------------------------===//
18491 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18494 const SelectionDAG &DAG,
18495 unsigned Depth) const {
18496 unsigned BitWidth = KnownZero.getBitWidth();
18497 unsigned Opc = Op.getOpcode();
18498 assert((Opc >= ISD::BUILTIN_OP_END ||
18499 Opc == ISD::INTRINSIC_WO_CHAIN ||
18500 Opc == ISD::INTRINSIC_W_CHAIN ||
18501 Opc == ISD::INTRINSIC_VOID) &&
18502 "Should use MaskedValueIsZero if you don't know whether Op"
18503 " is a target node!");
18505 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18519 // These nodes' second result is a boolean.
18520 if (Op.getResNo() == 0)
18523 case X86ISD::SETCC:
18524 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18526 case ISD::INTRINSIC_WO_CHAIN: {
18527 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18528 unsigned NumLoBits = 0;
18531 case Intrinsic::x86_sse_movmsk_ps:
18532 case Intrinsic::x86_avx_movmsk_ps_256:
18533 case Intrinsic::x86_sse2_movmsk_pd:
18534 case Intrinsic::x86_avx_movmsk_pd_256:
18535 case Intrinsic::x86_mmx_pmovmskb:
18536 case Intrinsic::x86_sse2_pmovmskb_128:
18537 case Intrinsic::x86_avx2_pmovmskb: {
18538 // High bits of movmskp{s|d}, pmovmskb are known zero.
18540 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18541 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18542 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18543 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18544 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18545 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18546 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18547 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18549 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18558 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18560 const SelectionDAG &,
18561 unsigned Depth) const {
18562 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18563 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18564 return Op.getValueType().getScalarType().getSizeInBits();
18570 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18571 /// node is a GlobalAddress + offset.
18572 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18573 const GlobalValue* &GA,
18574 int64_t &Offset) const {
18575 if (N->getOpcode() == X86ISD::Wrapper) {
18576 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18577 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18578 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18582 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18585 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18586 /// same as extracting the high 128-bit part of 256-bit vector and then
18587 /// inserting the result into the low part of a new 256-bit vector
18588 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18589 EVT VT = SVOp->getValueType(0);
18590 unsigned NumElems = VT.getVectorNumElements();
18592 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18593 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18594 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18595 SVOp->getMaskElt(j) >= 0)
18601 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18602 /// same as extracting the low 128-bit part of 256-bit vector and then
18603 /// inserting the result into the high part of a new 256-bit vector
18604 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18605 EVT VT = SVOp->getValueType(0);
18606 unsigned NumElems = VT.getVectorNumElements();
18608 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18609 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18610 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18611 SVOp->getMaskElt(j) >= 0)
18617 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18618 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18619 TargetLowering::DAGCombinerInfo &DCI,
18620 const X86Subtarget* Subtarget) {
18622 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18623 SDValue V1 = SVOp->getOperand(0);
18624 SDValue V2 = SVOp->getOperand(1);
18625 EVT VT = SVOp->getValueType(0);
18626 unsigned NumElems = VT.getVectorNumElements();
18628 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18629 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18633 // V UNDEF BUILD_VECTOR UNDEF
18635 // CONCAT_VECTOR CONCAT_VECTOR
18638 // RESULT: V + zero extended
18640 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18641 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18642 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18645 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18648 // To match the shuffle mask, the first half of the mask should
18649 // be exactly the first vector, and all the rest a splat with the
18650 // first element of the second one.
18651 for (unsigned i = 0; i != NumElems/2; ++i)
18652 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18653 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18656 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18657 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18658 if (Ld->hasNUsesOfValue(1, 0)) {
18659 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18660 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18662 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18664 Ld->getPointerInfo(),
18665 Ld->getAlignment(),
18666 false/*isVolatile*/, true/*ReadMem*/,
18667 false/*WriteMem*/);
18669 // Make sure the newly-created LOAD is in the same position as Ld in
18670 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18671 // and update uses of Ld's output chain to use the TokenFactor.
18672 if (Ld->hasAnyUseOfValue(1)) {
18673 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18674 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18675 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18676 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18677 SDValue(ResNode.getNode(), 1));
18680 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18684 // Emit a zeroed vector and insert the desired subvector on its
18686 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18687 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18688 return DCI.CombineTo(N, InsV);
18691 //===--------------------------------------------------------------------===//
18692 // Combine some shuffles into subvector extracts and inserts:
18695 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18696 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18697 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18698 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18699 return DCI.CombineTo(N, InsV);
18702 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18703 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18704 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18705 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18706 return DCI.CombineTo(N, InsV);
18712 /// \brief Get the PSHUF-style mask from PSHUF node.
18714 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18715 /// PSHUF-style masks that can be reused with such instructions.
18716 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18717 SmallVector<int, 4> Mask;
18719 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18723 switch (N.getOpcode()) {
18724 case X86ISD::PSHUFD:
18726 case X86ISD::PSHUFLW:
18729 case X86ISD::PSHUFHW:
18730 Mask.erase(Mask.begin(), Mask.begin() + 4);
18731 for (int &M : Mask)
18735 llvm_unreachable("No valid shuffle instruction found!");
18739 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18741 /// We walk up the chain and look for a combinable shuffle, skipping over
18742 /// shuffles that we could hoist this shuffle's transformation past without
18743 /// altering anything.
18744 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18746 TargetLowering::DAGCombinerInfo &DCI) {
18747 assert(N.getOpcode() == X86ISD::PSHUFD &&
18748 "Called with something other than an x86 128-bit half shuffle!");
18751 // Walk up a single-use chain looking for a combinable shuffle.
18752 SDValue V = N.getOperand(0);
18753 for (; V.hasOneUse(); V = V.getOperand(0)) {
18754 switch (V.getOpcode()) {
18756 return false; // Nothing combined!
18759 // Skip bitcasts as we always know the type for the target specific
18763 case X86ISD::PSHUFD:
18764 // Found another dword shuffle.
18767 case X86ISD::PSHUFLW:
18768 // Check that the low words (being shuffled) are the identity in the
18769 // dword shuffle, and the high words are self-contained.
18770 if (Mask[0] != 0 || Mask[1] != 1 ||
18771 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18776 case X86ISD::PSHUFHW:
18777 // Check that the high words (being shuffled) are the identity in the
18778 // dword shuffle, and the low words are self-contained.
18779 if (Mask[2] != 2 || Mask[3] != 3 ||
18780 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18785 case X86ISD::UNPCKL:
18786 case X86ISD::UNPCKH:
18787 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18788 // shuffle into a preceding word shuffle.
18789 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18792 // Search for a half-shuffle which we can combine with.
18793 unsigned CombineOp =
18794 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18795 if (V.getOperand(0) != V.getOperand(1) ||
18796 !V->isOnlyUserOf(V.getOperand(0).getNode()))
18798 V = V.getOperand(0);
18800 switch (V.getOpcode()) {
18802 return false; // Nothing to combine.
18804 case X86ISD::PSHUFLW:
18805 case X86ISD::PSHUFHW:
18806 if (V.getOpcode() == CombineOp)
18811 V = V.getOperand(0);
18815 } while (V.hasOneUse());
18818 // Break out of the loop if we break out of the switch.
18822 if (!V.hasOneUse())
18823 // We fell out of the loop without finding a viable combining instruction.
18826 // Record the old value to use in RAUW-ing.
18829 // Merge this node's mask and our incoming mask.
18830 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18831 for (int &M : Mask)
18833 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18834 getV4X86ShuffleImm8ForMask(Mask, DAG));
18836 // It is possible that one of the combinable shuffles was completely absorbed
18837 // by the other, just replace it and revisit all users in that case.
18838 if (Old.getNode() == V.getNode()) {
18839 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18843 // Replace N with its operand as we're going to combine that shuffle away.
18844 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18846 // Replace the combinable shuffle with the combined one, updating all users
18847 // so that we re-evaluate the chain here.
18848 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18852 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18854 /// We walk up the chain, skipping shuffles of the other half and looking
18855 /// through shuffles which switch halves trying to find a shuffle of the same
18856 /// pair of dwords.
18857 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18859 TargetLowering::DAGCombinerInfo &DCI) {
18861 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18862 "Called with something other than an x86 128-bit half shuffle!");
18864 unsigned CombineOpcode = N.getOpcode();
18866 // Walk up a single-use chain looking for a combinable shuffle.
18867 SDValue V = N.getOperand(0);
18868 for (; V.hasOneUse(); V = V.getOperand(0)) {
18869 switch (V.getOpcode()) {
18871 return false; // Nothing combined!
18874 // Skip bitcasts as we always know the type for the target specific
18878 case X86ISD::PSHUFLW:
18879 case X86ISD::PSHUFHW:
18880 if (V.getOpcode() == CombineOpcode)
18883 // Other-half shuffles are no-ops.
18886 case X86ISD::PSHUFD: {
18887 // We can only handle pshufd if the half we are combining either stays in
18888 // its half, or switches to the other half. Bail if one of these isn't
18890 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18891 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18892 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18893 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18896 // Map the mask through the pshufd and keep walking up the chain.
18897 for (int i = 0; i < 4; ++i)
18898 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18900 // Switch halves if the pshufd does.
18902 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18906 // Break out of the loop if we break out of the switch.
18910 if (!V.hasOneUse())
18911 // We fell out of the loop without finding a viable combining instruction.
18914 // Record the old value to use in RAUW-ing.
18917 // Merge this node's mask and our incoming mask (adjusted to account for all
18918 // the pshufd instructions encountered).
18919 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18920 for (int &M : Mask)
18922 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18923 getV4X86ShuffleImm8ForMask(Mask, DAG));
18925 // Replace N with its operand as we're going to combine that shuffle away.
18926 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18928 // Replace the combinable shuffle with the combined one, updating all users
18929 // so that we re-evaluate the chain here.
18930 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18934 /// \brief Try to combine x86 target specific shuffles.
18935 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18936 TargetLowering::DAGCombinerInfo &DCI,
18937 const X86Subtarget *Subtarget) {
18939 MVT VT = N.getSimpleValueType();
18940 SmallVector<int, 4> Mask;
18942 switch (N.getOpcode()) {
18943 case X86ISD::PSHUFD:
18944 case X86ISD::PSHUFLW:
18945 case X86ISD::PSHUFHW:
18946 Mask = getPSHUFShuffleMask(N);
18947 assert(Mask.size() == 4);
18953 // Nuke no-op shuffles that show up after combining.
18954 if (isNoopShuffleMask(Mask))
18955 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18957 // Look for simplifications involving one or two shuffle instructions.
18958 SDValue V = N.getOperand(0);
18959 switch (N.getOpcode()) {
18962 case X86ISD::PSHUFLW:
18963 case X86ISD::PSHUFHW:
18964 assert(VT == MVT::v8i16);
18967 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18968 return SDValue(); // We combined away this shuffle, so we're done.
18970 // See if this reduces to a PSHUFD which is no more expensive and can
18971 // combine with more operations.
18972 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18973 areAdjacentMasksSequential(Mask)) {
18974 int DMask[] = {-1, -1, -1, -1};
18975 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18976 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18977 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18978 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18979 DCI.AddToWorklist(V.getNode());
18980 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18981 getV4X86ShuffleImm8ForMask(DMask, DAG));
18982 DCI.AddToWorklist(V.getNode());
18983 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18986 // Look for shuffle patterns which can be implemented as a single unpack.
18987 // FIXME: This doesn't handle the location of the PSHUFD generically, and
18988 // only works when we have a PSHUFD followed by two half-shuffles.
18989 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18990 (V.getOpcode() == X86ISD::PSHUFLW ||
18991 V.getOpcode() == X86ISD::PSHUFHW) &&
18992 V.getOpcode() != N.getOpcode() &&
18994 SDValue D = V.getOperand(0);
18995 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18996 D = D.getOperand(0);
18997 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
18998 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18999 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19000 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19001 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19003 for (int i = 0; i < 4; ++i) {
19004 WordMask[i + NOffset] = Mask[i] + NOffset;
19005 WordMask[i + VOffset] = VMask[i] + VOffset;
19007 // Map the word mask through the DWord mask.
19009 for (int i = 0; i < 8; ++i)
19010 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19011 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19012 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19013 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19014 std::begin(UnpackLoMask)) ||
19015 std::equal(std::begin(MappedMask), std::end(MappedMask),
19016 std::begin(UnpackHiMask))) {
19017 // We can replace all three shuffles with an unpack.
19018 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19019 DCI.AddToWorklist(V.getNode());
19020 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19022 DL, MVT::v8i16, V, V);
19029 case X86ISD::PSHUFD:
19030 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19031 return SDValue(); // We combined away this shuffle.
19039 /// PerformShuffleCombine - Performs several different shuffle combines.
19040 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19041 TargetLowering::DAGCombinerInfo &DCI,
19042 const X86Subtarget *Subtarget) {
19044 SDValue N0 = N->getOperand(0);
19045 SDValue N1 = N->getOperand(1);
19046 EVT VT = N->getValueType(0);
19048 // Don't create instructions with illegal types after legalize types has run.
19049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19050 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19053 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19054 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19055 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19056 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19058 // During Type Legalization, when promoting illegal vector types,
19059 // the backend might introduce new shuffle dag nodes and bitcasts.
19061 // This code performs the following transformation:
19062 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19063 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19065 // We do this only if both the bitcast and the BINOP dag nodes have
19066 // one use. Also, perform this transformation only if the new binary
19067 // operation is legal. This is to avoid introducing dag nodes that
19068 // potentially need to be further expanded (or custom lowered) into a
19069 // less optimal sequence of dag nodes.
19070 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19071 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19072 N0.getOpcode() == ISD::BITCAST) {
19073 SDValue BC0 = N0.getOperand(0);
19074 EVT SVT = BC0.getValueType();
19075 unsigned Opcode = BC0.getOpcode();
19076 unsigned NumElts = VT.getVectorNumElements();
19078 if (BC0.hasOneUse() && SVT.isVector() &&
19079 SVT.getVectorNumElements() * 2 == NumElts &&
19080 TLI.isOperationLegal(Opcode, VT)) {
19081 bool CanFold = false;
19093 unsigned SVTNumElts = SVT.getVectorNumElements();
19094 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19095 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19096 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19097 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19098 CanFold = SVOp->getMaskElt(i) < 0;
19101 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19102 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19103 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19104 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19109 // Only handle 128 wide vector from here on.
19110 if (!VT.is128BitVector())
19113 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19114 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19115 // consecutive, non-overlapping, and in the right order.
19116 SmallVector<SDValue, 16> Elts;
19117 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19118 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19120 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19124 if (isTargetShuffle(N->getOpcode())) {
19126 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19127 if (Shuffle.getNode())
19134 /// PerformTruncateCombine - Converts truncate operation to
19135 /// a sequence of vector shuffle operations.
19136 /// It is possible when we truncate 256-bit vector to 128-bit vector
19137 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19138 TargetLowering::DAGCombinerInfo &DCI,
19139 const X86Subtarget *Subtarget) {
19143 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19144 /// specific shuffle of a load can be folded into a single element load.
19145 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19146 /// shuffles have been customed lowered so we need to handle those here.
19147 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19148 TargetLowering::DAGCombinerInfo &DCI) {
19149 if (DCI.isBeforeLegalizeOps())
19152 SDValue InVec = N->getOperand(0);
19153 SDValue EltNo = N->getOperand(1);
19155 if (!isa<ConstantSDNode>(EltNo))
19158 EVT VT = InVec.getValueType();
19160 bool HasShuffleIntoBitcast = false;
19161 if (InVec.getOpcode() == ISD::BITCAST) {
19162 // Don't duplicate a load with other uses.
19163 if (!InVec.hasOneUse())
19165 EVT BCVT = InVec.getOperand(0).getValueType();
19166 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19168 InVec = InVec.getOperand(0);
19169 HasShuffleIntoBitcast = true;
19172 if (!isTargetShuffle(InVec.getOpcode()))
19175 // Don't duplicate a load with other uses.
19176 if (!InVec.hasOneUse())
19179 SmallVector<int, 16> ShuffleMask;
19181 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19185 // Select the input vector, guarding against out of range extract vector.
19186 unsigned NumElems = VT.getVectorNumElements();
19187 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19188 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19189 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19190 : InVec.getOperand(1);
19192 // If inputs to shuffle are the same for both ops, then allow 2 uses
19193 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19195 if (LdNode.getOpcode() == ISD::BITCAST) {
19196 // Don't duplicate a load with other uses.
19197 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19200 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19201 LdNode = LdNode.getOperand(0);
19204 if (!ISD::isNormalLoad(LdNode.getNode()))
19207 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19209 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19212 if (HasShuffleIntoBitcast) {
19213 // If there's a bitcast before the shuffle, check if the load type and
19214 // alignment is valid.
19215 unsigned Align = LN0->getAlignment();
19216 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19217 unsigned NewAlign = TLI.getDataLayout()->
19218 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19220 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19224 // All checks match so transform back to vector_shuffle so that DAG combiner
19225 // can finish the job
19228 // Create shuffle node taking into account the case that its a unary shuffle
19229 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19230 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19231 InVec.getOperand(0), Shuffle,
19233 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19234 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19238 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19239 /// generation and convert it from being a bunch of shuffles and extracts
19240 /// to a simple store and scalar loads to extract the elements.
19241 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19242 TargetLowering::DAGCombinerInfo &DCI) {
19243 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19244 if (NewOp.getNode())
19247 SDValue InputVector = N->getOperand(0);
19249 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19250 // from mmx to v2i32 has a single usage.
19251 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19252 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19253 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19254 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19255 N->getValueType(0),
19256 InputVector.getNode()->getOperand(0));
19258 // Only operate on vectors of 4 elements, where the alternative shuffling
19259 // gets to be more expensive.
19260 if (InputVector.getValueType() != MVT::v4i32)
19263 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19264 // single use which is a sign-extend or zero-extend, and all elements are
19266 SmallVector<SDNode *, 4> Uses;
19267 unsigned ExtractedElements = 0;
19268 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19269 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19270 if (UI.getUse().getResNo() != InputVector.getResNo())
19273 SDNode *Extract = *UI;
19274 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19277 if (Extract->getValueType(0) != MVT::i32)
19279 if (!Extract->hasOneUse())
19281 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19282 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19284 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19287 // Record which element was extracted.
19288 ExtractedElements |=
19289 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19291 Uses.push_back(Extract);
19294 // If not all the elements were used, this may not be worthwhile.
19295 if (ExtractedElements != 15)
19298 // Ok, we've now decided to do the transformation.
19299 SDLoc dl(InputVector);
19301 // Store the value to a temporary stack slot.
19302 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19303 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19304 MachinePointerInfo(), false, false, 0);
19306 // Replace each use (extract) with a load of the appropriate element.
19307 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19308 UE = Uses.end(); UI != UE; ++UI) {
19309 SDNode *Extract = *UI;
19311 // cOMpute the element's address.
19312 SDValue Idx = Extract->getOperand(1);
19314 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19315 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19316 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19317 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19319 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19320 StackPtr, OffsetVal);
19322 // Load the scalar.
19323 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19324 ScalarAddr, MachinePointerInfo(),
19325 false, false, false, 0);
19327 // Replace the exact with the load.
19328 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19331 // The replacement was made in place; don't return anything.
19335 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19336 static std::pair<unsigned, bool>
19337 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19338 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19339 if (!VT.isVector())
19340 return std::make_pair(0, false);
19342 bool NeedSplit = false;
19343 switch (VT.getSimpleVT().SimpleTy) {
19344 default: return std::make_pair(0, false);
19348 if (!Subtarget->hasAVX2())
19350 if (!Subtarget->hasAVX())
19351 return std::make_pair(0, false);
19356 if (!Subtarget->hasSSE2())
19357 return std::make_pair(0, false);
19360 // SSE2 has only a small subset of the operations.
19361 bool hasUnsigned = Subtarget->hasSSE41() ||
19362 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19363 bool hasSigned = Subtarget->hasSSE41() ||
19364 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19366 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19369 // Check for x CC y ? x : y.
19370 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19371 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19376 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19379 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19382 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19385 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19387 // Check for x CC y ? y : x -- a min/max with reversed arms.
19388 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19389 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19394 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19397 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19400 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19403 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19407 return std::make_pair(Opc, NeedSplit);
19411 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19412 const X86Subtarget *Subtarget) {
19414 SDValue Cond = N->getOperand(0);
19415 SDValue LHS = N->getOperand(1);
19416 SDValue RHS = N->getOperand(2);
19418 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19419 SDValue CondSrc = Cond->getOperand(0);
19420 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19421 Cond = CondSrc->getOperand(0);
19424 MVT VT = N->getSimpleValueType(0);
19425 MVT EltVT = VT.getVectorElementType();
19426 unsigned NumElems = VT.getVectorNumElements();
19427 // There is no blend with immediate in AVX-512.
19428 if (VT.is512BitVector())
19431 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19433 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19436 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19439 unsigned MaskValue = 0;
19440 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19443 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19444 for (unsigned i = 0; i < NumElems; ++i) {
19445 // Be sure we emit undef where we can.
19446 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19447 ShuffleMask[i] = -1;
19449 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19452 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19455 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19457 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19458 TargetLowering::DAGCombinerInfo &DCI,
19459 const X86Subtarget *Subtarget) {
19461 SDValue Cond = N->getOperand(0);
19462 // Get the LHS/RHS of the select.
19463 SDValue LHS = N->getOperand(1);
19464 SDValue RHS = N->getOperand(2);
19465 EVT VT = LHS.getValueType();
19466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19468 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19469 // instructions match the semantics of the common C idiom x<y?x:y but not
19470 // x<=y?x:y, because of how they handle negative zero (which can be
19471 // ignored in unsafe-math mode).
19472 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19473 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19474 (Subtarget->hasSSE2() ||
19475 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19476 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19478 unsigned Opcode = 0;
19479 // Check for x CC y ? x : y.
19480 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19481 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19485 // Converting this to a min would handle NaNs incorrectly, and swapping
19486 // the operands would cause it to handle comparisons between positive
19487 // and negative zero incorrectly.
19488 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19489 if (!DAG.getTarget().Options.UnsafeFPMath &&
19490 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19492 std::swap(LHS, RHS);
19494 Opcode = X86ISD::FMIN;
19497 // Converting this to a min would handle comparisons between positive
19498 // and negative zero incorrectly.
19499 if (!DAG.getTarget().Options.UnsafeFPMath &&
19500 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19502 Opcode = X86ISD::FMIN;
19505 // Converting this to a min would handle both negative zeros and NaNs
19506 // incorrectly, but we can swap the operands to fix both.
19507 std::swap(LHS, RHS);
19511 Opcode = X86ISD::FMIN;
19515 // Converting this to a max would handle comparisons between positive
19516 // and negative zero incorrectly.
19517 if (!DAG.getTarget().Options.UnsafeFPMath &&
19518 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19520 Opcode = X86ISD::FMAX;
19523 // Converting this to a max would handle NaNs incorrectly, and swapping
19524 // the operands would cause it to handle comparisons between positive
19525 // and negative zero incorrectly.
19526 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19527 if (!DAG.getTarget().Options.UnsafeFPMath &&
19528 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19530 std::swap(LHS, RHS);
19532 Opcode = X86ISD::FMAX;
19535 // Converting this to a max would handle both negative zeros and NaNs
19536 // incorrectly, but we can swap the operands to fix both.
19537 std::swap(LHS, RHS);
19541 Opcode = X86ISD::FMAX;
19544 // Check for x CC y ? y : x -- a min/max with reversed arms.
19545 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19546 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19550 // Converting this to a min would handle comparisons between positive
19551 // and negative zero incorrectly, and swapping the operands would
19552 // cause it to handle NaNs incorrectly.
19553 if (!DAG.getTarget().Options.UnsafeFPMath &&
19554 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19555 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19557 std::swap(LHS, RHS);
19559 Opcode = X86ISD::FMIN;
19562 // Converting this to a min would handle NaNs incorrectly.
19563 if (!DAG.getTarget().Options.UnsafeFPMath &&
19564 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19566 Opcode = X86ISD::FMIN;
19569 // Converting this to a min would handle both negative zeros and NaNs
19570 // incorrectly, but we can swap the operands to fix both.
19571 std::swap(LHS, RHS);
19575 Opcode = X86ISD::FMIN;
19579 // Converting this to a max would handle NaNs incorrectly.
19580 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19582 Opcode = X86ISD::FMAX;
19585 // Converting this to a max would handle comparisons between positive
19586 // and negative zero incorrectly, and swapping the operands would
19587 // cause it to handle NaNs incorrectly.
19588 if (!DAG.getTarget().Options.UnsafeFPMath &&
19589 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19590 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19592 std::swap(LHS, RHS);
19594 Opcode = X86ISD::FMAX;
19597 // Converting this to a max would handle both negative zeros and NaNs
19598 // incorrectly, but we can swap the operands to fix both.
19599 std::swap(LHS, RHS);
19603 Opcode = X86ISD::FMAX;
19609 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19612 EVT CondVT = Cond.getValueType();
19613 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19614 CondVT.getVectorElementType() == MVT::i1) {
19615 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19616 // lowering on AVX-512. In this case we convert it to
19617 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19618 // The same situation for all 128 and 256-bit vectors of i8 and i16
19619 EVT OpVT = LHS.getValueType();
19620 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19621 (OpVT.getVectorElementType() == MVT::i8 ||
19622 OpVT.getVectorElementType() == MVT::i16)) {
19623 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19624 DCI.AddToWorklist(Cond.getNode());
19625 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19628 // If this is a select between two integer constants, try to do some
19630 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19631 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19632 // Don't do this for crazy integer types.
19633 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19634 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19635 // so that TrueC (the true value) is larger than FalseC.
19636 bool NeedsCondInvert = false;
19638 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19639 // Efficiently invertible.
19640 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19641 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19642 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19643 NeedsCondInvert = true;
19644 std::swap(TrueC, FalseC);
19647 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19648 if (FalseC->getAPIntValue() == 0 &&
19649 TrueC->getAPIntValue().isPowerOf2()) {
19650 if (NeedsCondInvert) // Invert the condition if needed.
19651 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19652 DAG.getConstant(1, Cond.getValueType()));
19654 // Zero extend the condition if needed.
19655 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19657 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19658 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19659 DAG.getConstant(ShAmt, MVT::i8));
19662 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19663 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19664 if (NeedsCondInvert) // Invert the condition if needed.
19665 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19666 DAG.getConstant(1, Cond.getValueType()));
19668 // Zero extend the condition if needed.
19669 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19670 FalseC->getValueType(0), Cond);
19671 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19672 SDValue(FalseC, 0));
19675 // Optimize cases that will turn into an LEA instruction. This requires
19676 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19677 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19678 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19679 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19681 bool isFastMultiplier = false;
19683 switch ((unsigned char)Diff) {
19685 case 1: // result = add base, cond
19686 case 2: // result = lea base( , cond*2)
19687 case 3: // result = lea base(cond, cond*2)
19688 case 4: // result = lea base( , cond*4)
19689 case 5: // result = lea base(cond, cond*4)
19690 case 8: // result = lea base( , cond*8)
19691 case 9: // result = lea base(cond, cond*8)
19692 isFastMultiplier = true;
19697 if (isFastMultiplier) {
19698 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19699 if (NeedsCondInvert) // Invert the condition if needed.
19700 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19701 DAG.getConstant(1, Cond.getValueType()));
19703 // Zero extend the condition if needed.
19704 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19706 // Scale the condition by the difference.
19708 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19709 DAG.getConstant(Diff, Cond.getValueType()));
19711 // Add the base if non-zero.
19712 if (FalseC->getAPIntValue() != 0)
19713 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19714 SDValue(FalseC, 0));
19721 // Canonicalize max and min:
19722 // (x > y) ? x : y -> (x >= y) ? x : y
19723 // (x < y) ? x : y -> (x <= y) ? x : y
19724 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19725 // the need for an extra compare
19726 // against zero. e.g.
19727 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19729 // testl %edi, %edi
19731 // cmovgl %edi, %eax
19735 // cmovsl %eax, %edi
19736 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19737 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19738 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19739 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19744 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19745 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19746 Cond.getOperand(0), Cond.getOperand(1), NewCC);
19747 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19752 // Early exit check
19753 if (!TLI.isTypeLegal(VT))
19756 // Match VSELECTs into subs with unsigned saturation.
19757 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19758 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19759 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19760 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19761 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19763 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19764 // left side invert the predicate to simplify logic below.
19766 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19768 CC = ISD::getSetCCInverse(CC, true);
19769 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19773 if (Other.getNode() && Other->getNumOperands() == 2 &&
19774 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19775 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19776 SDValue CondRHS = Cond->getOperand(1);
19778 // Look for a general sub with unsigned saturation first.
19779 // x >= y ? x-y : 0 --> subus x, y
19780 // x > y ? x-y : 0 --> subus x, y
19781 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19782 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19783 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19785 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19786 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19787 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19788 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19789 // If the RHS is a constant we have to reverse the const
19790 // canonicalization.
19791 // x > C-1 ? x+-C : 0 --> subus x, C
19792 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19793 CondRHSConst->getAPIntValue() ==
19794 (-OpRHSConst->getAPIntValue() - 1))
19795 return DAG.getNode(
19796 X86ISD::SUBUS, DL, VT, OpLHS,
19797 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19799 // Another special case: If C was a sign bit, the sub has been
19800 // canonicalized into a xor.
19801 // FIXME: Would it be better to use computeKnownBits to determine
19802 // whether it's safe to decanonicalize the xor?
19803 // x s< 0 ? x^C : 0 --> subus x, C
19804 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19805 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19806 OpRHSConst->getAPIntValue().isSignBit())
19807 // Note that we have to rebuild the RHS constant here to ensure we
19808 // don't rely on particular values of undef lanes.
19809 return DAG.getNode(
19810 X86ISD::SUBUS, DL, VT, OpLHS,
19811 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19816 // Try to match a min/max vector operation.
19817 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19818 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19819 unsigned Opc = ret.first;
19820 bool NeedSplit = ret.second;
19822 if (Opc && NeedSplit) {
19823 unsigned NumElems = VT.getVectorNumElements();
19824 // Extract the LHS vectors
19825 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19826 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19828 // Extract the RHS vectors
19829 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19830 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19832 // Create min/max for each subvector
19833 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19834 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19836 // Merge the result
19837 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19839 return DAG.getNode(Opc, DL, VT, LHS, RHS);
19842 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19843 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19844 // Check if SETCC has already been promoted
19845 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19846 // Check that condition value type matches vselect operand type
19849 assert(Cond.getValueType().isVector() &&
19850 "vector select expects a vector selector!");
19852 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19853 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19855 if (!TValIsAllOnes && !FValIsAllZeros) {
19856 // Try invert the condition if true value is not all 1s and false value
19858 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19859 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19861 if (TValIsAllZeros || FValIsAllOnes) {
19862 SDValue CC = Cond.getOperand(2);
19863 ISD::CondCode NewCC =
19864 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19865 Cond.getOperand(0).getValueType().isInteger());
19866 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19867 std::swap(LHS, RHS);
19868 TValIsAllOnes = FValIsAllOnes;
19869 FValIsAllZeros = TValIsAllZeros;
19873 if (TValIsAllOnes || FValIsAllZeros) {
19876 if (TValIsAllOnes && FValIsAllZeros)
19878 else if (TValIsAllOnes)
19879 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19880 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19881 else if (FValIsAllZeros)
19882 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19883 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19885 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19889 // Try to fold this VSELECT into a MOVSS/MOVSD
19890 if (N->getOpcode() == ISD::VSELECT &&
19891 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19892 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19893 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19894 bool CanFold = false;
19895 unsigned NumElems = Cond.getNumOperands();
19899 if (isZero(Cond.getOperand(0))) {
19902 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19903 // fold (vselect <0,-1> -> (movsd A, B)
19904 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19905 CanFold = isAllOnes(Cond.getOperand(i));
19906 } else if (isAllOnes(Cond.getOperand(0))) {
19910 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19911 // fold (vselect <-1,0> -> (movsd B, A)
19912 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19913 CanFold = isZero(Cond.getOperand(i));
19917 if (VT == MVT::v4i32 || VT == MVT::v4f32)
19918 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19919 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19922 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19923 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19924 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19925 // (v2i64 (bitcast B)))))
19927 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19928 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19929 // (v2f64 (bitcast B)))))
19931 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19932 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19933 // (v2i64 (bitcast A)))))
19935 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19936 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19937 // (v2f64 (bitcast A)))))
19939 CanFold = (isZero(Cond.getOperand(0)) &&
19940 isZero(Cond.getOperand(1)) &&
19941 isAllOnes(Cond.getOperand(2)) &&
19942 isAllOnes(Cond.getOperand(3)));
19944 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19945 isAllOnes(Cond.getOperand(1)) &&
19946 isZero(Cond.getOperand(2)) &&
19947 isZero(Cond.getOperand(3))) {
19949 std::swap(LHS, RHS);
19953 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19954 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19955 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19956 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19958 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19964 // If we know that this node is legal then we know that it is going to be
19965 // matched by one of the SSE/AVX BLEND instructions. These instructions only
19966 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19967 // to simplify previous instructions.
19968 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19969 !DCI.isBeforeLegalize() &&
19970 // We explicitly check against v8i16 and v16i16 because, although
19971 // they're marked as Custom, they might only be legal when Cond is a
19972 // build_vector of constants. This will be taken care in a later
19974 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19975 VT != MVT::v8i16)) {
19976 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19978 // Don't optimize vector selects that map to mask-registers.
19982 // Check all uses of that condition operand to check whether it will be
19983 // consumed by non-BLEND instructions, which may depend on all bits are set
19985 for (SDNode::use_iterator I = Cond->use_begin(),
19986 E = Cond->use_end(); I != E; ++I)
19987 if (I->getOpcode() != ISD::VSELECT)
19988 // TODO: Add other opcodes eventually lowered into BLEND.
19991 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19992 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19994 APInt KnownZero, KnownOne;
19995 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19996 DCI.isBeforeLegalizeOps());
19997 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19998 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19999 DCI.CommitTargetLoweringOpt(TLO);
20002 // We should generate an X86ISD::BLENDI from a vselect if its argument
20003 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20004 // constants. This specific pattern gets generated when we split a
20005 // selector for a 512 bit vector in a machine without AVX512 (but with
20006 // 256-bit vectors), during legalization:
20008 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20010 // Iff we find this pattern and the build_vectors are built from
20011 // constants, we translate the vselect into a shuffle_vector that we
20012 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20013 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20014 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20015 if (Shuffle.getNode())
20022 // Check whether a boolean test is testing a boolean value generated by
20023 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20026 // Simplify the following patterns:
20027 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20028 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20029 // to (Op EFLAGS Cond)
20031 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20032 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20033 // to (Op EFLAGS !Cond)
20035 // where Op could be BRCOND or CMOV.
20037 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20038 // Quit if not CMP and SUB with its value result used.
20039 if (Cmp.getOpcode() != X86ISD::CMP &&
20040 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20043 // Quit if not used as a boolean value.
20044 if (CC != X86::COND_E && CC != X86::COND_NE)
20047 // Check CMP operands. One of them should be 0 or 1 and the other should be
20048 // an SetCC or extended from it.
20049 SDValue Op1 = Cmp.getOperand(0);
20050 SDValue Op2 = Cmp.getOperand(1);
20053 const ConstantSDNode* C = nullptr;
20054 bool needOppositeCond = (CC == X86::COND_E);
20055 bool checkAgainstTrue = false; // Is it a comparison against 1?
20057 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20059 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20061 else // Quit if all operands are not constants.
20064 if (C->getZExtValue() == 1) {
20065 needOppositeCond = !needOppositeCond;
20066 checkAgainstTrue = true;
20067 } else if (C->getZExtValue() != 0)
20068 // Quit if the constant is neither 0 or 1.
20071 bool truncatedToBoolWithAnd = false;
20072 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20073 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20074 SetCC.getOpcode() == ISD::TRUNCATE ||
20075 SetCC.getOpcode() == ISD::AND) {
20076 if (SetCC.getOpcode() == ISD::AND) {
20078 ConstantSDNode *CS;
20079 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20080 CS->getZExtValue() == 1)
20082 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20083 CS->getZExtValue() == 1)
20087 SetCC = SetCC.getOperand(OpIdx);
20088 truncatedToBoolWithAnd = true;
20090 SetCC = SetCC.getOperand(0);
20093 switch (SetCC.getOpcode()) {
20094 case X86ISD::SETCC_CARRY:
20095 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20096 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20097 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20098 // truncated to i1 using 'and'.
20099 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20101 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20102 "Invalid use of SETCC_CARRY!");
20104 case X86ISD::SETCC:
20105 // Set the condition code or opposite one if necessary.
20106 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20107 if (needOppositeCond)
20108 CC = X86::GetOppositeBranchCondition(CC);
20109 return SetCC.getOperand(1);
20110 case X86ISD::CMOV: {
20111 // Check whether false/true value has canonical one, i.e. 0 or 1.
20112 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20113 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20114 // Quit if true value is not a constant.
20117 // Quit if false value is not a constant.
20119 SDValue Op = SetCC.getOperand(0);
20120 // Skip 'zext' or 'trunc' node.
20121 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20122 Op.getOpcode() == ISD::TRUNCATE)
20123 Op = Op.getOperand(0);
20124 // A special case for rdrand/rdseed, where 0 is set if false cond is
20126 if ((Op.getOpcode() != X86ISD::RDRAND &&
20127 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20130 // Quit if false value is not the constant 0 or 1.
20131 bool FValIsFalse = true;
20132 if (FVal && FVal->getZExtValue() != 0) {
20133 if (FVal->getZExtValue() != 1)
20135 // If FVal is 1, opposite cond is needed.
20136 needOppositeCond = !needOppositeCond;
20137 FValIsFalse = false;
20139 // Quit if TVal is not the constant opposite of FVal.
20140 if (FValIsFalse && TVal->getZExtValue() != 1)
20142 if (!FValIsFalse && TVal->getZExtValue() != 0)
20144 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20145 if (needOppositeCond)
20146 CC = X86::GetOppositeBranchCondition(CC);
20147 return SetCC.getOperand(3);
20154 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20155 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20156 TargetLowering::DAGCombinerInfo &DCI,
20157 const X86Subtarget *Subtarget) {
20160 // If the flag operand isn't dead, don't touch this CMOV.
20161 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20164 SDValue FalseOp = N->getOperand(0);
20165 SDValue TrueOp = N->getOperand(1);
20166 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20167 SDValue Cond = N->getOperand(3);
20169 if (CC == X86::COND_E || CC == X86::COND_NE) {
20170 switch (Cond.getOpcode()) {
20174 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20175 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20176 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20182 Flags = checkBoolTestSetCCCombine(Cond, CC);
20183 if (Flags.getNode() &&
20184 // Extra check as FCMOV only supports a subset of X86 cond.
20185 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20186 SDValue Ops[] = { FalseOp, TrueOp,
20187 DAG.getConstant(CC, MVT::i8), Flags };
20188 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20191 // If this is a select between two integer constants, try to do some
20192 // optimizations. Note that the operands are ordered the opposite of SELECT
20194 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20195 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20196 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20197 // larger than FalseC (the false value).
20198 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20199 CC = X86::GetOppositeBranchCondition(CC);
20200 std::swap(TrueC, FalseC);
20201 std::swap(TrueOp, FalseOp);
20204 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20205 // This is efficient for any integer data type (including i8/i16) and
20207 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20208 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20209 DAG.getConstant(CC, MVT::i8), Cond);
20211 // Zero extend the condition if needed.
20212 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20214 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20215 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20216 DAG.getConstant(ShAmt, MVT::i8));
20217 if (N->getNumValues() == 2) // Dead flag value?
20218 return DCI.CombineTo(N, Cond, SDValue());
20222 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20223 // for any integer data type, including i8/i16.
20224 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20225 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20226 DAG.getConstant(CC, MVT::i8), Cond);
20228 // Zero extend the condition if needed.
20229 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20230 FalseC->getValueType(0), Cond);
20231 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20232 SDValue(FalseC, 0));
20234 if (N->getNumValues() == 2) // Dead flag value?
20235 return DCI.CombineTo(N, Cond, SDValue());
20239 // Optimize cases that will turn into an LEA instruction. This requires
20240 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20241 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20242 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20243 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20245 bool isFastMultiplier = false;
20247 switch ((unsigned char)Diff) {
20249 case 1: // result = add base, cond
20250 case 2: // result = lea base( , cond*2)
20251 case 3: // result = lea base(cond, cond*2)
20252 case 4: // result = lea base( , cond*4)
20253 case 5: // result = lea base(cond, cond*4)
20254 case 8: // result = lea base( , cond*8)
20255 case 9: // result = lea base(cond, cond*8)
20256 isFastMultiplier = true;
20261 if (isFastMultiplier) {
20262 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20263 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20264 DAG.getConstant(CC, MVT::i8), Cond);
20265 // Zero extend the condition if needed.
20266 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20268 // Scale the condition by the difference.
20270 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20271 DAG.getConstant(Diff, Cond.getValueType()));
20273 // Add the base if non-zero.
20274 if (FalseC->getAPIntValue() != 0)
20275 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20276 SDValue(FalseC, 0));
20277 if (N->getNumValues() == 2) // Dead flag value?
20278 return DCI.CombineTo(N, Cond, SDValue());
20285 // Handle these cases:
20286 // (select (x != c), e, c) -> select (x != c), e, x),
20287 // (select (x == c), c, e) -> select (x == c), x, e)
20288 // where the c is an integer constant, and the "select" is the combination
20289 // of CMOV and CMP.
20291 // The rationale for this change is that the conditional-move from a constant
20292 // needs two instructions, however, conditional-move from a register needs
20293 // only one instruction.
20295 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20296 // some instruction-combining opportunities. This opt needs to be
20297 // postponed as late as possible.
20299 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20300 // the DCI.xxxx conditions are provided to postpone the optimization as
20301 // late as possible.
20303 ConstantSDNode *CmpAgainst = nullptr;
20304 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20305 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20306 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20308 if (CC == X86::COND_NE &&
20309 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20310 CC = X86::GetOppositeBranchCondition(CC);
20311 std::swap(TrueOp, FalseOp);
20314 if (CC == X86::COND_E &&
20315 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20316 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20317 DAG.getConstant(CC, MVT::i8), Cond };
20318 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20326 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20327 const X86Subtarget *Subtarget) {
20328 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20330 default: return SDValue();
20331 // SSE/AVX/AVX2 blend intrinsics.
20332 case Intrinsic::x86_avx2_pblendvb:
20333 case Intrinsic::x86_avx2_pblendw:
20334 case Intrinsic::x86_avx2_pblendd_128:
20335 case Intrinsic::x86_avx2_pblendd_256:
20336 // Don't try to simplify this intrinsic if we don't have AVX2.
20337 if (!Subtarget->hasAVX2())
20340 case Intrinsic::x86_avx_blend_pd_256:
20341 case Intrinsic::x86_avx_blend_ps_256:
20342 case Intrinsic::x86_avx_blendv_pd_256:
20343 case Intrinsic::x86_avx_blendv_ps_256:
20344 // Don't try to simplify this intrinsic if we don't have AVX.
20345 if (!Subtarget->hasAVX())
20348 case Intrinsic::x86_sse41_pblendw:
20349 case Intrinsic::x86_sse41_blendpd:
20350 case Intrinsic::x86_sse41_blendps:
20351 case Intrinsic::x86_sse41_blendvps:
20352 case Intrinsic::x86_sse41_blendvpd:
20353 case Intrinsic::x86_sse41_pblendvb: {
20354 SDValue Op0 = N->getOperand(1);
20355 SDValue Op1 = N->getOperand(2);
20356 SDValue Mask = N->getOperand(3);
20358 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20359 if (!Subtarget->hasSSE41())
20362 // fold (blend A, A, Mask) -> A
20365 // fold (blend A, B, allZeros) -> A
20366 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20368 // fold (blend A, B, allOnes) -> B
20369 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20372 // Simplify the case where the mask is a constant i32 value.
20373 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20374 if (C->isNullValue())
20376 if (C->isAllOnesValue())
20383 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20384 case Intrinsic::x86_sse2_psrai_w:
20385 case Intrinsic::x86_sse2_psrai_d:
20386 case Intrinsic::x86_avx2_psrai_w:
20387 case Intrinsic::x86_avx2_psrai_d:
20388 case Intrinsic::x86_sse2_psra_w:
20389 case Intrinsic::x86_sse2_psra_d:
20390 case Intrinsic::x86_avx2_psra_w:
20391 case Intrinsic::x86_avx2_psra_d: {
20392 SDValue Op0 = N->getOperand(1);
20393 SDValue Op1 = N->getOperand(2);
20394 EVT VT = Op0.getValueType();
20395 assert(VT.isVector() && "Expected a vector type!");
20397 if (isa<BuildVectorSDNode>(Op1))
20398 Op1 = Op1.getOperand(0);
20400 if (!isa<ConstantSDNode>(Op1))
20403 EVT SVT = VT.getVectorElementType();
20404 unsigned SVTBits = SVT.getSizeInBits();
20406 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20407 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20408 uint64_t ShAmt = C.getZExtValue();
20410 // Don't try to convert this shift into a ISD::SRA if the shift
20411 // count is bigger than or equal to the element size.
20412 if (ShAmt >= SVTBits)
20415 // Trivial case: if the shift count is zero, then fold this
20416 // into the first operand.
20420 // Replace this packed shift intrinsic with a target independent
20422 SDValue Splat = DAG.getConstant(C, VT);
20423 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20428 /// PerformMulCombine - Optimize a single multiply with constant into two
20429 /// in order to implement it with two cheaper instructions, e.g.
20430 /// LEA + SHL, LEA + LEA.
20431 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20432 TargetLowering::DAGCombinerInfo &DCI) {
20433 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20436 EVT VT = N->getValueType(0);
20437 if (VT != MVT::i64)
20440 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20443 uint64_t MulAmt = C->getZExtValue();
20444 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20447 uint64_t MulAmt1 = 0;
20448 uint64_t MulAmt2 = 0;
20449 if ((MulAmt % 9) == 0) {
20451 MulAmt2 = MulAmt / 9;
20452 } else if ((MulAmt % 5) == 0) {
20454 MulAmt2 = MulAmt / 5;
20455 } else if ((MulAmt % 3) == 0) {
20457 MulAmt2 = MulAmt / 3;
20460 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20463 if (isPowerOf2_64(MulAmt2) &&
20464 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20465 // If second multiplifer is pow2, issue it first. We want the multiply by
20466 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20468 std::swap(MulAmt1, MulAmt2);
20471 if (isPowerOf2_64(MulAmt1))
20472 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20473 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20475 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20476 DAG.getConstant(MulAmt1, VT));
20478 if (isPowerOf2_64(MulAmt2))
20479 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20480 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20482 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20483 DAG.getConstant(MulAmt2, VT));
20485 // Do not add new nodes to DAG combiner worklist.
20486 DCI.CombineTo(N, NewMul, false);
20491 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20492 SDValue N0 = N->getOperand(0);
20493 SDValue N1 = N->getOperand(1);
20494 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20495 EVT VT = N0.getValueType();
20497 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20498 // since the result of setcc_c is all zero's or all ones.
20499 if (VT.isInteger() && !VT.isVector() &&
20500 N1C && N0.getOpcode() == ISD::AND &&
20501 N0.getOperand(1).getOpcode() == ISD::Constant) {
20502 SDValue N00 = N0.getOperand(0);
20503 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20504 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20505 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20506 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20507 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20508 APInt ShAmt = N1C->getAPIntValue();
20509 Mask = Mask.shl(ShAmt);
20511 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20512 N00, DAG.getConstant(Mask, VT));
20516 // Hardware support for vector shifts is sparse which makes us scalarize the
20517 // vector operations in many cases. Also, on sandybridge ADD is faster than
20519 // (shl V, 1) -> add V,V
20520 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20521 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20522 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20523 // We shift all of the values by one. In many cases we do not have
20524 // hardware support for this operation. This is better expressed as an ADD
20526 if (N1SplatC->getZExtValue() == 1)
20527 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20533 /// \brief Returns a vector of 0s if the node in input is a vector logical
20534 /// shift by a constant amount which is known to be bigger than or equal
20535 /// to the vector element size in bits.
20536 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20537 const X86Subtarget *Subtarget) {
20538 EVT VT = N->getValueType(0);
20540 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20541 (!Subtarget->hasInt256() ||
20542 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20545 SDValue Amt = N->getOperand(1);
20547 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20548 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20549 APInt ShiftAmt = AmtSplat->getAPIntValue();
20550 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20552 // SSE2/AVX2 logical shifts always return a vector of 0s
20553 // if the shift amount is bigger than or equal to
20554 // the element size. The constant shift amount will be
20555 // encoded as a 8-bit immediate.
20556 if (ShiftAmt.trunc(8).uge(MaxAmount))
20557 return getZeroVector(VT, Subtarget, DAG, DL);
20563 /// PerformShiftCombine - Combine shifts.
20564 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20565 TargetLowering::DAGCombinerInfo &DCI,
20566 const X86Subtarget *Subtarget) {
20567 if (N->getOpcode() == ISD::SHL) {
20568 SDValue V = PerformSHLCombine(N, DAG);
20569 if (V.getNode()) return V;
20572 if (N->getOpcode() != ISD::SRA) {
20573 // Try to fold this logical shift into a zero vector.
20574 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20575 if (V.getNode()) return V;
20581 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20582 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20583 // and friends. Likewise for OR -> CMPNEQSS.
20584 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20585 TargetLowering::DAGCombinerInfo &DCI,
20586 const X86Subtarget *Subtarget) {
20589 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20590 // we're requiring SSE2 for both.
20591 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20592 SDValue N0 = N->getOperand(0);
20593 SDValue N1 = N->getOperand(1);
20594 SDValue CMP0 = N0->getOperand(1);
20595 SDValue CMP1 = N1->getOperand(1);
20598 // The SETCCs should both refer to the same CMP.
20599 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20602 SDValue CMP00 = CMP0->getOperand(0);
20603 SDValue CMP01 = CMP0->getOperand(1);
20604 EVT VT = CMP00.getValueType();
20606 if (VT == MVT::f32 || VT == MVT::f64) {
20607 bool ExpectingFlags = false;
20608 // Check for any users that want flags:
20609 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20610 !ExpectingFlags && UI != UE; ++UI)
20611 switch (UI->getOpcode()) {
20616 ExpectingFlags = true;
20618 case ISD::CopyToReg:
20619 case ISD::SIGN_EXTEND:
20620 case ISD::ZERO_EXTEND:
20621 case ISD::ANY_EXTEND:
20625 if (!ExpectingFlags) {
20626 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20627 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20629 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20630 X86::CondCode tmp = cc0;
20635 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20636 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20637 // FIXME: need symbolic constants for these magic numbers.
20638 // See X86ATTInstPrinter.cpp:printSSECC().
20639 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20640 if (Subtarget->hasAVX512()) {
20641 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20642 CMP01, DAG.getConstant(x86cc, MVT::i8));
20643 if (N->getValueType(0) != MVT::i1)
20644 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20648 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20649 CMP00.getValueType(), CMP00, CMP01,
20650 DAG.getConstant(x86cc, MVT::i8));
20652 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20653 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20655 if (is64BitFP && !Subtarget->is64Bit()) {
20656 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20657 // 64-bit integer, since that's not a legal type. Since
20658 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20659 // bits, but can do this little dance to extract the lowest 32 bits
20660 // and work with those going forward.
20661 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20663 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20665 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20666 Vector32, DAG.getIntPtrConstant(0));
20670 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20671 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20672 DAG.getConstant(1, IntVT));
20673 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20674 return OneBitOfTruth;
20682 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20683 /// so it can be folded inside ANDNP.
20684 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20685 EVT VT = N->getValueType(0);
20687 // Match direct AllOnes for 128 and 256-bit vectors
20688 if (ISD::isBuildVectorAllOnes(N))
20691 // Look through a bit convert.
20692 if (N->getOpcode() == ISD::BITCAST)
20693 N = N->getOperand(0).getNode();
20695 // Sometimes the operand may come from a insert_subvector building a 256-bit
20697 if (VT.is256BitVector() &&
20698 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20699 SDValue V1 = N->getOperand(0);
20700 SDValue V2 = N->getOperand(1);
20702 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20703 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20704 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20705 ISD::isBuildVectorAllOnes(V2.getNode()))
20712 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20713 // register. In most cases we actually compare or select YMM-sized registers
20714 // and mixing the two types creates horrible code. This method optimizes
20715 // some of the transition sequences.
20716 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20717 TargetLowering::DAGCombinerInfo &DCI,
20718 const X86Subtarget *Subtarget) {
20719 EVT VT = N->getValueType(0);
20720 if (!VT.is256BitVector())
20723 assert((N->getOpcode() == ISD::ANY_EXTEND ||
20724 N->getOpcode() == ISD::ZERO_EXTEND ||
20725 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20727 SDValue Narrow = N->getOperand(0);
20728 EVT NarrowVT = Narrow->getValueType(0);
20729 if (!NarrowVT.is128BitVector())
20732 if (Narrow->getOpcode() != ISD::XOR &&
20733 Narrow->getOpcode() != ISD::AND &&
20734 Narrow->getOpcode() != ISD::OR)
20737 SDValue N0 = Narrow->getOperand(0);
20738 SDValue N1 = Narrow->getOperand(1);
20741 // The Left side has to be a trunc.
20742 if (N0.getOpcode() != ISD::TRUNCATE)
20745 // The type of the truncated inputs.
20746 EVT WideVT = N0->getOperand(0)->getValueType(0);
20750 // The right side has to be a 'trunc' or a constant vector.
20751 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20752 ConstantSDNode *RHSConstSplat = nullptr;
20753 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20754 RHSConstSplat = RHSBV->getConstantSplatNode();
20755 if (!RHSTrunc && !RHSConstSplat)
20758 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20760 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20763 // Set N0 and N1 to hold the inputs to the new wide operation.
20764 N0 = N0->getOperand(0);
20765 if (RHSConstSplat) {
20766 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20767 SDValue(RHSConstSplat, 0));
20768 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20769 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20770 } else if (RHSTrunc) {
20771 N1 = N1->getOperand(0);
20774 // Generate the wide operation.
20775 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20776 unsigned Opcode = N->getOpcode();
20778 case ISD::ANY_EXTEND:
20780 case ISD::ZERO_EXTEND: {
20781 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20782 APInt Mask = APInt::getAllOnesValue(InBits);
20783 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20784 return DAG.getNode(ISD::AND, DL, VT,
20785 Op, DAG.getConstant(Mask, VT));
20787 case ISD::SIGN_EXTEND:
20788 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20789 Op, DAG.getValueType(NarrowVT));
20791 llvm_unreachable("Unexpected opcode");
20795 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20796 TargetLowering::DAGCombinerInfo &DCI,
20797 const X86Subtarget *Subtarget) {
20798 EVT VT = N->getValueType(0);
20799 if (DCI.isBeforeLegalizeOps())
20802 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20806 // Create BEXTR instructions
20807 // BEXTR is ((X >> imm) & (2**size-1))
20808 if (VT == MVT::i32 || VT == MVT::i64) {
20809 SDValue N0 = N->getOperand(0);
20810 SDValue N1 = N->getOperand(1);
20813 // Check for BEXTR.
20814 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20815 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20816 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20817 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20818 if (MaskNode && ShiftNode) {
20819 uint64_t Mask = MaskNode->getZExtValue();
20820 uint64_t Shift = ShiftNode->getZExtValue();
20821 if (isMask_64(Mask)) {
20822 uint64_t MaskSize = CountPopulation_64(Mask);
20823 if (Shift + MaskSize <= VT.getSizeInBits())
20824 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20825 DAG.getConstant(Shift | (MaskSize << 8), VT));
20833 // Want to form ANDNP nodes:
20834 // 1) In the hopes of then easily combining them with OR and AND nodes
20835 // to form PBLEND/PSIGN.
20836 // 2) To match ANDN packed intrinsics
20837 if (VT != MVT::v2i64 && VT != MVT::v4i64)
20840 SDValue N0 = N->getOperand(0);
20841 SDValue N1 = N->getOperand(1);
20844 // Check LHS for vnot
20845 if (N0.getOpcode() == ISD::XOR &&
20846 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20847 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20848 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20850 // Check RHS for vnot
20851 if (N1.getOpcode() == ISD::XOR &&
20852 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20853 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20854 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20859 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20860 TargetLowering::DAGCombinerInfo &DCI,
20861 const X86Subtarget *Subtarget) {
20862 if (DCI.isBeforeLegalizeOps())
20865 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20869 SDValue N0 = N->getOperand(0);
20870 SDValue N1 = N->getOperand(1);
20871 EVT VT = N->getValueType(0);
20873 // look for psign/blend
20874 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20875 if (!Subtarget->hasSSSE3() ||
20876 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20879 // Canonicalize pandn to RHS
20880 if (N0.getOpcode() == X86ISD::ANDNP)
20882 // or (and (m, y), (pandn m, x))
20883 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20884 SDValue Mask = N1.getOperand(0);
20885 SDValue X = N1.getOperand(1);
20887 if (N0.getOperand(0) == Mask)
20888 Y = N0.getOperand(1);
20889 if (N0.getOperand(1) == Mask)
20890 Y = N0.getOperand(0);
20892 // Check to see if the mask appeared in both the AND and ANDNP and
20896 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20897 // Look through mask bitcast.
20898 if (Mask.getOpcode() == ISD::BITCAST)
20899 Mask = Mask.getOperand(0);
20900 if (X.getOpcode() == ISD::BITCAST)
20901 X = X.getOperand(0);
20902 if (Y.getOpcode() == ISD::BITCAST)
20903 Y = Y.getOperand(0);
20905 EVT MaskVT = Mask.getValueType();
20907 // Validate that the Mask operand is a vector sra node.
20908 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20909 // there is no psrai.b
20910 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20911 unsigned SraAmt = ~0;
20912 if (Mask.getOpcode() == ISD::SRA) {
20913 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20914 if (auto *AmtConst = AmtBV->getConstantSplatNode())
20915 SraAmt = AmtConst->getZExtValue();
20916 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20917 SDValue SraC = Mask.getOperand(1);
20918 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
20920 if ((SraAmt + 1) != EltBits)
20925 // Now we know we at least have a plendvb with the mask val. See if
20926 // we can form a psignb/w/d.
20927 // psign = x.type == y.type == mask.type && y = sub(0, x);
20928 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20929 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20930 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20931 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20932 "Unsupported VT for PSIGN");
20933 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20934 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20936 // PBLENDVB only available on SSE 4.1
20937 if (!Subtarget->hasSSE41())
20940 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20942 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20943 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20944 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20945 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20946 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20950 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20953 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20954 MachineFunction &MF = DAG.getMachineFunction();
20955 bool OptForSize = MF.getFunction()->getAttributes().
20956 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20958 // SHLD/SHRD instructions have lower register pressure, but on some
20959 // platforms they have higher latency than the equivalent
20960 // series of shifts/or that would otherwise be generated.
20961 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20962 // have higher latencies and we are not optimizing for size.
20963 if (!OptForSize && Subtarget->isSHLDSlow())
20966 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20968 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20970 if (!N0.hasOneUse() || !N1.hasOneUse())
20973 SDValue ShAmt0 = N0.getOperand(1);
20974 if (ShAmt0.getValueType() != MVT::i8)
20976 SDValue ShAmt1 = N1.getOperand(1);
20977 if (ShAmt1.getValueType() != MVT::i8)
20979 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20980 ShAmt0 = ShAmt0.getOperand(0);
20981 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20982 ShAmt1 = ShAmt1.getOperand(0);
20985 unsigned Opc = X86ISD::SHLD;
20986 SDValue Op0 = N0.getOperand(0);
20987 SDValue Op1 = N1.getOperand(0);
20988 if (ShAmt0.getOpcode() == ISD::SUB) {
20989 Opc = X86ISD::SHRD;
20990 std::swap(Op0, Op1);
20991 std::swap(ShAmt0, ShAmt1);
20994 unsigned Bits = VT.getSizeInBits();
20995 if (ShAmt1.getOpcode() == ISD::SUB) {
20996 SDValue Sum = ShAmt1.getOperand(0);
20997 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20998 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20999 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21000 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21001 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21002 return DAG.getNode(Opc, DL, VT,
21004 DAG.getNode(ISD::TRUNCATE, DL,
21007 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21008 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21010 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21011 return DAG.getNode(Opc, DL, VT,
21012 N0.getOperand(0), N1.getOperand(0),
21013 DAG.getNode(ISD::TRUNCATE, DL,
21020 // Generate NEG and CMOV for integer abs.
21021 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21022 EVT VT = N->getValueType(0);
21024 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21025 // 8-bit integer abs to NEG and CMOV.
21026 if (VT.isInteger() && VT.getSizeInBits() == 8)
21029 SDValue N0 = N->getOperand(0);
21030 SDValue N1 = N->getOperand(1);
21033 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21034 // and change it to SUB and CMOV.
21035 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21036 N0.getOpcode() == ISD::ADD &&
21037 N0.getOperand(1) == N1 &&
21038 N1.getOpcode() == ISD::SRA &&
21039 N1.getOperand(0) == N0.getOperand(0))
21040 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21041 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21042 // Generate SUB & CMOV.
21043 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21044 DAG.getConstant(0, VT), N0.getOperand(0));
21046 SDValue Ops[] = { N0.getOperand(0), Neg,
21047 DAG.getConstant(X86::COND_GE, MVT::i8),
21048 SDValue(Neg.getNode(), 1) };
21049 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21054 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21055 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21056 TargetLowering::DAGCombinerInfo &DCI,
21057 const X86Subtarget *Subtarget) {
21058 if (DCI.isBeforeLegalizeOps())
21061 if (Subtarget->hasCMov()) {
21062 SDValue RV = performIntegerAbsCombine(N, DAG);
21070 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21071 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21072 TargetLowering::DAGCombinerInfo &DCI,
21073 const X86Subtarget *Subtarget) {
21074 LoadSDNode *Ld = cast<LoadSDNode>(N);
21075 EVT RegVT = Ld->getValueType(0);
21076 EVT MemVT = Ld->getMemoryVT();
21078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21080 // On Sandybridge unaligned 256bit loads are inefficient.
21081 ISD::LoadExtType Ext = Ld->getExtensionType();
21082 unsigned Alignment = Ld->getAlignment();
21083 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21084 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21085 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21086 unsigned NumElems = RegVT.getVectorNumElements();
21090 SDValue Ptr = Ld->getBasePtr();
21091 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21093 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21095 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21096 Ld->getPointerInfo(), Ld->isVolatile(),
21097 Ld->isNonTemporal(), Ld->isInvariant(),
21099 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21100 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21101 Ld->getPointerInfo(), Ld->isVolatile(),
21102 Ld->isNonTemporal(), Ld->isInvariant(),
21103 std::min(16U, Alignment));
21104 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21106 Load2.getValue(1));
21108 SDValue NewVec = DAG.getUNDEF(RegVT);
21109 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21110 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21111 return DCI.CombineTo(N, NewVec, TF, true);
21117 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21118 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21119 const X86Subtarget *Subtarget) {
21120 StoreSDNode *St = cast<StoreSDNode>(N);
21121 EVT VT = St->getValue().getValueType();
21122 EVT StVT = St->getMemoryVT();
21124 SDValue StoredVal = St->getOperand(1);
21125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21127 // If we are saving a concatenation of two XMM registers, perform two stores.
21128 // On Sandy Bridge, 256-bit memory operations are executed by two
21129 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21130 // memory operation.
21131 unsigned Alignment = St->getAlignment();
21132 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21133 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21134 StVT == VT && !IsAligned) {
21135 unsigned NumElems = VT.getVectorNumElements();
21139 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21140 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21142 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21143 SDValue Ptr0 = St->getBasePtr();
21144 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21146 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21147 St->getPointerInfo(), St->isVolatile(),
21148 St->isNonTemporal(), Alignment);
21149 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21150 St->getPointerInfo(), St->isVolatile(),
21151 St->isNonTemporal(),
21152 std::min(16U, Alignment));
21153 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21156 // Optimize trunc store (of multiple scalars) to shuffle and store.
21157 // First, pack all of the elements in one place. Next, store to memory
21158 // in fewer chunks.
21159 if (St->isTruncatingStore() && VT.isVector()) {
21160 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21161 unsigned NumElems = VT.getVectorNumElements();
21162 assert(StVT != VT && "Cannot truncate to the same type");
21163 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21164 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21166 // From, To sizes and ElemCount must be pow of two
21167 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21168 // We are going to use the original vector elt for storing.
21169 // Accumulated smaller vector elements must be a multiple of the store size.
21170 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21172 unsigned SizeRatio = FromSz / ToSz;
21174 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21176 // Create a type on which we perform the shuffle
21177 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21178 StVT.getScalarType(), NumElems*SizeRatio);
21180 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21182 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21183 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21184 for (unsigned i = 0; i != NumElems; ++i)
21185 ShuffleVec[i] = i * SizeRatio;
21187 // Can't shuffle using an illegal type.
21188 if (!TLI.isTypeLegal(WideVecVT))
21191 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21192 DAG.getUNDEF(WideVecVT),
21194 // At this point all of the data is stored at the bottom of the
21195 // register. We now need to save it to mem.
21197 // Find the largest store unit
21198 MVT StoreType = MVT::i8;
21199 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21200 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21201 MVT Tp = (MVT::SimpleValueType)tp;
21202 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21206 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21207 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21208 (64 <= NumElems * ToSz))
21209 StoreType = MVT::f64;
21211 // Bitcast the original vector into a vector of store-size units
21212 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21213 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21214 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21215 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21216 SmallVector<SDValue, 8> Chains;
21217 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21218 TLI.getPointerTy());
21219 SDValue Ptr = St->getBasePtr();
21221 // Perform one or more big stores into memory.
21222 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21223 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21224 StoreType, ShuffWide,
21225 DAG.getIntPtrConstant(i));
21226 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21227 St->getPointerInfo(), St->isVolatile(),
21228 St->isNonTemporal(), St->getAlignment());
21229 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21230 Chains.push_back(Ch);
21233 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21236 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21237 // the FP state in cases where an emms may be missing.
21238 // A preferable solution to the general problem is to figure out the right
21239 // places to insert EMMS. This qualifies as a quick hack.
21241 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21242 if (VT.getSizeInBits() != 64)
21245 const Function *F = DAG.getMachineFunction().getFunction();
21246 bool NoImplicitFloatOps = F->getAttributes().
21247 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21248 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21249 && Subtarget->hasSSE2();
21250 if ((VT.isVector() ||
21251 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21252 isa<LoadSDNode>(St->getValue()) &&
21253 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21254 St->getChain().hasOneUse() && !St->isVolatile()) {
21255 SDNode* LdVal = St->getValue().getNode();
21256 LoadSDNode *Ld = nullptr;
21257 int TokenFactorIndex = -1;
21258 SmallVector<SDValue, 8> Ops;
21259 SDNode* ChainVal = St->getChain().getNode();
21260 // Must be a store of a load. We currently handle two cases: the load
21261 // is a direct child, and it's under an intervening TokenFactor. It is
21262 // possible to dig deeper under nested TokenFactors.
21263 if (ChainVal == LdVal)
21264 Ld = cast<LoadSDNode>(St->getChain());
21265 else if (St->getValue().hasOneUse() &&
21266 ChainVal->getOpcode() == ISD::TokenFactor) {
21267 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21268 if (ChainVal->getOperand(i).getNode() == LdVal) {
21269 TokenFactorIndex = i;
21270 Ld = cast<LoadSDNode>(St->getValue());
21272 Ops.push_back(ChainVal->getOperand(i));
21276 if (!Ld || !ISD::isNormalLoad(Ld))
21279 // If this is not the MMX case, i.e. we are just turning i64 load/store
21280 // into f64 load/store, avoid the transformation if there are multiple
21281 // uses of the loaded value.
21282 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21287 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21288 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21290 if (Subtarget->is64Bit() || F64IsLegal) {
21291 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21292 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21293 Ld->getPointerInfo(), Ld->isVolatile(),
21294 Ld->isNonTemporal(), Ld->isInvariant(),
21295 Ld->getAlignment());
21296 SDValue NewChain = NewLd.getValue(1);
21297 if (TokenFactorIndex != -1) {
21298 Ops.push_back(NewChain);
21299 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21301 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21302 St->getPointerInfo(),
21303 St->isVolatile(), St->isNonTemporal(),
21304 St->getAlignment());
21307 // Otherwise, lower to two pairs of 32-bit loads / stores.
21308 SDValue LoAddr = Ld->getBasePtr();
21309 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21310 DAG.getConstant(4, MVT::i32));
21312 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21313 Ld->getPointerInfo(),
21314 Ld->isVolatile(), Ld->isNonTemporal(),
21315 Ld->isInvariant(), Ld->getAlignment());
21316 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21317 Ld->getPointerInfo().getWithOffset(4),
21318 Ld->isVolatile(), Ld->isNonTemporal(),
21320 MinAlign(Ld->getAlignment(), 4));
21322 SDValue NewChain = LoLd.getValue(1);
21323 if (TokenFactorIndex != -1) {
21324 Ops.push_back(LoLd);
21325 Ops.push_back(HiLd);
21326 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21329 LoAddr = St->getBasePtr();
21330 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21331 DAG.getConstant(4, MVT::i32));
21333 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21334 St->getPointerInfo(),
21335 St->isVolatile(), St->isNonTemporal(),
21336 St->getAlignment());
21337 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21338 St->getPointerInfo().getWithOffset(4),
21340 St->isNonTemporal(),
21341 MinAlign(St->getAlignment(), 4));
21342 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21347 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21348 /// and return the operands for the horizontal operation in LHS and RHS. A
21349 /// horizontal operation performs the binary operation on successive elements
21350 /// of its first operand, then on successive elements of its second operand,
21351 /// returning the resulting values in a vector. For example, if
21352 /// A = < float a0, float a1, float a2, float a3 >
21354 /// B = < float b0, float b1, float b2, float b3 >
21355 /// then the result of doing a horizontal operation on A and B is
21356 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21357 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21358 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21359 /// set to A, RHS to B, and the routine returns 'true'.
21360 /// Note that the binary operation should have the property that if one of the
21361 /// operands is UNDEF then the result is UNDEF.
21362 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21363 // Look for the following pattern: if
21364 // A = < float a0, float a1, float a2, float a3 >
21365 // B = < float b0, float b1, float b2, float b3 >
21367 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21368 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21369 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21370 // which is A horizontal-op B.
21372 // At least one of the operands should be a vector shuffle.
21373 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21374 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21377 MVT VT = LHS.getSimpleValueType();
21379 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21380 "Unsupported vector type for horizontal add/sub");
21382 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21383 // operate independently on 128-bit lanes.
21384 unsigned NumElts = VT.getVectorNumElements();
21385 unsigned NumLanes = VT.getSizeInBits()/128;
21386 unsigned NumLaneElts = NumElts / NumLanes;
21387 assert((NumLaneElts % 2 == 0) &&
21388 "Vector type should have an even number of elements in each lane");
21389 unsigned HalfLaneElts = NumLaneElts/2;
21391 // View LHS in the form
21392 // LHS = VECTOR_SHUFFLE A, B, LMask
21393 // If LHS is not a shuffle then pretend it is the shuffle
21394 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21395 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21398 SmallVector<int, 16> LMask(NumElts);
21399 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21400 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21401 A = LHS.getOperand(0);
21402 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21403 B = LHS.getOperand(1);
21404 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21405 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21407 if (LHS.getOpcode() != ISD::UNDEF)
21409 for (unsigned i = 0; i != NumElts; ++i)
21413 // Likewise, view RHS in the form
21414 // RHS = VECTOR_SHUFFLE C, D, RMask
21416 SmallVector<int, 16> RMask(NumElts);
21417 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21418 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21419 C = RHS.getOperand(0);
21420 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21421 D = RHS.getOperand(1);
21422 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21423 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21425 if (RHS.getOpcode() != ISD::UNDEF)
21427 for (unsigned i = 0; i != NumElts; ++i)
21431 // Check that the shuffles are both shuffling the same vectors.
21432 if (!(A == C && B == D) && !(A == D && B == C))
21435 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21436 if (!A.getNode() && !B.getNode())
21439 // If A and B occur in reverse order in RHS, then "swap" them (which means
21440 // rewriting the mask).
21442 CommuteVectorShuffleMask(RMask, NumElts);
21444 // At this point LHS and RHS are equivalent to
21445 // LHS = VECTOR_SHUFFLE A, B, LMask
21446 // RHS = VECTOR_SHUFFLE A, B, RMask
21447 // Check that the masks correspond to performing a horizontal operation.
21448 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21449 for (unsigned i = 0; i != NumLaneElts; ++i) {
21450 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21452 // Ignore any UNDEF components.
21453 if (LIdx < 0 || RIdx < 0 ||
21454 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21455 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21458 // Check that successive elements are being operated on. If not, this is
21459 // not a horizontal operation.
21460 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21461 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21462 if (!(LIdx == Index && RIdx == Index + 1) &&
21463 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21468 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21469 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21473 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21474 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21475 const X86Subtarget *Subtarget) {
21476 EVT VT = N->getValueType(0);
21477 SDValue LHS = N->getOperand(0);
21478 SDValue RHS = N->getOperand(1);
21480 // Try to synthesize horizontal adds from adds of shuffles.
21481 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21482 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21483 isHorizontalBinOp(LHS, RHS, true))
21484 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21488 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21489 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21490 const X86Subtarget *Subtarget) {
21491 EVT VT = N->getValueType(0);
21492 SDValue LHS = N->getOperand(0);
21493 SDValue RHS = N->getOperand(1);
21495 // Try to synthesize horizontal subs from subs of shuffles.
21496 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21497 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21498 isHorizontalBinOp(LHS, RHS, false))
21499 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21503 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21504 /// X86ISD::FXOR nodes.
21505 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21506 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21507 // F[X]OR(0.0, x) -> x
21508 // F[X]OR(x, 0.0) -> x
21509 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21510 if (C->getValueAPF().isPosZero())
21511 return N->getOperand(1);
21512 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21513 if (C->getValueAPF().isPosZero())
21514 return N->getOperand(0);
21518 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21519 /// X86ISD::FMAX nodes.
21520 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21521 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21523 // Only perform optimizations if UnsafeMath is used.
21524 if (!DAG.getTarget().Options.UnsafeFPMath)
21527 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21528 // into FMINC and FMAXC, which are Commutative operations.
21529 unsigned NewOp = 0;
21530 switch (N->getOpcode()) {
21531 default: llvm_unreachable("unknown opcode");
21532 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21533 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21536 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21537 N->getOperand(0), N->getOperand(1));
21540 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21541 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21542 // FAND(0.0, x) -> 0.0
21543 // FAND(x, 0.0) -> 0.0
21544 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21545 if (C->getValueAPF().isPosZero())
21546 return N->getOperand(0);
21547 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21548 if (C->getValueAPF().isPosZero())
21549 return N->getOperand(1);
21553 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21554 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21555 // FANDN(x, 0.0) -> 0.0
21556 // FANDN(0.0, x) -> x
21557 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21558 if (C->getValueAPF().isPosZero())
21559 return N->getOperand(1);
21560 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21561 if (C->getValueAPF().isPosZero())
21562 return N->getOperand(1);
21566 static SDValue PerformBTCombine(SDNode *N,
21568 TargetLowering::DAGCombinerInfo &DCI) {
21569 // BT ignores high bits in the bit index operand.
21570 SDValue Op1 = N->getOperand(1);
21571 if (Op1.hasOneUse()) {
21572 unsigned BitWidth = Op1.getValueSizeInBits();
21573 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21574 APInt KnownZero, KnownOne;
21575 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21576 !DCI.isBeforeLegalizeOps());
21577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21578 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21579 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21580 DCI.CommitTargetLoweringOpt(TLO);
21585 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21586 SDValue Op = N->getOperand(0);
21587 if (Op.getOpcode() == ISD::BITCAST)
21588 Op = Op.getOperand(0);
21589 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21590 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21591 VT.getVectorElementType().getSizeInBits() ==
21592 OpVT.getVectorElementType().getSizeInBits()) {
21593 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21598 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21599 const X86Subtarget *Subtarget) {
21600 EVT VT = N->getValueType(0);
21601 if (!VT.isVector())
21604 SDValue N0 = N->getOperand(0);
21605 SDValue N1 = N->getOperand(1);
21606 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21609 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21610 // both SSE and AVX2 since there is no sign-extended shift right
21611 // operation on a vector with 64-bit elements.
21612 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21613 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21614 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21615 N0.getOpcode() == ISD::SIGN_EXTEND)) {
21616 SDValue N00 = N0.getOperand(0);
21618 // EXTLOAD has a better solution on AVX2,
21619 // it may be replaced with X86ISD::VSEXT node.
21620 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21621 if (!ISD::isNormalLoad(N00.getNode()))
21624 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21625 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21627 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21633 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21634 TargetLowering::DAGCombinerInfo &DCI,
21635 const X86Subtarget *Subtarget) {
21636 if (!DCI.isBeforeLegalizeOps())
21639 if (!Subtarget->hasFp256())
21642 EVT VT = N->getValueType(0);
21643 if (VT.isVector() && VT.getSizeInBits() == 256) {
21644 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21652 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21653 const X86Subtarget* Subtarget) {
21655 EVT VT = N->getValueType(0);
21657 // Let legalize expand this if it isn't a legal type yet.
21658 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21661 EVT ScalarVT = VT.getScalarType();
21662 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21663 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21666 SDValue A = N->getOperand(0);
21667 SDValue B = N->getOperand(1);
21668 SDValue C = N->getOperand(2);
21670 bool NegA = (A.getOpcode() == ISD::FNEG);
21671 bool NegB = (B.getOpcode() == ISD::FNEG);
21672 bool NegC = (C.getOpcode() == ISD::FNEG);
21674 // Negative multiplication when NegA xor NegB
21675 bool NegMul = (NegA != NegB);
21677 A = A.getOperand(0);
21679 B = B.getOperand(0);
21681 C = C.getOperand(0);
21685 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21687 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21689 return DAG.getNode(Opcode, dl, VT, A, B, C);
21692 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21693 TargetLowering::DAGCombinerInfo &DCI,
21694 const X86Subtarget *Subtarget) {
21695 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
21696 // (and (i32 x86isd::setcc_carry), 1)
21697 // This eliminates the zext. This transformation is necessary because
21698 // ISD::SETCC is always legalized to i8.
21700 SDValue N0 = N->getOperand(0);
21701 EVT VT = N->getValueType(0);
21703 if (N0.getOpcode() == ISD::AND &&
21705 N0.getOperand(0).hasOneUse()) {
21706 SDValue N00 = N0.getOperand(0);
21707 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21708 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21709 if (!C || C->getZExtValue() != 1)
21711 return DAG.getNode(ISD::AND, dl, VT,
21712 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21713 N00.getOperand(0), N00.getOperand(1)),
21714 DAG.getConstant(1, VT));
21718 if (N0.getOpcode() == ISD::TRUNCATE &&
21720 N0.getOperand(0).hasOneUse()) {
21721 SDValue N00 = N0.getOperand(0);
21722 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21723 return DAG.getNode(ISD::AND, dl, VT,
21724 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21725 N00.getOperand(0), N00.getOperand(1)),
21726 DAG.getConstant(1, VT));
21729 if (VT.is256BitVector()) {
21730 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21738 // Optimize x == -y --> x+y == 0
21739 // x != -y --> x+y != 0
21740 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21741 const X86Subtarget* Subtarget) {
21742 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21743 SDValue LHS = N->getOperand(0);
21744 SDValue RHS = N->getOperand(1);
21745 EVT VT = N->getValueType(0);
21748 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21750 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21751 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21752 LHS.getValueType(), RHS, LHS.getOperand(1));
21753 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21754 addV, DAG.getConstant(0, addV.getValueType()), CC);
21756 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21757 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21758 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21759 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21760 RHS.getValueType(), LHS, RHS.getOperand(1));
21761 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21762 addV, DAG.getConstant(0, addV.getValueType()), CC);
21765 if (VT.getScalarType() == MVT::i1) {
21766 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21767 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21768 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21769 if (!IsSEXT0 && !IsVZero0)
21771 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21772 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21773 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21775 if (!IsSEXT1 && !IsVZero1)
21778 if (IsSEXT0 && IsVZero1) {
21779 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21780 if (CC == ISD::SETEQ)
21781 return DAG.getNOT(DL, LHS.getOperand(0), VT);
21782 return LHS.getOperand(0);
21784 if (IsSEXT1 && IsVZero0) {
21785 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21786 if (CC == ISD::SETEQ)
21787 return DAG.getNOT(DL, RHS.getOperand(0), VT);
21788 return RHS.getOperand(0);
21795 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21796 const X86Subtarget *Subtarget) {
21798 MVT VT = N->getOperand(1)->getSimpleValueType(0);
21799 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21800 "X86insertps is only defined for v4x32");
21802 SDValue Ld = N->getOperand(1);
21803 if (MayFoldLoad(Ld)) {
21804 // Extract the countS bits from the immediate so we can get the proper
21805 // address when narrowing the vector load to a specific element.
21806 // When the second source op is a memory address, interps doesn't use
21807 // countS and just gets an f32 from that address.
21808 unsigned DestIndex =
21809 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21810 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21814 // Create this as a scalar to vector to match the instruction pattern.
21815 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21816 // countS bits are ignored when loading from memory on insertps, which
21817 // means we don't need to explicitly set them to 0.
21818 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21819 LoadScalarToVector, N->getOperand(2));
21822 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21823 // as "sbb reg,reg", since it can be extended without zext and produces
21824 // an all-ones bit which is more useful than 0/1 in some cases.
21825 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21828 return DAG.getNode(ISD::AND, DL, VT,
21829 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21830 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21831 DAG.getConstant(1, VT));
21832 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21833 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21834 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21835 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21838 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21839 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21840 TargetLowering::DAGCombinerInfo &DCI,
21841 const X86Subtarget *Subtarget) {
21843 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21844 SDValue EFLAGS = N->getOperand(1);
21846 if (CC == X86::COND_A) {
21847 // Try to convert COND_A into COND_B in an attempt to facilitate
21848 // materializing "setb reg".
21850 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21851 // cannot take an immediate as its first operand.
21853 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21854 EFLAGS.getValueType().isInteger() &&
21855 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21856 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21857 EFLAGS.getNode()->getVTList(),
21858 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21859 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21860 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21864 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21865 // a zext and produces an all-ones bit which is more useful than 0/1 in some
21867 if (CC == X86::COND_B)
21868 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21872 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21873 if (Flags.getNode()) {
21874 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21875 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21881 // Optimize branch condition evaluation.
21883 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21884 TargetLowering::DAGCombinerInfo &DCI,
21885 const X86Subtarget *Subtarget) {
21887 SDValue Chain = N->getOperand(0);
21888 SDValue Dest = N->getOperand(1);
21889 SDValue EFLAGS = N->getOperand(3);
21890 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21894 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21895 if (Flags.getNode()) {
21896 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21897 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21904 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
21905 SelectionDAG &DAG) {
21906 // Take advantage of vector comparisons producing 0 or -1 in each lane to
21907 // optimize away operation when it's from a constant.
21909 // The general transformation is:
21910 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
21911 // AND(VECTOR_CMP(x,y), constant2)
21912 // constant2 = UNARYOP(constant)
21914 // Early exit if this isn't a vector operation, the operand of the
21915 // unary operation isn't a bitwise AND, or if the sizes of the operations
21916 // aren't the same.
21917 EVT VT = N->getValueType(0);
21918 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
21919 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
21920 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
21923 // Now check that the other operand of the AND is a constant. We could
21924 // make the transformation for non-constant splats as well, but it's unclear
21925 // that would be a benefit as it would not eliminate any operations, just
21926 // perform one more step in scalar code before moving to the vector unit.
21927 if (BuildVectorSDNode *BV =
21928 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
21929 // Bail out if the vector isn't a constant.
21930 if (!BV->isConstant())
21933 // Everything checks out. Build up the new and improved node.
21935 EVT IntVT = BV->getValueType(0);
21936 // Create a new constant of the appropriate type for the transformed
21938 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
21939 // The AND node needs bitcasts to/from an integer vector type around it.
21940 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
21941 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
21942 N->getOperand(0)->getOperand(0), MaskConst);
21943 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
21950 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21951 const X86TargetLowering *XTLI) {
21952 // First try to optimize away the conversion entirely when it's
21953 // conditionally from a constant. Vectors only.
21954 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
21955 if (Res != SDValue())
21958 // Now move on to more general possibilities.
21959 SDValue Op0 = N->getOperand(0);
21960 EVT InVT = Op0->getValueType(0);
21962 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21963 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21965 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21966 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21967 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21970 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21971 // a 32-bit target where SSE doesn't support i64->FP operations.
21972 if (Op0.getOpcode() == ISD::LOAD) {
21973 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21974 EVT VT = Ld->getValueType(0);
21975 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21976 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21977 !XTLI->getSubtarget()->is64Bit() &&
21979 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21980 Ld->getChain(), Op0, DAG);
21981 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21988 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21989 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21990 X86TargetLowering::DAGCombinerInfo &DCI) {
21991 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21992 // the result is either zero or one (depending on the input carry bit).
21993 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21994 if (X86::isZeroNode(N->getOperand(0)) &&
21995 X86::isZeroNode(N->getOperand(1)) &&
21996 // We don't have a good way to replace an EFLAGS use, so only do this when
21998 SDValue(N, 1).use_empty()) {
22000 EVT VT = N->getValueType(0);
22001 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22002 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22003 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22004 DAG.getConstant(X86::COND_B,MVT::i8),
22006 DAG.getConstant(1, VT));
22007 return DCI.CombineTo(N, Res1, CarryOut);
22013 // fold (add Y, (sete X, 0)) -> adc 0, Y
22014 // (add Y, (setne X, 0)) -> sbb -1, Y
22015 // (sub (sete X, 0), Y) -> sbb 0, Y
22016 // (sub (setne X, 0), Y) -> adc -1, Y
22017 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22020 // Look through ZExts.
22021 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22022 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22025 SDValue SetCC = Ext.getOperand(0);
22026 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22029 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22030 if (CC != X86::COND_E && CC != X86::COND_NE)
22033 SDValue Cmp = SetCC.getOperand(1);
22034 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22035 !X86::isZeroNode(Cmp.getOperand(1)) ||
22036 !Cmp.getOperand(0).getValueType().isInteger())
22039 SDValue CmpOp0 = Cmp.getOperand(0);
22040 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22041 DAG.getConstant(1, CmpOp0.getValueType()));
22043 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22044 if (CC == X86::COND_NE)
22045 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22046 DL, OtherVal.getValueType(), OtherVal,
22047 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22048 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22049 DL, OtherVal.getValueType(), OtherVal,
22050 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22053 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22054 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22055 const X86Subtarget *Subtarget) {
22056 EVT VT = N->getValueType(0);
22057 SDValue Op0 = N->getOperand(0);
22058 SDValue Op1 = N->getOperand(1);
22060 // Try to synthesize horizontal adds from adds of shuffles.
22061 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22062 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22063 isHorizontalBinOp(Op0, Op1, true))
22064 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22066 return OptimizeConditionalInDecrement(N, DAG);
22069 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22070 const X86Subtarget *Subtarget) {
22071 SDValue Op0 = N->getOperand(0);
22072 SDValue Op1 = N->getOperand(1);
22074 // X86 can't encode an immediate LHS of a sub. See if we can push the
22075 // negation into a preceding instruction.
22076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22077 // If the RHS of the sub is a XOR with one use and a constant, invert the
22078 // immediate. Then add one to the LHS of the sub so we can turn
22079 // X-Y -> X+~Y+1, saving one register.
22080 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22081 isa<ConstantSDNode>(Op1.getOperand(1))) {
22082 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22083 EVT VT = Op0.getValueType();
22084 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22086 DAG.getConstant(~XorC, VT));
22087 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22088 DAG.getConstant(C->getAPIntValue()+1, VT));
22092 // Try to synthesize horizontal adds from adds of shuffles.
22093 EVT VT = N->getValueType(0);
22094 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22095 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22096 isHorizontalBinOp(Op0, Op1, true))
22097 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22099 return OptimizeConditionalInDecrement(N, DAG);
22102 /// performVZEXTCombine - Performs build vector combines
22103 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22104 TargetLowering::DAGCombinerInfo &DCI,
22105 const X86Subtarget *Subtarget) {
22106 // (vzext (bitcast (vzext (x)) -> (vzext x)
22107 SDValue In = N->getOperand(0);
22108 while (In.getOpcode() == ISD::BITCAST)
22109 In = In.getOperand(0);
22111 if (In.getOpcode() != X86ISD::VZEXT)
22114 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22118 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22119 DAGCombinerInfo &DCI) const {
22120 SelectionDAG &DAG = DCI.DAG;
22121 switch (N->getOpcode()) {
22123 case ISD::EXTRACT_VECTOR_ELT:
22124 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22126 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22127 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22128 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22129 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22130 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22131 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22134 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22135 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22136 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22137 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22138 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22139 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22140 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22141 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22142 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22144 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22146 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22147 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22148 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22149 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22150 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22151 case ISD::ANY_EXTEND:
22152 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22153 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22154 case ISD::SIGN_EXTEND_INREG:
22155 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22156 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22157 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22158 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22159 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22160 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22161 case X86ISD::SHUFP: // Handle all target specific shuffles
22162 case X86ISD::PALIGNR:
22163 case X86ISD::UNPCKH:
22164 case X86ISD::UNPCKL:
22165 case X86ISD::MOVHLPS:
22166 case X86ISD::MOVLHPS:
22167 case X86ISD::PSHUFD:
22168 case X86ISD::PSHUFHW:
22169 case X86ISD::PSHUFLW:
22170 case X86ISD::MOVSS:
22171 case X86ISD::MOVSD:
22172 case X86ISD::VPERMILP:
22173 case X86ISD::VPERM2X128:
22174 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22175 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22176 case ISD::INTRINSIC_WO_CHAIN:
22177 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22178 case X86ISD::INSERTPS:
22179 return PerformINSERTPSCombine(N, DAG, Subtarget);
22180 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22186 /// isTypeDesirableForOp - Return true if the target has native support for
22187 /// the specified value type and it is 'desirable' to use the type for the
22188 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22189 /// instruction encodings are longer and some i16 instructions are slow.
22190 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22191 if (!isTypeLegal(VT))
22193 if (VT != MVT::i16)
22200 case ISD::SIGN_EXTEND:
22201 case ISD::ZERO_EXTEND:
22202 case ISD::ANY_EXTEND:
22215 /// IsDesirableToPromoteOp - This method query the target whether it is
22216 /// beneficial for dag combiner to promote the specified node. If true, it
22217 /// should return the desired promotion type by reference.
22218 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22219 EVT VT = Op.getValueType();
22220 if (VT != MVT::i16)
22223 bool Promote = false;
22224 bool Commute = false;
22225 switch (Op.getOpcode()) {
22228 LoadSDNode *LD = cast<LoadSDNode>(Op);
22229 // If the non-extending load has a single use and it's not live out, then it
22230 // might be folded.
22231 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22232 Op.hasOneUse()*/) {
22233 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22234 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22235 // The only case where we'd want to promote LOAD (rather then it being
22236 // promoted as an operand is when it's only use is liveout.
22237 if (UI->getOpcode() != ISD::CopyToReg)
22244 case ISD::SIGN_EXTEND:
22245 case ISD::ZERO_EXTEND:
22246 case ISD::ANY_EXTEND:
22251 SDValue N0 = Op.getOperand(0);
22252 // Look out for (store (shl (load), x)).
22253 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22266 SDValue N0 = Op.getOperand(0);
22267 SDValue N1 = Op.getOperand(1);
22268 if (!Commute && MayFoldLoad(N1))
22270 // Avoid disabling potential load folding opportunities.
22271 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22273 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22283 //===----------------------------------------------------------------------===//
22284 // X86 Inline Assembly Support
22285 //===----------------------------------------------------------------------===//
22288 // Helper to match a string separated by whitespace.
22289 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22290 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22292 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22293 StringRef piece(*args[i]);
22294 if (!s.startswith(piece)) // Check if the piece matches.
22297 s = s.substr(piece.size());
22298 StringRef::size_type pos = s.find_first_not_of(" \t");
22299 if (pos == 0) // We matched a prefix.
22307 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22310 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22312 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22313 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22314 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22315 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22317 if (AsmPieces.size() == 3)
22319 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22326 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22327 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22329 std::string AsmStr = IA->getAsmString();
22331 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22332 if (!Ty || Ty->getBitWidth() % 16 != 0)
22335 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22336 SmallVector<StringRef, 4> AsmPieces;
22337 SplitString(AsmStr, AsmPieces, ";\n");
22339 switch (AsmPieces.size()) {
22340 default: return false;
22342 // FIXME: this should verify that we are targeting a 486 or better. If not,
22343 // we will turn this bswap into something that will be lowered to logical
22344 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22345 // lower so don't worry about this.
22347 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22348 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22349 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22350 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22351 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22352 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22353 // No need to check constraints, nothing other than the equivalent of
22354 // "=r,0" would be valid here.
22355 return IntrinsicLowering::LowerToByteSwap(CI);
22358 // rorw $$8, ${0:w} --> llvm.bswap.i16
22359 if (CI->getType()->isIntegerTy(16) &&
22360 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22361 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22362 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22364 const std::string &ConstraintsStr = IA->getConstraintString();
22365 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22366 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22367 if (clobbersFlagRegisters(AsmPieces))
22368 return IntrinsicLowering::LowerToByteSwap(CI);
22372 if (CI->getType()->isIntegerTy(32) &&
22373 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22374 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22375 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22376 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22378 const std::string &ConstraintsStr = IA->getConstraintString();
22379 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22380 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22381 if (clobbersFlagRegisters(AsmPieces))
22382 return IntrinsicLowering::LowerToByteSwap(CI);
22385 if (CI->getType()->isIntegerTy(64)) {
22386 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22387 if (Constraints.size() >= 2 &&
22388 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22389 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22390 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22391 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22392 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22393 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22394 return IntrinsicLowering::LowerToByteSwap(CI);
22402 /// getConstraintType - Given a constraint letter, return the type of
22403 /// constraint it is for this target.
22404 X86TargetLowering::ConstraintType
22405 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22406 if (Constraint.size() == 1) {
22407 switch (Constraint[0]) {
22418 return C_RegisterClass;
22442 return TargetLowering::getConstraintType(Constraint);
22445 /// Examine constraint type and operand type and determine a weight value.
22446 /// This object must already have been set up with the operand type
22447 /// and the current alternative constraint selected.
22448 TargetLowering::ConstraintWeight
22449 X86TargetLowering::getSingleConstraintMatchWeight(
22450 AsmOperandInfo &info, const char *constraint) const {
22451 ConstraintWeight weight = CW_Invalid;
22452 Value *CallOperandVal = info.CallOperandVal;
22453 // If we don't have a value, we can't do a match,
22454 // but allow it at the lowest weight.
22455 if (!CallOperandVal)
22457 Type *type = CallOperandVal->getType();
22458 // Look at the constraint type.
22459 switch (*constraint) {
22461 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22472 if (CallOperandVal->getType()->isIntegerTy())
22473 weight = CW_SpecificReg;
22478 if (type->isFloatingPointTy())
22479 weight = CW_SpecificReg;
22482 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22483 weight = CW_SpecificReg;
22487 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22488 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22489 weight = CW_Register;
22492 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22493 if (C->getZExtValue() <= 31)
22494 weight = CW_Constant;
22498 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22499 if (C->getZExtValue() <= 63)
22500 weight = CW_Constant;
22504 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22505 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22506 weight = CW_Constant;
22510 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22511 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22512 weight = CW_Constant;
22516 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22517 if (C->getZExtValue() <= 3)
22518 weight = CW_Constant;
22522 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22523 if (C->getZExtValue() <= 0xff)
22524 weight = CW_Constant;
22529 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22530 weight = CW_Constant;
22534 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22535 if ((C->getSExtValue() >= -0x80000000LL) &&
22536 (C->getSExtValue() <= 0x7fffffffLL))
22537 weight = CW_Constant;
22541 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22542 if (C->getZExtValue() <= 0xffffffff)
22543 weight = CW_Constant;
22550 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22551 /// with another that has more specific requirements based on the type of the
22552 /// corresponding operand.
22553 const char *X86TargetLowering::
22554 LowerXConstraint(EVT ConstraintVT) const {
22555 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22556 // 'f' like normal targets.
22557 if (ConstraintVT.isFloatingPoint()) {
22558 if (Subtarget->hasSSE2())
22560 if (Subtarget->hasSSE1())
22564 return TargetLowering::LowerXConstraint(ConstraintVT);
22567 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22568 /// vector. If it is invalid, don't add anything to Ops.
22569 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22570 std::string &Constraint,
22571 std::vector<SDValue>&Ops,
22572 SelectionDAG &DAG) const {
22575 // Only support length 1 constraints for now.
22576 if (Constraint.length() > 1) return;
22578 char ConstraintLetter = Constraint[0];
22579 switch (ConstraintLetter) {
22582 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22583 if (C->getZExtValue() <= 31) {
22584 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22590 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22591 if (C->getZExtValue() <= 63) {
22592 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22598 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22599 if (isInt<8>(C->getSExtValue())) {
22600 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22606 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22607 if (C->getZExtValue() <= 255) {
22608 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22614 // 32-bit signed value
22615 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22616 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22617 C->getSExtValue())) {
22618 // Widen to 64 bits here to get it sign extended.
22619 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22622 // FIXME gcc accepts some relocatable values here too, but only in certain
22623 // memory models; it's complicated.
22628 // 32-bit unsigned value
22629 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22630 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22631 C->getZExtValue())) {
22632 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22636 // FIXME gcc accepts some relocatable values here too, but only in certain
22637 // memory models; it's complicated.
22641 // Literal immediates are always ok.
22642 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22643 // Widen to 64 bits here to get it sign extended.
22644 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22648 // In any sort of PIC mode addresses need to be computed at runtime by
22649 // adding in a register or some sort of table lookup. These can't
22650 // be used as immediates.
22651 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22654 // If we are in non-pic codegen mode, we allow the address of a global (with
22655 // an optional displacement) to be used with 'i'.
22656 GlobalAddressSDNode *GA = nullptr;
22657 int64_t Offset = 0;
22659 // Match either (GA), (GA+C), (GA+C1+C2), etc.
22661 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22662 Offset += GA->getOffset();
22664 } else if (Op.getOpcode() == ISD::ADD) {
22665 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22666 Offset += C->getZExtValue();
22667 Op = Op.getOperand(0);
22670 } else if (Op.getOpcode() == ISD::SUB) {
22671 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22672 Offset += -C->getZExtValue();
22673 Op = Op.getOperand(0);
22678 // Otherwise, this isn't something we can handle, reject it.
22682 const GlobalValue *GV = GA->getGlobal();
22683 // If we require an extra load to get this address, as in PIC mode, we
22684 // can't accept it.
22685 if (isGlobalStubReference(
22686 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22689 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22690 GA->getValueType(0), Offset);
22695 if (Result.getNode()) {
22696 Ops.push_back(Result);
22699 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22702 std::pair<unsigned, const TargetRegisterClass*>
22703 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22705 // First, see if this is a constraint that directly corresponds to an LLVM
22707 if (Constraint.size() == 1) {
22708 // GCC Constraint Letters
22709 switch (Constraint[0]) {
22711 // TODO: Slight differences here in allocation order and leaving
22712 // RIP in the class. Do they matter any more here than they do
22713 // in the normal allocation?
22714 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22715 if (Subtarget->is64Bit()) {
22716 if (VT == MVT::i32 || VT == MVT::f32)
22717 return std::make_pair(0U, &X86::GR32RegClass);
22718 if (VT == MVT::i16)
22719 return std::make_pair(0U, &X86::GR16RegClass);
22720 if (VT == MVT::i8 || VT == MVT::i1)
22721 return std::make_pair(0U, &X86::GR8RegClass);
22722 if (VT == MVT::i64 || VT == MVT::f64)
22723 return std::make_pair(0U, &X86::GR64RegClass);
22726 // 32-bit fallthrough
22727 case 'Q': // Q_REGS
22728 if (VT == MVT::i32 || VT == MVT::f32)
22729 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22730 if (VT == MVT::i16)
22731 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22732 if (VT == MVT::i8 || VT == MVT::i1)
22733 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22734 if (VT == MVT::i64)
22735 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22737 case 'r': // GENERAL_REGS
22738 case 'l': // INDEX_REGS
22739 if (VT == MVT::i8 || VT == MVT::i1)
22740 return std::make_pair(0U, &X86::GR8RegClass);
22741 if (VT == MVT::i16)
22742 return std::make_pair(0U, &X86::GR16RegClass);
22743 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22744 return std::make_pair(0U, &X86::GR32RegClass);
22745 return std::make_pair(0U, &X86::GR64RegClass);
22746 case 'R': // LEGACY_REGS
22747 if (VT == MVT::i8 || VT == MVT::i1)
22748 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22749 if (VT == MVT::i16)
22750 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22751 if (VT == MVT::i32 || !Subtarget->is64Bit())
22752 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22753 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22754 case 'f': // FP Stack registers.
22755 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22756 // value to the correct fpstack register class.
22757 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22758 return std::make_pair(0U, &X86::RFP32RegClass);
22759 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22760 return std::make_pair(0U, &X86::RFP64RegClass);
22761 return std::make_pair(0U, &X86::RFP80RegClass);
22762 case 'y': // MMX_REGS if MMX allowed.
22763 if (!Subtarget->hasMMX()) break;
22764 return std::make_pair(0U, &X86::VR64RegClass);
22765 case 'Y': // SSE_REGS if SSE2 allowed
22766 if (!Subtarget->hasSSE2()) break;
22768 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22769 if (!Subtarget->hasSSE1()) break;
22771 switch (VT.SimpleTy) {
22773 // Scalar SSE types.
22776 return std::make_pair(0U, &X86::FR32RegClass);
22779 return std::make_pair(0U, &X86::FR64RegClass);
22787 return std::make_pair(0U, &X86::VR128RegClass);
22795 return std::make_pair(0U, &X86::VR256RegClass);
22800 return std::make_pair(0U, &X86::VR512RegClass);
22806 // Use the default implementation in TargetLowering to convert the register
22807 // constraint into a member of a register class.
22808 std::pair<unsigned, const TargetRegisterClass*> Res;
22809 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22811 // Not found as a standard register?
22813 // Map st(0) -> st(7) -> ST0
22814 if (Constraint.size() == 7 && Constraint[0] == '{' &&
22815 tolower(Constraint[1]) == 's' &&
22816 tolower(Constraint[2]) == 't' &&
22817 Constraint[3] == '(' &&
22818 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22819 Constraint[5] == ')' &&
22820 Constraint[6] == '}') {
22822 Res.first = X86::ST0+Constraint[4]-'0';
22823 Res.second = &X86::RFP80RegClass;
22827 // GCC allows "st(0)" to be called just plain "st".
22828 if (StringRef("{st}").equals_lower(Constraint)) {
22829 Res.first = X86::ST0;
22830 Res.second = &X86::RFP80RegClass;
22835 if (StringRef("{flags}").equals_lower(Constraint)) {
22836 Res.first = X86::EFLAGS;
22837 Res.second = &X86::CCRRegClass;
22841 // 'A' means EAX + EDX.
22842 if (Constraint == "A") {
22843 Res.first = X86::EAX;
22844 Res.second = &X86::GR32_ADRegClass;
22850 // Otherwise, check to see if this is a register class of the wrong value
22851 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22852 // turn into {ax},{dx}.
22853 if (Res.second->hasType(VT))
22854 return Res; // Correct type already, nothing to do.
22856 // All of the single-register GCC register classes map their values onto
22857 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
22858 // really want an 8-bit or 32-bit register, map to the appropriate register
22859 // class and return the appropriate register.
22860 if (Res.second == &X86::GR16RegClass) {
22861 if (VT == MVT::i8 || VT == MVT::i1) {
22862 unsigned DestReg = 0;
22863 switch (Res.first) {
22865 case X86::AX: DestReg = X86::AL; break;
22866 case X86::DX: DestReg = X86::DL; break;
22867 case X86::CX: DestReg = X86::CL; break;
22868 case X86::BX: DestReg = X86::BL; break;
22871 Res.first = DestReg;
22872 Res.second = &X86::GR8RegClass;
22874 } else if (VT == MVT::i32 || VT == MVT::f32) {
22875 unsigned DestReg = 0;
22876 switch (Res.first) {
22878 case X86::AX: DestReg = X86::EAX; break;
22879 case X86::DX: DestReg = X86::EDX; break;
22880 case X86::CX: DestReg = X86::ECX; break;
22881 case X86::BX: DestReg = X86::EBX; break;
22882 case X86::SI: DestReg = X86::ESI; break;
22883 case X86::DI: DestReg = X86::EDI; break;
22884 case X86::BP: DestReg = X86::EBP; break;
22885 case X86::SP: DestReg = X86::ESP; break;
22888 Res.first = DestReg;
22889 Res.second = &X86::GR32RegClass;
22891 } else if (VT == MVT::i64 || VT == MVT::f64) {
22892 unsigned DestReg = 0;
22893 switch (Res.first) {
22895 case X86::AX: DestReg = X86::RAX; break;
22896 case X86::DX: DestReg = X86::RDX; break;
22897 case X86::CX: DestReg = X86::RCX; break;
22898 case X86::BX: DestReg = X86::RBX; break;
22899 case X86::SI: DestReg = X86::RSI; break;
22900 case X86::DI: DestReg = X86::RDI; break;
22901 case X86::BP: DestReg = X86::RBP; break;
22902 case X86::SP: DestReg = X86::RSP; break;
22905 Res.first = DestReg;
22906 Res.second = &X86::GR64RegClass;
22909 } else if (Res.second == &X86::FR32RegClass ||
22910 Res.second == &X86::FR64RegClass ||
22911 Res.second == &X86::VR128RegClass ||
22912 Res.second == &X86::VR256RegClass ||
22913 Res.second == &X86::FR32XRegClass ||
22914 Res.second == &X86::FR64XRegClass ||
22915 Res.second == &X86::VR128XRegClass ||
22916 Res.second == &X86::VR256XRegClass ||
22917 Res.second == &X86::VR512RegClass) {
22918 // Handle references to XMM physical registers that got mapped into the
22919 // wrong class. This can happen with constraints like {xmm0} where the
22920 // target independent register mapper will just pick the first match it can
22921 // find, ignoring the required type.
22923 if (VT == MVT::f32 || VT == MVT::i32)
22924 Res.second = &X86::FR32RegClass;
22925 else if (VT == MVT::f64 || VT == MVT::i64)
22926 Res.second = &X86::FR64RegClass;
22927 else if (X86::VR128RegClass.hasType(VT))
22928 Res.second = &X86::VR128RegClass;
22929 else if (X86::VR256RegClass.hasType(VT))
22930 Res.second = &X86::VR256RegClass;
22931 else if (X86::VR512RegClass.hasType(VT))
22932 Res.second = &X86::VR512RegClass;
22938 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22940 // Scaling factors are not free at all.
22941 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22942 // will take 2 allocations in the out of order engine instead of 1
22943 // for plain addressing mode, i.e. inst (reg1).
22945 // vaddps (%rsi,%drx), %ymm0, %ymm1
22946 // Requires two allocations (one for the load, one for the computation)
22948 // vaddps (%rsi), %ymm0, %ymm1
22949 // Requires just 1 allocation, i.e., freeing allocations for other operations
22950 // and having less micro operations to execute.
22952 // For some X86 architectures, this is even worse because for instance for
22953 // stores, the complex addressing mode forces the instruction to use the
22954 // "load" ports instead of the dedicated "store" port.
22955 // E.g., on Haswell:
22956 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22957 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
22958 if (isLegalAddressingMode(AM, Ty))
22959 // Scale represents reg2 * scale, thus account for 1
22960 // as soon as we use a second register.
22961 return AM.Scale != 0;
22965 bool X86TargetLowering::isTargetFTOL() const {
22966 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();