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> ExperimentalVectorShuffleLowering(
62 "x86-experimental-vector-shuffle-lowering", cl::init(false),
63 cl::desc("Enable an experimental vector shuffle lowering code path."),
66 // Forward declarations.
67 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
70 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
71 SelectionDAG &DAG, SDLoc dl,
72 unsigned vectorWidth) {
73 assert((vectorWidth == 128 || vectorWidth == 256) &&
74 "Unsupported vector width");
75 EVT VT = Vec.getValueType();
76 EVT ElVT = VT.getVectorElementType();
77 unsigned Factor = VT.getSizeInBits()/vectorWidth;
78 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
79 VT.getVectorNumElements()/Factor);
81 // Extract from UNDEF is UNDEF.
82 if (Vec.getOpcode() == ISD::UNDEF)
83 return DAG.getUNDEF(ResultVT);
85 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
86 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
88 // This is the index of the first element of the vectorWidth-bit chunk
90 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
93 // If the input is a buildvector just emit a smaller one.
94 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
95 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
96 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
99 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
100 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
106 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
107 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
108 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
109 /// instructions or a simple subregister reference. Idx is an index in the
110 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
111 /// lowering EXTRACT_VECTOR_ELT operations easier.
112 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
113 SelectionDAG &DAG, SDLoc dl) {
114 assert((Vec.getValueType().is256BitVector() ||
115 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
119 /// Generate a DAG to grab 256-bits from a 512-bit vector.
120 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
121 SelectionDAG &DAG, SDLoc dl) {
122 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
123 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
126 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
127 unsigned IdxVal, SelectionDAG &DAG,
128 SDLoc dl, unsigned vectorWidth) {
129 assert((vectorWidth == 128 || vectorWidth == 256) &&
130 "Unsupported vector width");
131 // Inserting UNDEF is Result
132 if (Vec.getOpcode() == ISD::UNDEF)
134 EVT VT = Vec.getValueType();
135 EVT ElVT = VT.getVectorElementType();
136 EVT ResultVT = Result.getValueType();
138 // Insert the relevant vectorWidth bits.
139 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
141 // This is the index of the first element of the vectorWidth-bit chunk
143 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
146 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
147 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
150 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
151 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
152 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
153 /// simple superregister reference. Idx is an index in the 128 bits
154 /// we want. It need not be aligned to a 128-bit bounday. That makes
155 /// lowering INSERT_VECTOR_ELT operations easier.
156 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
163 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
164 unsigned IdxVal, SelectionDAG &DAG,
166 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
167 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
170 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
171 /// instructions. This is used because creating CONCAT_VECTOR nodes of
172 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
173 /// large BUILD_VECTORS.
174 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
181 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
182 unsigned NumElems, SelectionDAG &DAG,
184 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
188 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
189 if (TT.isOSBinFormatMachO()) {
190 if (TT.getArch() == Triple::x86_64)
191 return new X86_64MachoTargetObjectFile();
192 return new TargetLoweringObjectFileMachO();
196 return new X86LinuxTargetObjectFile();
197 if (TT.isOSBinFormatELF())
198 return new TargetLoweringObjectFileELF();
199 if (TT.isKnownWindowsMSVCEnvironment())
200 return new X86WindowsTargetObjectFile();
201 if (TT.isOSBinFormatCOFF())
202 return new TargetLoweringObjectFileCOFF();
203 llvm_unreachable("unknown subtarget type");
206 // FIXME: This should stop caching the target machine as soon as
207 // we can remove resetOperationActions et al.
208 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
209 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
210 Subtarget = &TM.getSubtarget<X86Subtarget>();
211 X86ScalarSSEf64 = Subtarget->hasSSE2();
212 X86ScalarSSEf32 = Subtarget->hasSSE1();
213 TD = getDataLayout();
215 resetOperationActions();
218 void X86TargetLowering::resetOperationActions() {
219 const TargetMachine &TM = getTargetMachine();
220 static bool FirstTimeThrough = true;
222 // If none of the target options have changed, then we don't need to reset the
223 // operation actions.
224 if (!FirstTimeThrough && TO == TM.Options) return;
226 if (!FirstTimeThrough) {
227 // Reinitialize the actions.
229 FirstTimeThrough = false;
234 // Set up the TargetLowering object.
235 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
237 // X86 is weird, it always uses i8 for shift amounts and setcc results.
238 setBooleanContents(ZeroOrOneBooleanContent);
239 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
240 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
242 // For 64-bit since we have so many registers use the ILP scheduler, for
243 // 32-bit code use the register pressure specific scheduling.
244 // For Atom, always use ILP scheduling.
245 if (Subtarget->isAtom())
246 setSchedulingPreference(Sched::ILP);
247 else if (Subtarget->is64Bit())
248 setSchedulingPreference(Sched::ILP);
250 setSchedulingPreference(Sched::RegPressure);
251 const X86RegisterInfo *RegInfo =
252 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
253 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
255 // Bypass expensive divides on Atom when compiling with O2
256 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
257 addBypassSlowDiv(32, 8);
258 if (Subtarget->is64Bit())
259 addBypassSlowDiv(64, 16);
262 if (Subtarget->isTargetKnownWindowsMSVC()) {
263 // Setup Windows compiler runtime calls.
264 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
265 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
266 setLibcallName(RTLIB::SREM_I64, "_allrem");
267 setLibcallName(RTLIB::UREM_I64, "_aullrem");
268 setLibcallName(RTLIB::MUL_I64, "_allmul");
269 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
270 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
271 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
272 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
273 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
275 // The _ftol2 runtime function has an unusual calling conv, which
276 // is modeled by a special pseudo-instruction.
277 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
278 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
279 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
280 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
283 if (Subtarget->isTargetDarwin()) {
284 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
285 setUseUnderscoreSetJmp(false);
286 setUseUnderscoreLongJmp(false);
287 } else if (Subtarget->isTargetWindowsGNU()) {
288 // MS runtime is weird: it exports _setjmp, but longjmp!
289 setUseUnderscoreSetJmp(true);
290 setUseUnderscoreLongJmp(false);
292 setUseUnderscoreSetJmp(true);
293 setUseUnderscoreLongJmp(true);
296 // Set up the register classes.
297 addRegisterClass(MVT::i8, &X86::GR8RegClass);
298 addRegisterClass(MVT::i16, &X86::GR16RegClass);
299 addRegisterClass(MVT::i32, &X86::GR32RegClass);
300 if (Subtarget->is64Bit())
301 addRegisterClass(MVT::i64, &X86::GR64RegClass);
303 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
305 // We don't accept any truncstore of integer registers.
306 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
307 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
308 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
309 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
310 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
311 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
313 // SETOEQ and SETUNE require checking two conditions.
314 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
315 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
316 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
317 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
318 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
319 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
321 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
323 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
324 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
325 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
327 if (Subtarget->is64Bit()) {
328 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
329 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
330 } else if (!TM.Options.UseSoftFloat) {
331 // We have an algorithm for SSE2->double, and we turn this into a
332 // 64-bit FILD followed by conditional FADD for other targets.
333 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
334 // We have an algorithm for SSE2, and we turn this into a 64-bit
335 // FILD for other targets.
336 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
339 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
341 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
344 if (!TM.Options.UseSoftFloat) {
345 // SSE has no i16 to fp conversion, only i32
346 if (X86ScalarSSEf32) {
347 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
348 // f32 and f64 cases are Legal, f80 case is not
349 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
351 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
352 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
355 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
356 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
359 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
360 // are Legal, f80 is custom lowered.
361 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
364 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
366 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
369 if (X86ScalarSSEf32) {
370 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
371 // f32 and f64 cases are Legal, f80 case is not
372 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
374 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
375 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
378 // Handle FP_TO_UINT by promoting the destination to a larger signed
380 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
381 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
382 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
384 if (Subtarget->is64Bit()) {
385 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
387 } else if (!TM.Options.UseSoftFloat) {
388 // Since AVX is a superset of SSE3, only check for SSE here.
389 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
390 // Expand FP_TO_UINT into a select.
391 // FIXME: We would like to use a Custom expander here eventually to do
392 // the optimal thing for SSE vs. the default expansion in the legalizer.
393 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
395 // With SSE3 we can use fisttpll to convert to a signed i64; without
396 // SSE, we're stuck with a fistpll.
397 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
400 if (isTargetFTOL()) {
401 // Use the _ftol2 runtime function, which has a pseudo-instruction
402 // to handle its weird calling convention.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
406 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
407 if (!X86ScalarSSEf64) {
408 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
409 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
410 if (Subtarget->is64Bit()) {
411 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
412 // Without SSE, i64->f64 goes through memory.
413 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
417 // Scalar integer divide and remainder are lowered to use operations that
418 // produce two results, to match the available instructions. This exposes
419 // the two-result form to trivial CSE, which is able to combine x/y and x%y
420 // into a single instruction.
422 // Scalar integer multiply-high is also lowered to use two-result
423 // operations, to match the available instructions. However, plain multiply
424 // (low) operations are left as Legal, as there are single-result
425 // instructions for this in x86. Using the two-result multiply instructions
426 // when both high and low results are needed must be arranged by dagcombine.
427 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
429 setOperationAction(ISD::MULHS, VT, Expand);
430 setOperationAction(ISD::MULHU, VT, Expand);
431 setOperationAction(ISD::SDIV, VT, Expand);
432 setOperationAction(ISD::UDIV, VT, Expand);
433 setOperationAction(ISD::SREM, VT, Expand);
434 setOperationAction(ISD::UREM, VT, Expand);
436 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
437 setOperationAction(ISD::ADDC, VT, Custom);
438 setOperationAction(ISD::ADDE, VT, Custom);
439 setOperationAction(ISD::SUBC, VT, Custom);
440 setOperationAction(ISD::SUBE, VT, Custom);
443 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
444 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
445 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
446 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
447 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
448 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
449 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
450 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
451 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
452 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
453 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
454 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
455 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
456 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
457 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
459 if (Subtarget->is64Bit())
460 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
461 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
462 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
463 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
464 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
465 setOperationAction(ISD::FREM , MVT::f32 , Expand);
466 setOperationAction(ISD::FREM , MVT::f64 , Expand);
467 setOperationAction(ISD::FREM , MVT::f80 , Expand);
468 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
470 // Promote the i8 variants and force them on up to i32 which has a shorter
472 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
473 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
474 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
475 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
476 if (Subtarget->hasBMI()) {
477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
479 if (Subtarget->is64Bit())
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
482 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
483 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
484 if (Subtarget->is64Bit())
485 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
488 if (Subtarget->hasLZCNT()) {
489 // When promoting the i8 variants, force them to i32 for a shorter
491 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
492 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
494 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
495 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
497 if (Subtarget->is64Bit())
498 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
500 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
501 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
502 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
503 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
505 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
506 if (Subtarget->is64Bit()) {
507 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
508 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
512 if (Subtarget->hasPOPCNT()) {
513 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
515 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
516 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
517 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
518 if (Subtarget->is64Bit())
519 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
522 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
524 if (!Subtarget->hasMOVBE())
525 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
527 // These should be promoted to a larger select which is supported.
528 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
529 // X86 wants to expand cmov itself.
530 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
531 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
532 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
533 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
534 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
535 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
536 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
537 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
538 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
539 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
540 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
541 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
542 if (Subtarget->is64Bit()) {
543 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
544 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
546 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
547 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
548 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
549 // support continuation, user-level threading, and etc.. As a result, no
550 // other SjLj exception interfaces are implemented and please don't build
551 // your own exception handling based on them.
552 // LLVM/Clang supports zero-cost DWARF exception handling.
553 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
554 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
557 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
558 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
559 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
560 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
561 if (Subtarget->is64Bit())
562 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
563 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
564 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
567 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
568 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
569 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
570 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
572 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
573 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
574 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
575 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
576 if (Subtarget->is64Bit()) {
577 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
578 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
579 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
582 if (Subtarget->hasSSE1())
583 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
585 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
587 // Expand certain atomics
588 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
590 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
592 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
595 if (!Subtarget->is64Bit()) {
596 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
598 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
599 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
600 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
601 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
602 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
603 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
604 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
605 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
606 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
607 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
610 if (Subtarget->hasCmpxchg16b()) {
611 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
614 // FIXME - use subtarget debug flags
615 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
616 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
617 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
620 if (Subtarget->is64Bit()) {
621 setExceptionPointerRegister(X86::RAX);
622 setExceptionSelectorRegister(X86::RDX);
624 setExceptionPointerRegister(X86::EAX);
625 setExceptionSelectorRegister(X86::EDX);
627 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
628 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
630 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
631 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
633 setOperationAction(ISD::TRAP, MVT::Other, Legal);
634 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
636 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
637 setOperationAction(ISD::VASTART , MVT::Other, Custom);
638 setOperationAction(ISD::VAEND , MVT::Other, Expand);
639 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
640 // TargetInfo::X86_64ABIBuiltinVaList
641 setOperationAction(ISD::VAARG , MVT::Other, Custom);
642 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
644 // TargetInfo::CharPtrBuiltinVaList
645 setOperationAction(ISD::VAARG , MVT::Other, Expand);
646 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
649 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
650 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
652 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
653 MVT::i64 : MVT::i32, Custom);
655 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
656 // f32 and f64 use SSE.
657 // Set up the FP register classes.
658 addRegisterClass(MVT::f32, &X86::FR32RegClass);
659 addRegisterClass(MVT::f64, &X86::FR64RegClass);
661 // Use ANDPD to simulate FABS.
662 setOperationAction(ISD::FABS , MVT::f64, Custom);
663 setOperationAction(ISD::FABS , MVT::f32, Custom);
665 // Use XORP to simulate FNEG.
666 setOperationAction(ISD::FNEG , MVT::f64, Custom);
667 setOperationAction(ISD::FNEG , MVT::f32, Custom);
669 // Use ANDPD and ORPD to simulate FCOPYSIGN.
670 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
671 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
673 // Lower this to FGETSIGNx86 plus an AND.
674 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
675 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
677 // We don't support sin/cos/fmod
678 setOperationAction(ISD::FSIN , MVT::f64, Expand);
679 setOperationAction(ISD::FCOS , MVT::f64, Expand);
680 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
681 setOperationAction(ISD::FSIN , MVT::f32, Expand);
682 setOperationAction(ISD::FCOS , MVT::f32, Expand);
683 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
685 // Expand FP immediates into loads from the stack, except for the special
687 addLegalFPImmediate(APFloat(+0.0)); // xorpd
688 addLegalFPImmediate(APFloat(+0.0f)); // xorps
689 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
690 // Use SSE for f32, x87 for f64.
691 // Set up the FP register classes.
692 addRegisterClass(MVT::f32, &X86::FR32RegClass);
693 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
695 // Use ANDPS to simulate FABS.
696 setOperationAction(ISD::FABS , MVT::f32, Custom);
698 // Use XORP to simulate FNEG.
699 setOperationAction(ISD::FNEG , MVT::f32, Custom);
701 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
703 // Use ANDPS and ORPS to simulate FCOPYSIGN.
704 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
705 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
707 // We don't support sin/cos/fmod
708 setOperationAction(ISD::FSIN , MVT::f32, Expand);
709 setOperationAction(ISD::FCOS , MVT::f32, Expand);
710 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
712 // Special cases we handle for FP constants.
713 addLegalFPImmediate(APFloat(+0.0f)); // xorps
714 addLegalFPImmediate(APFloat(+0.0)); // FLD0
715 addLegalFPImmediate(APFloat(+1.0)); // FLD1
716 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
717 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
719 if (!TM.Options.UnsafeFPMath) {
720 setOperationAction(ISD::FSIN , MVT::f64, Expand);
721 setOperationAction(ISD::FCOS , MVT::f64, Expand);
722 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
724 } else if (!TM.Options.UseSoftFloat) {
725 // f32 and f64 in x87.
726 // Set up the FP register classes.
727 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
728 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
730 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
731 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
732 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
733 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
735 if (!TM.Options.UnsafeFPMath) {
736 setOperationAction(ISD::FSIN , MVT::f64, Expand);
737 setOperationAction(ISD::FSIN , MVT::f32, Expand);
738 setOperationAction(ISD::FCOS , MVT::f64, Expand);
739 setOperationAction(ISD::FCOS , MVT::f32, Expand);
740 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
741 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
743 addLegalFPImmediate(APFloat(+0.0)); // FLD0
744 addLegalFPImmediate(APFloat(+1.0)); // FLD1
745 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
746 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
747 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
748 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
749 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
750 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
753 // We don't support FMA.
754 setOperationAction(ISD::FMA, MVT::f64, Expand);
755 setOperationAction(ISD::FMA, MVT::f32, Expand);
757 // Long double always uses X87.
758 if (!TM.Options.UseSoftFloat) {
759 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
760 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
761 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
763 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
764 addLegalFPImmediate(TmpFlt); // FLD0
766 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
769 APFloat TmpFlt2(+1.0);
770 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
772 addLegalFPImmediate(TmpFlt2); // FLD1
773 TmpFlt2.changeSign();
774 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
777 if (!TM.Options.UnsafeFPMath) {
778 setOperationAction(ISD::FSIN , MVT::f80, Expand);
779 setOperationAction(ISD::FCOS , MVT::f80, Expand);
780 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
783 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
784 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
785 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
786 setOperationAction(ISD::FRINT, MVT::f80, Expand);
787 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
788 setOperationAction(ISD::FMA, MVT::f80, Expand);
791 // Always use a library call for pow.
792 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
793 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
794 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
796 setOperationAction(ISD::FLOG, MVT::f80, Expand);
797 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
798 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
799 setOperationAction(ISD::FEXP, MVT::f80, Expand);
800 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
802 // First set operation action for all vector types to either promote
803 // (for widening) or expand (for scalarization). Then we will selectively
804 // turn on ones that can be effectively codegen'd.
805 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
806 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
807 MVT VT = (MVT::SimpleValueType)i;
808 setOperationAction(ISD::ADD , VT, Expand);
809 setOperationAction(ISD::SUB , VT, Expand);
810 setOperationAction(ISD::FADD, VT, Expand);
811 setOperationAction(ISD::FNEG, VT, Expand);
812 setOperationAction(ISD::FSUB, VT, Expand);
813 setOperationAction(ISD::MUL , VT, Expand);
814 setOperationAction(ISD::FMUL, VT, Expand);
815 setOperationAction(ISD::SDIV, VT, Expand);
816 setOperationAction(ISD::UDIV, VT, Expand);
817 setOperationAction(ISD::FDIV, VT, Expand);
818 setOperationAction(ISD::SREM, VT, Expand);
819 setOperationAction(ISD::UREM, VT, Expand);
820 setOperationAction(ISD::LOAD, VT, Expand);
821 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
823 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
824 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
825 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
826 setOperationAction(ISD::FABS, VT, Expand);
827 setOperationAction(ISD::FSIN, VT, Expand);
828 setOperationAction(ISD::FSINCOS, VT, Expand);
829 setOperationAction(ISD::FCOS, VT, Expand);
830 setOperationAction(ISD::FSINCOS, VT, Expand);
831 setOperationAction(ISD::FREM, VT, Expand);
832 setOperationAction(ISD::FMA, VT, Expand);
833 setOperationAction(ISD::FPOWI, VT, Expand);
834 setOperationAction(ISD::FSQRT, VT, Expand);
835 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
836 setOperationAction(ISD::FFLOOR, VT, Expand);
837 setOperationAction(ISD::FCEIL, VT, Expand);
838 setOperationAction(ISD::FTRUNC, VT, Expand);
839 setOperationAction(ISD::FRINT, VT, Expand);
840 setOperationAction(ISD::FNEARBYINT, VT, Expand);
841 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
842 setOperationAction(ISD::MULHS, VT, Expand);
843 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
844 setOperationAction(ISD::MULHU, VT, Expand);
845 setOperationAction(ISD::SDIVREM, VT, Expand);
846 setOperationAction(ISD::UDIVREM, VT, Expand);
847 setOperationAction(ISD::FPOW, VT, Expand);
848 setOperationAction(ISD::CTPOP, VT, Expand);
849 setOperationAction(ISD::CTTZ, VT, Expand);
850 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
851 setOperationAction(ISD::CTLZ, VT, Expand);
852 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
853 setOperationAction(ISD::SHL, VT, Expand);
854 setOperationAction(ISD::SRA, VT, Expand);
855 setOperationAction(ISD::SRL, VT, Expand);
856 setOperationAction(ISD::ROTL, VT, Expand);
857 setOperationAction(ISD::ROTR, VT, Expand);
858 setOperationAction(ISD::BSWAP, VT, Expand);
859 setOperationAction(ISD::SETCC, VT, Expand);
860 setOperationAction(ISD::FLOG, VT, Expand);
861 setOperationAction(ISD::FLOG2, VT, Expand);
862 setOperationAction(ISD::FLOG10, VT, Expand);
863 setOperationAction(ISD::FEXP, VT, Expand);
864 setOperationAction(ISD::FEXP2, VT, Expand);
865 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
866 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
867 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
868 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
869 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
870 setOperationAction(ISD::TRUNCATE, VT, Expand);
871 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
872 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
873 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
874 setOperationAction(ISD::VSELECT, VT, Expand);
875 setOperationAction(ISD::SELECT_CC, VT, Expand);
876 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
877 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
878 setTruncStoreAction(VT,
879 (MVT::SimpleValueType)InnerVT, Expand);
880 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
881 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
882 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
885 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
886 // with -msoft-float, disable use of MMX as well.
887 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
888 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
889 // No operations on x86mmx supported, everything uses intrinsics.
892 // MMX-sized vectors (other than x86mmx) are expected to be expanded
893 // into smaller operations.
894 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
895 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
896 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
897 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
898 setOperationAction(ISD::AND, MVT::v8i8, Expand);
899 setOperationAction(ISD::AND, MVT::v4i16, Expand);
900 setOperationAction(ISD::AND, MVT::v2i32, Expand);
901 setOperationAction(ISD::AND, MVT::v1i64, Expand);
902 setOperationAction(ISD::OR, MVT::v8i8, Expand);
903 setOperationAction(ISD::OR, MVT::v4i16, Expand);
904 setOperationAction(ISD::OR, MVT::v2i32, Expand);
905 setOperationAction(ISD::OR, MVT::v1i64, Expand);
906 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
907 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
908 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
909 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
911 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
914 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
915 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
916 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
917 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
918 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
919 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
920 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
921 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
922 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
924 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
925 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
927 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
928 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
929 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
930 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
931 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
932 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
933 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
934 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
935 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
936 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
941 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
942 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
944 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
945 // registers cannot be used even for integer operations.
946 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
947 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
948 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
949 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
951 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
952 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
953 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
954 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
955 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
956 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
957 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
958 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
959 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
960 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
961 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
962 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
963 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
964 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
965 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
966 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
967 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
968 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
969 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
970 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
971 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
972 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
974 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
975 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
976 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
977 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
979 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
980 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
981 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
982 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
985 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
986 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
987 MVT VT = (MVT::SimpleValueType)i;
988 // Do not attempt to custom lower non-power-of-2 vectors
989 if (!isPowerOf2_32(VT.getVectorNumElements()))
991 // Do not attempt to custom lower non-128-bit vectors
992 if (!VT.is128BitVector())
994 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
995 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
999 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1000 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1001 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1002 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1003 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1004 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1006 if (Subtarget->is64Bit()) {
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1008 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1011 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1012 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1013 MVT VT = (MVT::SimpleValueType)i;
1015 // Do not attempt to promote non-128-bit vectors
1016 if (!VT.is128BitVector())
1019 setOperationAction(ISD::AND, VT, Promote);
1020 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1021 setOperationAction(ISD::OR, VT, Promote);
1022 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1023 setOperationAction(ISD::XOR, VT, Promote);
1024 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1025 setOperationAction(ISD::LOAD, VT, Promote);
1026 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1027 setOperationAction(ISD::SELECT, VT, Promote);
1028 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1031 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1033 // Custom lower v2i64 and v2f64 selects.
1034 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1035 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1036 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1037 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1039 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1040 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1042 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1043 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1044 // As there is no 64-bit GPR available, we need build a special custom
1045 // sequence to convert from v2i32 to v2f32.
1046 if (!Subtarget->is64Bit())
1047 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1049 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1050 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1052 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1054 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1055 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1056 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1059 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1060 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1061 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1062 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1063 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1064 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1068 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1071 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1072 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1073 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1074 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1075 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1076 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1077 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1078 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1079 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1080 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1082 // FIXME: Do we need to handle scalar-to-vector here?
1083 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1085 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1086 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1087 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1088 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1089 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1090 // There is no BLENDI for byte vectors. We don't need to custom lower
1091 // some vselects for now.
1092 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1094 // i8 and i16 vectors are custom , because the source register and source
1095 // source memory operand types are not the same width. f32 vectors are
1096 // custom since the immediate controlling the insert encodes additional
1098 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1099 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1100 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1101 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1105 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1106 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1108 // FIXME: these should be Legal but thats only for the case where
1109 // the index is constant. For now custom expand to deal with that.
1110 if (Subtarget->is64Bit()) {
1111 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1112 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1116 if (Subtarget->hasSSE2()) {
1117 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1118 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1120 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1121 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1123 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1124 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1126 // In the customized shift lowering, the legal cases in AVX2 will be
1128 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1129 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1131 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1132 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1134 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1137 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1138 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1139 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1140 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1141 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1142 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1143 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1145 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1146 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1147 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1149 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1152 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1153 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1154 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1155 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1156 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1157 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1158 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1159 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1160 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1162 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1165 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1167 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1168 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1169 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1170 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1171 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1172 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1173 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1175 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1176 // even though v8i16 is a legal type.
1177 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1178 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1179 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1181 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1182 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1183 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1185 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1186 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1188 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1190 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1191 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1194 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1196 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1197 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1199 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1200 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1201 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1202 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1204 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1205 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1206 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1208 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1209 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1210 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1211 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1213 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1214 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1215 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1216 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1217 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1218 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1219 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1220 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1221 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1222 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1223 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1224 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1226 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1227 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1228 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1229 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1230 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1231 setOperationAction(ISD::FMA, MVT::f32, Legal);
1232 setOperationAction(ISD::FMA, MVT::f64, Legal);
1235 if (Subtarget->hasInt256()) {
1236 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1237 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1238 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1239 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1241 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1242 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1243 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1244 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1246 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1247 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1248 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1249 // Don't lower v32i8 because there is no 128-bit byte mul
1251 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1252 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1253 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1254 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1256 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1257 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1259 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1260 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1261 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1262 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1264 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1265 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1266 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1267 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1269 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1270 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1271 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1272 // Don't lower v32i8 because there is no 128-bit byte mul
1275 // In the customized shift lowering, the legal cases in AVX2 will be
1277 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1278 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1280 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1281 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1283 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1285 // Custom lower several nodes for 256-bit types.
1286 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1287 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1288 MVT VT = (MVT::SimpleValueType)i;
1290 // Extract subvector is special because the value type
1291 // (result) is 128-bit but the source is 256-bit wide.
1292 if (VT.is128BitVector())
1293 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1295 // Do not attempt to custom lower other non-256-bit vectors
1296 if (!VT.is256BitVector())
1299 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1300 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1301 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1302 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1303 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1304 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1305 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1308 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1309 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1310 MVT VT = (MVT::SimpleValueType)i;
1312 // Do not attempt to promote non-256-bit vectors
1313 if (!VT.is256BitVector())
1316 setOperationAction(ISD::AND, VT, Promote);
1317 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1318 setOperationAction(ISD::OR, VT, Promote);
1319 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1320 setOperationAction(ISD::XOR, VT, Promote);
1321 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1322 setOperationAction(ISD::LOAD, VT, Promote);
1323 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1324 setOperationAction(ISD::SELECT, VT, Promote);
1325 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1329 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1330 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1331 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1332 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1333 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1335 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1336 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1337 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1339 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1340 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1341 setOperationAction(ISD::XOR, MVT::i1, Legal);
1342 setOperationAction(ISD::OR, MVT::i1, Legal);
1343 setOperationAction(ISD::AND, MVT::i1, Legal);
1344 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1345 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1346 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1348 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1349 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1351 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1356 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1358 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1360 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1363 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1364 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1365 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1367 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1368 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1369 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1371 if (Subtarget->is64Bit()) {
1372 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1373 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1377 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1378 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1379 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1380 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1381 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1382 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1384 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1385 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1386 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1388 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1389 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1390 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1391 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1392 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1393 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1394 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1395 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1396 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1397 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1398 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1399 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1400 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1402 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1403 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1404 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1405 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1406 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1407 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1409 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1410 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1412 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1414 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1415 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1416 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1417 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1418 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1419 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1420 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1421 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1422 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1424 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1425 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1427 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1428 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1430 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1432 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1435 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1436 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1438 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1439 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1441 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1442 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1443 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1444 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1445 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1446 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1448 if (Subtarget->hasCDI()) {
1449 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1450 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1453 // Custom lower several nodes.
1454 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1455 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1456 MVT VT = (MVT::SimpleValueType)i;
1458 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1459 // Extract subvector is special because the value type
1460 // (result) is 256/128-bit but the source is 512-bit wide.
1461 if (VT.is128BitVector() || VT.is256BitVector())
1462 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1464 if (VT.getVectorElementType() == MVT::i1)
1465 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1467 // Do not attempt to custom lower other non-512-bit vectors
1468 if (!VT.is512BitVector())
1471 if ( EltSize >= 32) {
1472 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1473 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1474 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1475 setOperationAction(ISD::VSELECT, VT, Legal);
1476 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1477 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1478 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1481 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1482 MVT VT = (MVT::SimpleValueType)i;
1484 // Do not attempt to promote non-256-bit vectors
1485 if (!VT.is512BitVector())
1488 setOperationAction(ISD::SELECT, VT, Promote);
1489 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1493 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1494 // of this type with custom code.
1495 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1496 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1497 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1501 // We want to custom lower some of our intrinsics.
1502 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1503 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1504 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1505 if (!Subtarget->is64Bit())
1506 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1508 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1509 // handle type legalization for these operations here.
1511 // FIXME: We really should do custom legalization for addition and
1512 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1513 // than generic legalization for 64-bit multiplication-with-overflow, though.
1514 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1515 // Add/Sub/Mul with overflow operations are custom lowered.
1517 setOperationAction(ISD::SADDO, VT, Custom);
1518 setOperationAction(ISD::UADDO, VT, Custom);
1519 setOperationAction(ISD::SSUBO, VT, Custom);
1520 setOperationAction(ISD::USUBO, VT, Custom);
1521 setOperationAction(ISD::SMULO, VT, Custom);
1522 setOperationAction(ISD::UMULO, VT, Custom);
1525 // There are no 8-bit 3-address imul/mul instructions
1526 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1527 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1529 if (!Subtarget->is64Bit()) {
1530 // These libcalls are not available in 32-bit.
1531 setLibcallName(RTLIB::SHL_I128, nullptr);
1532 setLibcallName(RTLIB::SRL_I128, nullptr);
1533 setLibcallName(RTLIB::SRA_I128, nullptr);
1536 // Combine sin / cos into one node or libcall if possible.
1537 if (Subtarget->hasSinCos()) {
1538 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1539 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1540 if (Subtarget->isTargetDarwin()) {
1541 // For MacOSX, we don't want to the normal expansion of a libcall to
1542 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1544 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1545 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1549 if (Subtarget->isTargetWin64()) {
1550 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1551 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1552 setOperationAction(ISD::SREM, MVT::i128, Custom);
1553 setOperationAction(ISD::UREM, MVT::i128, Custom);
1554 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1555 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1558 // We have target-specific dag combine patterns for the following nodes:
1559 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1560 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1561 setTargetDAGCombine(ISD::VSELECT);
1562 setTargetDAGCombine(ISD::SELECT);
1563 setTargetDAGCombine(ISD::SHL);
1564 setTargetDAGCombine(ISD::SRA);
1565 setTargetDAGCombine(ISD::SRL);
1566 setTargetDAGCombine(ISD::OR);
1567 setTargetDAGCombine(ISD::AND);
1568 setTargetDAGCombine(ISD::ADD);
1569 setTargetDAGCombine(ISD::FADD);
1570 setTargetDAGCombine(ISD::FSUB);
1571 setTargetDAGCombine(ISD::FMA);
1572 setTargetDAGCombine(ISD::SUB);
1573 setTargetDAGCombine(ISD::LOAD);
1574 setTargetDAGCombine(ISD::STORE);
1575 setTargetDAGCombine(ISD::ZERO_EXTEND);
1576 setTargetDAGCombine(ISD::ANY_EXTEND);
1577 setTargetDAGCombine(ISD::SIGN_EXTEND);
1578 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1579 setTargetDAGCombine(ISD::TRUNCATE);
1580 setTargetDAGCombine(ISD::SINT_TO_FP);
1581 setTargetDAGCombine(ISD::SETCC);
1582 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1583 setTargetDAGCombine(ISD::BUILD_VECTOR);
1584 if (Subtarget->is64Bit())
1585 setTargetDAGCombine(ISD::MUL);
1586 setTargetDAGCombine(ISD::XOR);
1588 computeRegisterProperties();
1590 // On Darwin, -Os means optimize for size without hurting performance,
1591 // do not reduce the limit.
1592 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1593 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1594 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1595 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1596 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1597 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1598 setPrefLoopAlignment(4); // 2^4 bytes.
1600 // Predictable cmov don't hurt on atom because it's in-order.
1601 PredictableSelectIsExpensive = !Subtarget->isAtom();
1603 setPrefFunctionAlignment(4); // 2^4 bytes.
1606 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1608 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1610 if (Subtarget->hasAVX512())
1611 switch(VT.getVectorNumElements()) {
1612 case 8: return MVT::v8i1;
1613 case 16: return MVT::v16i1;
1616 return VT.changeVectorElementTypeToInteger();
1619 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1620 /// the desired ByVal argument alignment.
1621 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1624 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1625 if (VTy->getBitWidth() == 128)
1627 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1628 unsigned EltAlign = 0;
1629 getMaxByValAlign(ATy->getElementType(), EltAlign);
1630 if (EltAlign > MaxAlign)
1631 MaxAlign = EltAlign;
1632 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1633 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1634 unsigned EltAlign = 0;
1635 getMaxByValAlign(STy->getElementType(i), EltAlign);
1636 if (EltAlign > MaxAlign)
1637 MaxAlign = EltAlign;
1644 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1645 /// function arguments in the caller parameter area. For X86, aggregates
1646 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1647 /// are at 4-byte boundaries.
1648 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1649 if (Subtarget->is64Bit()) {
1650 // Max of 8 and alignment of type.
1651 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1658 if (Subtarget->hasSSE1())
1659 getMaxByValAlign(Ty, Align);
1663 /// getOptimalMemOpType - Returns the target specific optimal type for load
1664 /// and store operations as a result of memset, memcpy, and memmove
1665 /// lowering. If DstAlign is zero that means it's safe to destination
1666 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1667 /// means there isn't a need to check it against alignment requirement,
1668 /// probably because the source does not need to be loaded. If 'IsMemset' is
1669 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1670 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1671 /// source is constant so it does not need to be loaded.
1672 /// It returns EVT::Other if the type should be determined using generic
1673 /// target-independent logic.
1675 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1676 unsigned DstAlign, unsigned SrcAlign,
1677 bool IsMemset, bool ZeroMemset,
1679 MachineFunction &MF) const {
1680 const Function *F = MF.getFunction();
1681 if ((!IsMemset || ZeroMemset) &&
1682 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1683 Attribute::NoImplicitFloat)) {
1685 (Subtarget->isUnalignedMemAccessFast() ||
1686 ((DstAlign == 0 || DstAlign >= 16) &&
1687 (SrcAlign == 0 || SrcAlign >= 16)))) {
1689 if (Subtarget->hasInt256())
1691 if (Subtarget->hasFp256())
1694 if (Subtarget->hasSSE2())
1696 if (Subtarget->hasSSE1())
1698 } else if (!MemcpyStrSrc && Size >= 8 &&
1699 !Subtarget->is64Bit() &&
1700 Subtarget->hasSSE2()) {
1701 // Do not use f64 to lower memcpy if source is string constant. It's
1702 // better to use i32 to avoid the loads.
1706 if (Subtarget->is64Bit() && Size >= 8)
1711 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1713 return X86ScalarSSEf32;
1714 else if (VT == MVT::f64)
1715 return X86ScalarSSEf64;
1720 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1724 *Fast = Subtarget->isUnalignedMemAccessFast();
1728 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1729 /// current function. The returned value is a member of the
1730 /// MachineJumpTableInfo::JTEntryKind enum.
1731 unsigned X86TargetLowering::getJumpTableEncoding() const {
1732 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1734 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1735 Subtarget->isPICStyleGOT())
1736 return MachineJumpTableInfo::EK_Custom32;
1738 // Otherwise, use the normal jump table encoding heuristics.
1739 return TargetLowering::getJumpTableEncoding();
1743 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1744 const MachineBasicBlock *MBB,
1745 unsigned uid,MCContext &Ctx) const{
1746 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1747 Subtarget->isPICStyleGOT());
1748 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1750 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1751 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1754 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1756 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1757 SelectionDAG &DAG) const {
1758 if (!Subtarget->is64Bit())
1759 // This doesn't have SDLoc associated with it, but is not really the
1760 // same as a Register.
1761 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1765 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1766 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1768 const MCExpr *X86TargetLowering::
1769 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1770 MCContext &Ctx) const {
1771 // X86-64 uses RIP relative addressing based on the jump table label.
1772 if (Subtarget->isPICStyleRIPRel())
1773 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1775 // Otherwise, the reference is relative to the PIC base.
1776 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1779 // FIXME: Why this routine is here? Move to RegInfo!
1780 std::pair<const TargetRegisterClass*, uint8_t>
1781 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1782 const TargetRegisterClass *RRC = nullptr;
1784 switch (VT.SimpleTy) {
1786 return TargetLowering::findRepresentativeClass(VT);
1787 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1788 RRC = Subtarget->is64Bit() ?
1789 (const TargetRegisterClass*)&X86::GR64RegClass :
1790 (const TargetRegisterClass*)&X86::GR32RegClass;
1793 RRC = &X86::VR64RegClass;
1795 case MVT::f32: case MVT::f64:
1796 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1797 case MVT::v4f32: case MVT::v2f64:
1798 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1800 RRC = &X86::VR128RegClass;
1803 return std::make_pair(RRC, Cost);
1806 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1807 unsigned &Offset) const {
1808 if (!Subtarget->isTargetLinux())
1811 if (Subtarget->is64Bit()) {
1812 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1814 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1826 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1827 unsigned DestAS) const {
1828 assert(SrcAS != DestAS && "Expected different address spaces!");
1830 return SrcAS < 256 && DestAS < 256;
1833 //===----------------------------------------------------------------------===//
1834 // Return Value Calling Convention Implementation
1835 //===----------------------------------------------------------------------===//
1837 #include "X86GenCallingConv.inc"
1840 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1841 MachineFunction &MF, bool isVarArg,
1842 const SmallVectorImpl<ISD::OutputArg> &Outs,
1843 LLVMContext &Context) const {
1844 SmallVector<CCValAssign, 16> RVLocs;
1845 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1847 return CCInfo.CheckReturn(Outs, RetCC_X86);
1850 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1851 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1856 X86TargetLowering::LowerReturn(SDValue Chain,
1857 CallingConv::ID CallConv, bool isVarArg,
1858 const SmallVectorImpl<ISD::OutputArg> &Outs,
1859 const SmallVectorImpl<SDValue> &OutVals,
1860 SDLoc dl, SelectionDAG &DAG) const {
1861 MachineFunction &MF = DAG.getMachineFunction();
1862 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1864 SmallVector<CCValAssign, 16> RVLocs;
1865 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1866 RVLocs, *DAG.getContext());
1867 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1870 SmallVector<SDValue, 6> RetOps;
1871 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1872 // Operand #1 = Bytes To Pop
1873 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1876 // Copy the result values into the output registers.
1877 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1878 CCValAssign &VA = RVLocs[i];
1879 assert(VA.isRegLoc() && "Can only return in registers!");
1880 SDValue ValToCopy = OutVals[i];
1881 EVT ValVT = ValToCopy.getValueType();
1883 // Promote values to the appropriate types
1884 if (VA.getLocInfo() == CCValAssign::SExt)
1885 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1886 else if (VA.getLocInfo() == CCValAssign::ZExt)
1887 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1888 else if (VA.getLocInfo() == CCValAssign::AExt)
1889 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1890 else if (VA.getLocInfo() == CCValAssign::BCvt)
1891 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1893 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1894 "Unexpected FP-extend for return value.");
1896 // If this is x86-64, and we disabled SSE, we can't return FP values,
1897 // or SSE or MMX vectors.
1898 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1899 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1900 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1901 report_fatal_error("SSE register return with SSE disabled");
1903 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1904 // llvm-gcc has never done it right and no one has noticed, so this
1905 // should be OK for now.
1906 if (ValVT == MVT::f64 &&
1907 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1908 report_fatal_error("SSE2 register return with SSE2 disabled");
1910 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1911 // the RET instruction and handled by the FP Stackifier.
1912 if (VA.getLocReg() == X86::ST0 ||
1913 VA.getLocReg() == X86::ST1) {
1914 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1915 // change the value to the FP stack register class.
1916 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1917 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1918 RetOps.push_back(ValToCopy);
1919 // Don't emit a copytoreg.
1923 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1924 // which is returned in RAX / RDX.
1925 if (Subtarget->is64Bit()) {
1926 if (ValVT == MVT::x86mmx) {
1927 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1928 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1929 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1931 // If we don't have SSE2 available, convert to v4f32 so the generated
1932 // register is legal.
1933 if (!Subtarget->hasSSE2())
1934 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1939 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1940 Flag = Chain.getValue(1);
1941 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1944 // The x86-64 ABIs require that for returning structs by value we copy
1945 // the sret argument into %rax/%eax (depending on ABI) for the return.
1946 // Win32 requires us to put the sret argument to %eax as well.
1947 // We saved the argument into a virtual register in the entry block,
1948 // so now we copy the value out and into %rax/%eax.
1949 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1950 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1951 MachineFunction &MF = DAG.getMachineFunction();
1952 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1953 unsigned Reg = FuncInfo->getSRetReturnReg();
1955 "SRetReturnReg should have been set in LowerFormalArguments().");
1956 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1959 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1960 X86::RAX : X86::EAX;
1961 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1962 Flag = Chain.getValue(1);
1964 // RAX/EAX now acts like a return value.
1965 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1968 RetOps[0] = Chain; // Update chain.
1970 // Add the flag if we have it.
1972 RetOps.push_back(Flag);
1974 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1977 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1978 if (N->getNumValues() != 1)
1980 if (!N->hasNUsesOfValue(1, 0))
1983 SDValue TCChain = Chain;
1984 SDNode *Copy = *N->use_begin();
1985 if (Copy->getOpcode() == ISD::CopyToReg) {
1986 // If the copy has a glue operand, we conservatively assume it isn't safe to
1987 // perform a tail call.
1988 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1990 TCChain = Copy->getOperand(0);
1991 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1994 bool HasRet = false;
1995 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1997 if (UI->getOpcode() != X86ISD::RET_FLAG)
2010 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2011 ISD::NodeType ExtendKind) const {
2013 // TODO: Is this also valid on 32-bit?
2014 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2015 ReturnMVT = MVT::i8;
2017 ReturnMVT = MVT::i32;
2019 MVT MinVT = getRegisterType(ReturnMVT);
2020 return VT.bitsLT(MinVT) ? MinVT : VT;
2023 /// LowerCallResult - Lower the result values of a call into the
2024 /// appropriate copies out of appropriate physical registers.
2027 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2028 CallingConv::ID CallConv, bool isVarArg,
2029 const SmallVectorImpl<ISD::InputArg> &Ins,
2030 SDLoc dl, SelectionDAG &DAG,
2031 SmallVectorImpl<SDValue> &InVals) const {
2033 // Assign locations to each value returned by this call.
2034 SmallVector<CCValAssign, 16> RVLocs;
2035 bool Is64Bit = Subtarget->is64Bit();
2036 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2037 DAG.getTarget(), RVLocs, *DAG.getContext());
2038 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2040 // Copy all of the result registers out of their specified physreg.
2041 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2042 CCValAssign &VA = RVLocs[i];
2043 EVT CopyVT = VA.getValVT();
2045 // If this is x86-64, and we disabled SSE, we can't return FP values
2046 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2047 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2048 report_fatal_error("SSE register return with SSE disabled");
2053 // If this is a call to a function that returns an fp value on the floating
2054 // point stack, we must guarantee the value is popped from the stack, so
2055 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2056 // if the return value is not used. We use the FpPOP_RETVAL instruction
2058 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2059 // If we prefer to use the value in xmm registers, copy it out as f80 and
2060 // use a truncate to move it from fp stack reg to xmm reg.
2061 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2062 SDValue Ops[] = { Chain, InFlag };
2063 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2064 MVT::Other, MVT::Glue, Ops), 1);
2065 Val = Chain.getValue(0);
2067 // Round the f80 to the right size, which also moves it to the appropriate
2069 if (CopyVT != VA.getValVT())
2070 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2071 // This truncation won't change the value.
2072 DAG.getIntPtrConstant(1));
2074 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2075 CopyVT, InFlag).getValue(1);
2076 Val = Chain.getValue(0);
2078 InFlag = Chain.getValue(2);
2079 InVals.push_back(Val);
2085 //===----------------------------------------------------------------------===//
2086 // C & StdCall & Fast Calling Convention implementation
2087 //===----------------------------------------------------------------------===//
2088 // StdCall calling convention seems to be standard for many Windows' API
2089 // routines and around. It differs from C calling convention just a little:
2090 // callee should clean up the stack, not caller. Symbols should be also
2091 // decorated in some fancy way :) It doesn't support any vector arguments.
2092 // For info on fast calling convention see Fast Calling Convention (tail call)
2093 // implementation LowerX86_32FastCCCallTo.
2095 /// CallIsStructReturn - Determines whether a call uses struct return
2097 enum StructReturnType {
2102 static StructReturnType
2103 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2105 return NotStructReturn;
2107 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2108 if (!Flags.isSRet())
2109 return NotStructReturn;
2110 if (Flags.isInReg())
2111 return RegStructReturn;
2112 return StackStructReturn;
2115 /// ArgsAreStructReturn - Determines whether a function uses struct
2116 /// return semantics.
2117 static StructReturnType
2118 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2120 return NotStructReturn;
2122 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2123 if (!Flags.isSRet())
2124 return NotStructReturn;
2125 if (Flags.isInReg())
2126 return RegStructReturn;
2127 return StackStructReturn;
2130 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2131 /// by "Src" to address "Dst" with size and alignment information specified by
2132 /// the specific parameter attribute. The copy will be passed as a byval
2133 /// function parameter.
2135 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2136 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2138 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2140 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2141 /*isVolatile*/false, /*AlwaysInline=*/true,
2142 MachinePointerInfo(), MachinePointerInfo());
2145 /// IsTailCallConvention - Return true if the calling convention is one that
2146 /// supports tail call optimization.
2147 static bool IsTailCallConvention(CallingConv::ID CC) {
2148 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2149 CC == CallingConv::HiPE);
2152 /// \brief Return true if the calling convention is a C calling convention.
2153 static bool IsCCallConvention(CallingConv::ID CC) {
2154 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2155 CC == CallingConv::X86_64_SysV);
2158 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2159 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2163 CallingConv::ID CalleeCC = CS.getCallingConv();
2164 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2170 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2171 /// a tailcall target by changing its ABI.
2172 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2173 bool GuaranteedTailCallOpt) {
2174 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2178 X86TargetLowering::LowerMemArgument(SDValue Chain,
2179 CallingConv::ID CallConv,
2180 const SmallVectorImpl<ISD::InputArg> &Ins,
2181 SDLoc dl, SelectionDAG &DAG,
2182 const CCValAssign &VA,
2183 MachineFrameInfo *MFI,
2185 // Create the nodes corresponding to a load from this parameter slot.
2186 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2187 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2188 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2189 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2192 // If value is passed by pointer we have address passed instead of the value
2194 if (VA.getLocInfo() == CCValAssign::Indirect)
2195 ValVT = VA.getLocVT();
2197 ValVT = VA.getValVT();
2199 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2200 // changed with more analysis.
2201 // In case of tail call optimization mark all arguments mutable. Since they
2202 // could be overwritten by lowering of arguments in case of a tail call.
2203 if (Flags.isByVal()) {
2204 unsigned Bytes = Flags.getByValSize();
2205 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2206 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2207 return DAG.getFrameIndex(FI, getPointerTy());
2209 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2210 VA.getLocMemOffset(), isImmutable);
2211 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2212 return DAG.getLoad(ValVT, dl, Chain, FIN,
2213 MachinePointerInfo::getFixedStack(FI),
2214 false, false, false, 0);
2219 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2220 CallingConv::ID CallConv,
2222 const SmallVectorImpl<ISD::InputArg> &Ins,
2225 SmallVectorImpl<SDValue> &InVals)
2227 MachineFunction &MF = DAG.getMachineFunction();
2228 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2230 const Function* Fn = MF.getFunction();
2231 if (Fn->hasExternalLinkage() &&
2232 Subtarget->isTargetCygMing() &&
2233 Fn->getName() == "main")
2234 FuncInfo->setForceFramePointer(true);
2236 MachineFrameInfo *MFI = MF.getFrameInfo();
2237 bool Is64Bit = Subtarget->is64Bit();
2238 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2240 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2241 "Var args not supported with calling convention fastcc, ghc or hipe");
2243 // Assign locations to all of the incoming arguments.
2244 SmallVector<CCValAssign, 16> ArgLocs;
2245 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2246 ArgLocs, *DAG.getContext());
2248 // Allocate shadow area for Win64
2250 CCInfo.AllocateStack(32, 8);
2252 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2254 unsigned LastVal = ~0U;
2256 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2257 CCValAssign &VA = ArgLocs[i];
2258 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2260 assert(VA.getValNo() != LastVal &&
2261 "Don't support value assigned to multiple locs yet");
2263 LastVal = VA.getValNo();
2265 if (VA.isRegLoc()) {
2266 EVT RegVT = VA.getLocVT();
2267 const TargetRegisterClass *RC;
2268 if (RegVT == MVT::i32)
2269 RC = &X86::GR32RegClass;
2270 else if (Is64Bit && RegVT == MVT::i64)
2271 RC = &X86::GR64RegClass;
2272 else if (RegVT == MVT::f32)
2273 RC = &X86::FR32RegClass;
2274 else if (RegVT == MVT::f64)
2275 RC = &X86::FR64RegClass;
2276 else if (RegVT.is512BitVector())
2277 RC = &X86::VR512RegClass;
2278 else if (RegVT.is256BitVector())
2279 RC = &X86::VR256RegClass;
2280 else if (RegVT.is128BitVector())
2281 RC = &X86::VR128RegClass;
2282 else if (RegVT == MVT::x86mmx)
2283 RC = &X86::VR64RegClass;
2284 else if (RegVT == MVT::i1)
2285 RC = &X86::VK1RegClass;
2286 else if (RegVT == MVT::v8i1)
2287 RC = &X86::VK8RegClass;
2288 else if (RegVT == MVT::v16i1)
2289 RC = &X86::VK16RegClass;
2291 llvm_unreachable("Unknown argument type!");
2293 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2294 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2296 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2297 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2299 if (VA.getLocInfo() == CCValAssign::SExt)
2300 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2301 DAG.getValueType(VA.getValVT()));
2302 else if (VA.getLocInfo() == CCValAssign::ZExt)
2303 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2304 DAG.getValueType(VA.getValVT()));
2305 else if (VA.getLocInfo() == CCValAssign::BCvt)
2306 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2308 if (VA.isExtInLoc()) {
2309 // Handle MMX values passed in XMM regs.
2310 if (RegVT.isVector())
2311 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2313 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2316 assert(VA.isMemLoc());
2317 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2320 // If value is passed via pointer - do a load.
2321 if (VA.getLocInfo() == CCValAssign::Indirect)
2322 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2323 MachinePointerInfo(), false, false, false, 0);
2325 InVals.push_back(ArgValue);
2328 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2329 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2330 // The x86-64 ABIs require that for returning structs by value we copy
2331 // the sret argument into %rax/%eax (depending on ABI) for the return.
2332 // Win32 requires us to put the sret argument to %eax as well.
2333 // Save the argument into a virtual register so that we can access it
2334 // from the return points.
2335 if (Ins[i].Flags.isSRet()) {
2336 unsigned Reg = FuncInfo->getSRetReturnReg();
2338 MVT PtrTy = getPointerTy();
2339 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2340 FuncInfo->setSRetReturnReg(Reg);
2342 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2343 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2349 unsigned StackSize = CCInfo.getNextStackOffset();
2350 // Align stack specially for tail calls.
2351 if (FuncIsMadeTailCallSafe(CallConv,
2352 MF.getTarget().Options.GuaranteedTailCallOpt))
2353 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2355 // If the function takes variable number of arguments, make a frame index for
2356 // the start of the first vararg value... for expansion of llvm.va_start.
2358 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2359 CallConv != CallingConv::X86_ThisCall)) {
2360 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2363 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2365 // FIXME: We should really autogenerate these arrays
2366 static const MCPhysReg GPR64ArgRegsWin64[] = {
2367 X86::RCX, X86::RDX, X86::R8, X86::R9
2369 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2370 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2372 static const MCPhysReg XMMArgRegs64Bit[] = {
2373 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2374 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2376 const MCPhysReg *GPR64ArgRegs;
2377 unsigned NumXMMRegs = 0;
2380 // The XMM registers which might contain var arg parameters are shadowed
2381 // in their paired GPR. So we only need to save the GPR to their home
2383 TotalNumIntRegs = 4;
2384 GPR64ArgRegs = GPR64ArgRegsWin64;
2386 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2387 GPR64ArgRegs = GPR64ArgRegs64Bit;
2389 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2392 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2395 bool NoImplicitFloatOps = Fn->getAttributes().
2396 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2397 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2398 "SSE register cannot be used when SSE is disabled!");
2399 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2400 NoImplicitFloatOps) &&
2401 "SSE register cannot be used when SSE is disabled!");
2402 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2403 !Subtarget->hasSSE1())
2404 // Kernel mode asks for SSE to be disabled, so don't push them
2406 TotalNumXMMRegs = 0;
2409 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2410 // Get to the caller-allocated home save location. Add 8 to account
2411 // for the return address.
2412 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2413 FuncInfo->setRegSaveFrameIndex(
2414 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2415 // Fixup to set vararg frame on shadow area (4 x i64).
2417 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2419 // For X86-64, if there are vararg parameters that are passed via
2420 // registers, then we must store them to their spots on the stack so
2421 // they may be loaded by deferencing the result of va_next.
2422 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2423 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2424 FuncInfo->setRegSaveFrameIndex(
2425 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2429 // Store the integer parameter registers.
2430 SmallVector<SDValue, 8> MemOps;
2431 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2433 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2434 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2435 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2436 DAG.getIntPtrConstant(Offset));
2437 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2438 &X86::GR64RegClass);
2439 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2441 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2442 MachinePointerInfo::getFixedStack(
2443 FuncInfo->getRegSaveFrameIndex(), Offset),
2445 MemOps.push_back(Store);
2449 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2450 // Now store the XMM (fp + vector) parameter registers.
2451 SmallVector<SDValue, 11> SaveXMMOps;
2452 SaveXMMOps.push_back(Chain);
2454 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2455 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2456 SaveXMMOps.push_back(ALVal);
2458 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2459 FuncInfo->getRegSaveFrameIndex()));
2460 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2461 FuncInfo->getVarArgsFPOffset()));
2463 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2464 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2465 &X86::VR128RegClass);
2466 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2467 SaveXMMOps.push_back(Val);
2469 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2470 MVT::Other, SaveXMMOps));
2473 if (!MemOps.empty())
2474 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2478 // Some CCs need callee pop.
2479 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2480 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2481 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2483 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2484 // If this is an sret function, the return should pop the hidden pointer.
2485 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2486 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2487 argsAreStructReturn(Ins) == StackStructReturn)
2488 FuncInfo->setBytesToPopOnReturn(4);
2492 // RegSaveFrameIndex is X86-64 only.
2493 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2494 if (CallConv == CallingConv::X86_FastCall ||
2495 CallConv == CallingConv::X86_ThisCall)
2496 // fastcc functions can't have varargs.
2497 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2500 FuncInfo->setArgumentStackSize(StackSize);
2506 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2507 SDValue StackPtr, SDValue Arg,
2508 SDLoc dl, SelectionDAG &DAG,
2509 const CCValAssign &VA,
2510 ISD::ArgFlagsTy Flags) const {
2511 unsigned LocMemOffset = VA.getLocMemOffset();
2512 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2513 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2514 if (Flags.isByVal())
2515 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2517 return DAG.getStore(Chain, dl, Arg, PtrOff,
2518 MachinePointerInfo::getStack(LocMemOffset),
2522 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2523 /// optimization is performed and it is required.
2525 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2526 SDValue &OutRetAddr, SDValue Chain,
2527 bool IsTailCall, bool Is64Bit,
2528 int FPDiff, SDLoc dl) const {
2529 // Adjust the Return address stack slot.
2530 EVT VT = getPointerTy();
2531 OutRetAddr = getReturnAddressFrameIndex(DAG);
2533 // Load the "old" Return address.
2534 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2535 false, false, false, 0);
2536 return SDValue(OutRetAddr.getNode(), 1);
2539 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2540 /// optimization is performed and it is required (FPDiff!=0).
2541 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2542 SDValue Chain, SDValue RetAddrFrIdx,
2543 EVT PtrVT, unsigned SlotSize,
2544 int FPDiff, SDLoc dl) {
2545 // Store the return address to the appropriate stack slot.
2546 if (!FPDiff) return Chain;
2547 // Calculate the new stack slot for the return address.
2548 int NewReturnAddrFI =
2549 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2551 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2552 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2553 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2559 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2560 SmallVectorImpl<SDValue> &InVals) const {
2561 SelectionDAG &DAG = CLI.DAG;
2563 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2564 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2565 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2566 SDValue Chain = CLI.Chain;
2567 SDValue Callee = CLI.Callee;
2568 CallingConv::ID CallConv = CLI.CallConv;
2569 bool &isTailCall = CLI.IsTailCall;
2570 bool isVarArg = CLI.IsVarArg;
2572 MachineFunction &MF = DAG.getMachineFunction();
2573 bool Is64Bit = Subtarget->is64Bit();
2574 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2575 StructReturnType SR = callIsStructReturn(Outs);
2576 bool IsSibcall = false;
2578 if (MF.getTarget().Options.DisableTailCalls)
2581 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2583 // Force this to be a tail call. The verifier rules are enough to ensure
2584 // that we can lower this successfully without moving the return address
2587 } else if (isTailCall) {
2588 // Check if it's really possible to do a tail call.
2589 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2590 isVarArg, SR != NotStructReturn,
2591 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2592 Outs, OutVals, Ins, DAG);
2594 // Sibcalls are automatically detected tailcalls which do not require
2596 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2603 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2604 "Var args not supported with calling convention fastcc, ghc or hipe");
2606 // Analyze operands of the call, assigning locations to each operand.
2607 SmallVector<CCValAssign, 16> ArgLocs;
2608 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2609 ArgLocs, *DAG.getContext());
2611 // Allocate shadow area for Win64
2613 CCInfo.AllocateStack(32, 8);
2615 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2617 // Get a count of how many bytes are to be pushed on the stack.
2618 unsigned NumBytes = CCInfo.getNextStackOffset();
2620 // This is a sibcall. The memory operands are available in caller's
2621 // own caller's stack.
2623 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2624 IsTailCallConvention(CallConv))
2625 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2628 if (isTailCall && !IsSibcall && !IsMustTail) {
2629 // Lower arguments at fp - stackoffset + fpdiff.
2630 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2631 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2633 FPDiff = NumBytesCallerPushed - NumBytes;
2635 // Set the delta of movement of the returnaddr stackslot.
2636 // But only set if delta is greater than previous delta.
2637 if (FPDiff < X86Info->getTCReturnAddrDelta())
2638 X86Info->setTCReturnAddrDelta(FPDiff);
2641 unsigned NumBytesToPush = NumBytes;
2642 unsigned NumBytesToPop = NumBytes;
2644 // If we have an inalloca argument, all stack space has already been allocated
2645 // for us and be right at the top of the stack. We don't support multiple
2646 // arguments passed in memory when using inalloca.
2647 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2649 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2650 "an inalloca argument must be the only memory argument");
2654 Chain = DAG.getCALLSEQ_START(
2655 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2657 SDValue RetAddrFrIdx;
2658 // Load return address for tail calls.
2659 if (isTailCall && FPDiff)
2660 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2661 Is64Bit, FPDiff, dl);
2663 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2664 SmallVector<SDValue, 8> MemOpChains;
2667 // Walk the register/memloc assignments, inserting copies/loads. In the case
2668 // of tail call optimization arguments are handle later.
2669 const X86RegisterInfo *RegInfo =
2670 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2671 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2672 // Skip inalloca arguments, they have already been written.
2673 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2674 if (Flags.isInAlloca())
2677 CCValAssign &VA = ArgLocs[i];
2678 EVT RegVT = VA.getLocVT();
2679 SDValue Arg = OutVals[i];
2680 bool isByVal = Flags.isByVal();
2682 // Promote the value if needed.
2683 switch (VA.getLocInfo()) {
2684 default: llvm_unreachable("Unknown loc info!");
2685 case CCValAssign::Full: break;
2686 case CCValAssign::SExt:
2687 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2689 case CCValAssign::ZExt:
2690 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2692 case CCValAssign::AExt:
2693 if (RegVT.is128BitVector()) {
2694 // Special case: passing MMX values in XMM registers.
2695 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2696 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2697 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2699 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2701 case CCValAssign::BCvt:
2702 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2704 case CCValAssign::Indirect: {
2705 // Store the argument.
2706 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2707 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2708 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2709 MachinePointerInfo::getFixedStack(FI),
2716 if (VA.isRegLoc()) {
2717 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2718 if (isVarArg && IsWin64) {
2719 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2720 // shadow reg if callee is a varargs function.
2721 unsigned ShadowReg = 0;
2722 switch (VA.getLocReg()) {
2723 case X86::XMM0: ShadowReg = X86::RCX; break;
2724 case X86::XMM1: ShadowReg = X86::RDX; break;
2725 case X86::XMM2: ShadowReg = X86::R8; break;
2726 case X86::XMM3: ShadowReg = X86::R9; break;
2729 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2731 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2732 assert(VA.isMemLoc());
2733 if (!StackPtr.getNode())
2734 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2736 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2737 dl, DAG, VA, Flags));
2741 if (!MemOpChains.empty())
2742 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2744 if (Subtarget->isPICStyleGOT()) {
2745 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2748 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2749 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2751 // If we are tail calling and generating PIC/GOT style code load the
2752 // address of the callee into ECX. The value in ecx is used as target of
2753 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2754 // for tail calls on PIC/GOT architectures. Normally we would just put the
2755 // address of GOT into ebx and then call target@PLT. But for tail calls
2756 // ebx would be restored (since ebx is callee saved) before jumping to the
2759 // Note: The actual moving to ECX is done further down.
2760 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2761 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2762 !G->getGlobal()->hasProtectedVisibility())
2763 Callee = LowerGlobalAddress(Callee, DAG);
2764 else if (isa<ExternalSymbolSDNode>(Callee))
2765 Callee = LowerExternalSymbol(Callee, DAG);
2769 if (Is64Bit && isVarArg && !IsWin64) {
2770 // From AMD64 ABI document:
2771 // For calls that may call functions that use varargs or stdargs
2772 // (prototype-less calls or calls to functions containing ellipsis (...) in
2773 // the declaration) %al is used as hidden argument to specify the number
2774 // of SSE registers used. The contents of %al do not need to match exactly
2775 // the number of registers, but must be an ubound on the number of SSE
2776 // registers used and is in the range 0 - 8 inclusive.
2778 // Count the number of XMM registers allocated.
2779 static const MCPhysReg XMMArgRegs[] = {
2780 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2781 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2783 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2784 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2785 && "SSE registers cannot be used when SSE is disabled");
2787 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2788 DAG.getConstant(NumXMMRegs, MVT::i8)));
2791 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2792 // don't need this because the eligibility check rejects calls that require
2793 // shuffling arguments passed in memory.
2794 if (!IsSibcall && isTailCall) {
2795 // Force all the incoming stack arguments to be loaded from the stack
2796 // before any new outgoing arguments are stored to the stack, because the
2797 // outgoing stack slots may alias the incoming argument stack slots, and
2798 // the alias isn't otherwise explicit. This is slightly more conservative
2799 // than necessary, because it means that each store effectively depends
2800 // on every argument instead of just those arguments it would clobber.
2801 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2803 SmallVector<SDValue, 8> MemOpChains2;
2806 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2807 CCValAssign &VA = ArgLocs[i];
2810 assert(VA.isMemLoc());
2811 SDValue Arg = OutVals[i];
2812 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2813 // Skip inalloca arguments. They don't require any work.
2814 if (Flags.isInAlloca())
2816 // Create frame index.
2817 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2818 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2819 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2820 FIN = DAG.getFrameIndex(FI, getPointerTy());
2822 if (Flags.isByVal()) {
2823 // Copy relative to framepointer.
2824 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2825 if (!StackPtr.getNode())
2826 StackPtr = DAG.getCopyFromReg(Chain, dl,
2827 RegInfo->getStackRegister(),
2829 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2831 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2835 // Store relative to framepointer.
2836 MemOpChains2.push_back(
2837 DAG.getStore(ArgChain, dl, Arg, FIN,
2838 MachinePointerInfo::getFixedStack(FI),
2843 if (!MemOpChains2.empty())
2844 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2846 // Store the return address to the appropriate stack slot.
2847 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2848 getPointerTy(), RegInfo->getSlotSize(),
2852 // Build a sequence of copy-to-reg nodes chained together with token chain
2853 // and flag operands which copy the outgoing args into registers.
2855 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2856 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2857 RegsToPass[i].second, InFlag);
2858 InFlag = Chain.getValue(1);
2861 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2862 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2863 // In the 64-bit large code model, we have to make all calls
2864 // through a register, since the call instruction's 32-bit
2865 // pc-relative offset may not be large enough to hold the whole
2867 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2868 // If the callee is a GlobalAddress node (quite common, every direct call
2869 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2872 // We should use extra load for direct calls to dllimported functions in
2874 const GlobalValue *GV = G->getGlobal();
2875 if (!GV->hasDLLImportStorageClass()) {
2876 unsigned char OpFlags = 0;
2877 bool ExtraLoad = false;
2878 unsigned WrapperKind = ISD::DELETED_NODE;
2880 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2881 // external symbols most go through the PLT in PIC mode. If the symbol
2882 // has hidden or protected visibility, or if it is static or local, then
2883 // we don't need to use the PLT - we can directly call it.
2884 if (Subtarget->isTargetELF() &&
2885 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2886 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2887 OpFlags = X86II::MO_PLT;
2888 } else if (Subtarget->isPICStyleStubAny() &&
2889 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2890 (!Subtarget->getTargetTriple().isMacOSX() ||
2891 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2892 // PC-relative references to external symbols should go through $stub,
2893 // unless we're building with the leopard linker or later, which
2894 // automatically synthesizes these stubs.
2895 OpFlags = X86II::MO_DARWIN_STUB;
2896 } else if (Subtarget->isPICStyleRIPRel() &&
2897 isa<Function>(GV) &&
2898 cast<Function>(GV)->getAttributes().
2899 hasAttribute(AttributeSet::FunctionIndex,
2900 Attribute::NonLazyBind)) {
2901 // If the function is marked as non-lazy, generate an indirect call
2902 // which loads from the GOT directly. This avoids runtime overhead
2903 // at the cost of eager binding (and one extra byte of encoding).
2904 OpFlags = X86II::MO_GOTPCREL;
2905 WrapperKind = X86ISD::WrapperRIP;
2909 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2910 G->getOffset(), OpFlags);
2912 // Add a wrapper if needed.
2913 if (WrapperKind != ISD::DELETED_NODE)
2914 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2915 // Add extra indirection if needed.
2917 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2918 MachinePointerInfo::getGOT(),
2919 false, false, false, 0);
2921 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2922 unsigned char OpFlags = 0;
2924 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2925 // external symbols should go through the PLT.
2926 if (Subtarget->isTargetELF() &&
2927 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2928 OpFlags = X86II::MO_PLT;
2929 } else if (Subtarget->isPICStyleStubAny() &&
2930 (!Subtarget->getTargetTriple().isMacOSX() ||
2931 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2932 // PC-relative references to external symbols should go through $stub,
2933 // unless we're building with the leopard linker or later, which
2934 // automatically synthesizes these stubs.
2935 OpFlags = X86II::MO_DARWIN_STUB;
2938 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2942 // Returns a chain & a flag for retval copy to use.
2943 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2944 SmallVector<SDValue, 8> Ops;
2946 if (!IsSibcall && isTailCall) {
2947 Chain = DAG.getCALLSEQ_END(Chain,
2948 DAG.getIntPtrConstant(NumBytesToPop, true),
2949 DAG.getIntPtrConstant(0, true), InFlag, dl);
2950 InFlag = Chain.getValue(1);
2953 Ops.push_back(Chain);
2954 Ops.push_back(Callee);
2957 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2959 // Add argument registers to the end of the list so that they are known live
2961 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2962 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2963 RegsToPass[i].second.getValueType()));
2965 // Add a register mask operand representing the call-preserved registers.
2966 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2967 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2968 assert(Mask && "Missing call preserved mask for calling convention");
2969 Ops.push_back(DAG.getRegisterMask(Mask));
2971 if (InFlag.getNode())
2972 Ops.push_back(InFlag);
2976 //// If this is the first return lowered for this function, add the regs
2977 //// to the liveout set for the function.
2978 // This isn't right, although it's probably harmless on x86; liveouts
2979 // should be computed from returns not tail calls. Consider a void
2980 // function making a tail call to a function returning int.
2981 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2984 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2985 InFlag = Chain.getValue(1);
2987 // Create the CALLSEQ_END node.
2988 unsigned NumBytesForCalleeToPop;
2989 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2990 DAG.getTarget().Options.GuaranteedTailCallOpt))
2991 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2992 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2993 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2994 SR == StackStructReturn)
2995 // If this is a call to a struct-return function, the callee
2996 // pops the hidden struct pointer, so we have to push it back.
2997 // This is common for Darwin/X86, Linux & Mingw32 targets.
2998 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2999 NumBytesForCalleeToPop = 4;
3001 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3003 // Returns a flag for retval copy to use.
3005 Chain = DAG.getCALLSEQ_END(Chain,
3006 DAG.getIntPtrConstant(NumBytesToPop, true),
3007 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3010 InFlag = Chain.getValue(1);
3013 // Handle result values, copying them out of physregs into vregs that we
3015 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3016 Ins, dl, DAG, InVals);
3019 //===----------------------------------------------------------------------===//
3020 // Fast Calling Convention (tail call) implementation
3021 //===----------------------------------------------------------------------===//
3023 // Like std call, callee cleans arguments, convention except that ECX is
3024 // reserved for storing the tail called function address. Only 2 registers are
3025 // free for argument passing (inreg). Tail call optimization is performed
3027 // * tailcallopt is enabled
3028 // * caller/callee are fastcc
3029 // On X86_64 architecture with GOT-style position independent code only local
3030 // (within module) calls are supported at the moment.
3031 // To keep the stack aligned according to platform abi the function
3032 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3033 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3034 // If a tail called function callee has more arguments than the caller the
3035 // caller needs to make sure that there is room to move the RETADDR to. This is
3036 // achieved by reserving an area the size of the argument delta right after the
3037 // original REtADDR, but before the saved framepointer or the spilled registers
3038 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3050 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3051 /// for a 16 byte align requirement.
3053 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3054 SelectionDAG& DAG) const {
3055 MachineFunction &MF = DAG.getMachineFunction();
3056 const TargetMachine &TM = MF.getTarget();
3057 const X86RegisterInfo *RegInfo =
3058 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3059 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3060 unsigned StackAlignment = TFI.getStackAlignment();
3061 uint64_t AlignMask = StackAlignment - 1;
3062 int64_t Offset = StackSize;
3063 unsigned SlotSize = RegInfo->getSlotSize();
3064 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3065 // Number smaller than 12 so just add the difference.
3066 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3068 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3069 Offset = ((~AlignMask) & Offset) + StackAlignment +
3070 (StackAlignment-SlotSize);
3075 /// MatchingStackOffset - Return true if the given stack call argument is
3076 /// already available in the same position (relatively) of the caller's
3077 /// incoming argument stack.
3079 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3080 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3081 const X86InstrInfo *TII) {
3082 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3084 if (Arg.getOpcode() == ISD::CopyFromReg) {
3085 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3086 if (!TargetRegisterInfo::isVirtualRegister(VR))
3088 MachineInstr *Def = MRI->getVRegDef(VR);
3091 if (!Flags.isByVal()) {
3092 if (!TII->isLoadFromStackSlot(Def, FI))
3095 unsigned Opcode = Def->getOpcode();
3096 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3097 Def->getOperand(1).isFI()) {
3098 FI = Def->getOperand(1).getIndex();
3099 Bytes = Flags.getByValSize();
3103 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3104 if (Flags.isByVal())
3105 // ByVal argument is passed in as a pointer but it's now being
3106 // dereferenced. e.g.
3107 // define @foo(%struct.X* %A) {
3108 // tail call @bar(%struct.X* byval %A)
3111 SDValue Ptr = Ld->getBasePtr();
3112 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3115 FI = FINode->getIndex();
3116 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3117 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3118 FI = FINode->getIndex();
3119 Bytes = Flags.getByValSize();
3123 assert(FI != INT_MAX);
3124 if (!MFI->isFixedObjectIndex(FI))
3126 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3129 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3130 /// for tail call optimization. Targets which want to do tail call
3131 /// optimization should implement this function.
3133 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3134 CallingConv::ID CalleeCC,
3136 bool isCalleeStructRet,
3137 bool isCallerStructRet,
3139 const SmallVectorImpl<ISD::OutputArg> &Outs,
3140 const SmallVectorImpl<SDValue> &OutVals,
3141 const SmallVectorImpl<ISD::InputArg> &Ins,
3142 SelectionDAG &DAG) const {
3143 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3146 // If -tailcallopt is specified, make fastcc functions tail-callable.
3147 const MachineFunction &MF = DAG.getMachineFunction();
3148 const Function *CallerF = MF.getFunction();
3150 // If the function return type is x86_fp80 and the callee return type is not,
3151 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3152 // perform a tailcall optimization here.
3153 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3156 CallingConv::ID CallerCC = CallerF->getCallingConv();
3157 bool CCMatch = CallerCC == CalleeCC;
3158 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3159 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3161 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3162 if (IsTailCallConvention(CalleeCC) && CCMatch)
3167 // Look for obvious safe cases to perform tail call optimization that do not
3168 // require ABI changes. This is what gcc calls sibcall.
3170 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3171 // emit a special epilogue.
3172 const X86RegisterInfo *RegInfo =
3173 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3174 if (RegInfo->needsStackRealignment(MF))
3177 // Also avoid sibcall optimization if either caller or callee uses struct
3178 // return semantics.
3179 if (isCalleeStructRet || isCallerStructRet)
3182 // An stdcall/thiscall caller is expected to clean up its arguments; the
3183 // callee isn't going to do that.
3184 // FIXME: this is more restrictive than needed. We could produce a tailcall
3185 // when the stack adjustment matches. For example, with a thiscall that takes
3186 // only one argument.
3187 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3188 CallerCC == CallingConv::X86_ThisCall))
3191 // Do not sibcall optimize vararg calls unless all arguments are passed via
3193 if (isVarArg && !Outs.empty()) {
3195 // Optimizing for varargs on Win64 is unlikely to be safe without
3196 // additional testing.
3197 if (IsCalleeWin64 || IsCallerWin64)
3200 SmallVector<CCValAssign, 16> ArgLocs;
3201 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3202 DAG.getTarget(), ArgLocs, *DAG.getContext());
3204 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3205 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3206 if (!ArgLocs[i].isRegLoc())
3210 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3211 // stack. Therefore, if it's not used by the call it is not safe to optimize
3212 // this into a sibcall.
3213 bool Unused = false;
3214 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3221 SmallVector<CCValAssign, 16> RVLocs;
3222 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3223 DAG.getTarget(), RVLocs, *DAG.getContext());
3224 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3225 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3226 CCValAssign &VA = RVLocs[i];
3227 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3232 // If the calling conventions do not match, then we'd better make sure the
3233 // results are returned in the same way as what the caller expects.
3235 SmallVector<CCValAssign, 16> RVLocs1;
3236 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3237 DAG.getTarget(), RVLocs1, *DAG.getContext());
3238 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3240 SmallVector<CCValAssign, 16> RVLocs2;
3241 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3242 DAG.getTarget(), RVLocs2, *DAG.getContext());
3243 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3245 if (RVLocs1.size() != RVLocs2.size())
3247 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3248 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3250 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3252 if (RVLocs1[i].isRegLoc()) {
3253 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3256 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3262 // If the callee takes no arguments then go on to check the results of the
3264 if (!Outs.empty()) {
3265 // Check if stack adjustment is needed. For now, do not do this if any
3266 // argument is passed on the stack.
3267 SmallVector<CCValAssign, 16> ArgLocs;
3268 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3269 DAG.getTarget(), ArgLocs, *DAG.getContext());
3271 // Allocate shadow area for Win64
3273 CCInfo.AllocateStack(32, 8);
3275 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3276 if (CCInfo.getNextStackOffset()) {
3277 MachineFunction &MF = DAG.getMachineFunction();
3278 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3281 // Check if the arguments are already laid out in the right way as
3282 // the caller's fixed stack objects.
3283 MachineFrameInfo *MFI = MF.getFrameInfo();
3284 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3285 const X86InstrInfo *TII =
3286 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3287 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3288 CCValAssign &VA = ArgLocs[i];
3289 SDValue Arg = OutVals[i];
3290 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3291 if (VA.getLocInfo() == CCValAssign::Indirect)
3293 if (!VA.isRegLoc()) {
3294 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3301 // If the tailcall address may be in a register, then make sure it's
3302 // possible to register allocate for it. In 32-bit, the call address can
3303 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3304 // callee-saved registers are restored. These happen to be the same
3305 // registers used to pass 'inreg' arguments so watch out for those.
3306 if (!Subtarget->is64Bit() &&
3307 ((!isa<GlobalAddressSDNode>(Callee) &&
3308 !isa<ExternalSymbolSDNode>(Callee)) ||
3309 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3310 unsigned NumInRegs = 0;
3311 // In PIC we need an extra register to formulate the address computation
3313 unsigned MaxInRegs =
3314 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3316 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3317 CCValAssign &VA = ArgLocs[i];
3320 unsigned Reg = VA.getLocReg();
3323 case X86::EAX: case X86::EDX: case X86::ECX:
3324 if (++NumInRegs == MaxInRegs)
3336 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3337 const TargetLibraryInfo *libInfo) const {
3338 return X86::createFastISel(funcInfo, libInfo);
3341 //===----------------------------------------------------------------------===//
3342 // Other Lowering Hooks
3343 //===----------------------------------------------------------------------===//
3345 static bool MayFoldLoad(SDValue Op) {
3346 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3349 static bool MayFoldIntoStore(SDValue Op) {
3350 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3353 static bool isTargetShuffle(unsigned Opcode) {
3355 default: return false;
3356 case X86ISD::PSHUFD:
3357 case X86ISD::PSHUFHW:
3358 case X86ISD::PSHUFLW:
3360 case X86ISD::PALIGNR:
3361 case X86ISD::MOVLHPS:
3362 case X86ISD::MOVLHPD:
3363 case X86ISD::MOVHLPS:
3364 case X86ISD::MOVLPS:
3365 case X86ISD::MOVLPD:
3366 case X86ISD::MOVSHDUP:
3367 case X86ISD::MOVSLDUP:
3368 case X86ISD::MOVDDUP:
3371 case X86ISD::UNPCKL:
3372 case X86ISD::UNPCKH:
3373 case X86ISD::VPERMILP:
3374 case X86ISD::VPERM2X128:
3375 case X86ISD::VPERMI:
3380 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3381 SDValue V1, SelectionDAG &DAG) {
3383 default: llvm_unreachable("Unknown x86 shuffle node");
3384 case X86ISD::MOVSHDUP:
3385 case X86ISD::MOVSLDUP:
3386 case X86ISD::MOVDDUP:
3387 return DAG.getNode(Opc, dl, VT, V1);
3391 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3392 SDValue V1, unsigned TargetMask,
3393 SelectionDAG &DAG) {
3395 default: llvm_unreachable("Unknown x86 shuffle node");
3396 case X86ISD::PSHUFD:
3397 case X86ISD::PSHUFHW:
3398 case X86ISD::PSHUFLW:
3399 case X86ISD::VPERMILP:
3400 case X86ISD::VPERMI:
3401 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406 SDValue V1, SDValue V2, unsigned TargetMask,
3407 SelectionDAG &DAG) {
3409 default: llvm_unreachable("Unknown x86 shuffle node");
3410 case X86ISD::PALIGNR:
3412 case X86ISD::VPERM2X128:
3413 return DAG.getNode(Opc, dl, VT, V1, V2,
3414 DAG.getConstant(TargetMask, MVT::i8));
3418 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3419 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3421 default: llvm_unreachable("Unknown x86 shuffle node");
3422 case X86ISD::MOVLHPS:
3423 case X86ISD::MOVLHPD:
3424 case X86ISD::MOVHLPS:
3425 case X86ISD::MOVLPS:
3426 case X86ISD::MOVLPD:
3429 case X86ISD::UNPCKL:
3430 case X86ISD::UNPCKH:
3431 return DAG.getNode(Opc, dl, VT, V1, V2);
3435 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3436 MachineFunction &MF = DAG.getMachineFunction();
3437 const X86RegisterInfo *RegInfo =
3438 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3439 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3440 int ReturnAddrIndex = FuncInfo->getRAIndex();
3442 if (ReturnAddrIndex == 0) {
3443 // Set up a frame object for the return address.
3444 unsigned SlotSize = RegInfo->getSlotSize();
3445 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3448 FuncInfo->setRAIndex(ReturnAddrIndex);
3451 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3454 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3455 bool hasSymbolicDisplacement) {
3456 // Offset should fit into 32 bit immediate field.
3457 if (!isInt<32>(Offset))
3460 // If we don't have a symbolic displacement - we don't have any extra
3462 if (!hasSymbolicDisplacement)
3465 // FIXME: Some tweaks might be needed for medium code model.
3466 if (M != CodeModel::Small && M != CodeModel::Kernel)
3469 // For small code model we assume that latest object is 16MB before end of 31
3470 // bits boundary. We may also accept pretty large negative constants knowing
3471 // that all objects are in the positive half of address space.
3472 if (M == CodeModel::Small && Offset < 16*1024*1024)
3475 // For kernel code model we know that all object resist in the negative half
3476 // of 32bits address space. We may not accept negative offsets, since they may
3477 // be just off and we may accept pretty large positive ones.
3478 if (M == CodeModel::Kernel && Offset > 0)
3484 /// isCalleePop - Determines whether the callee is required to pop its
3485 /// own arguments. Callee pop is necessary to support tail calls.
3486 bool X86::isCalleePop(CallingConv::ID CallingConv,
3487 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3491 switch (CallingConv) {
3494 case CallingConv::X86_StdCall:
3496 case CallingConv::X86_FastCall:
3498 case CallingConv::X86_ThisCall:
3500 case CallingConv::Fast:
3502 case CallingConv::GHC:
3504 case CallingConv::HiPE:
3509 /// \brief Return true if the condition is an unsigned comparison operation.
3510 static bool isX86CCUnsigned(unsigned X86CC) {
3512 default: llvm_unreachable("Invalid integer condition!");
3513 case X86::COND_E: return true;
3514 case X86::COND_G: return false;
3515 case X86::COND_GE: return false;
3516 case X86::COND_L: return false;
3517 case X86::COND_LE: return false;
3518 case X86::COND_NE: return true;
3519 case X86::COND_B: return true;
3520 case X86::COND_A: return true;
3521 case X86::COND_BE: return true;
3522 case X86::COND_AE: return true;
3524 llvm_unreachable("covered switch fell through?!");
3527 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3528 /// specific condition code, returning the condition code and the LHS/RHS of the
3529 /// comparison to make.
3530 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3531 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3533 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3534 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3535 // X > -1 -> X == 0, jump !sign.
3536 RHS = DAG.getConstant(0, RHS.getValueType());
3537 return X86::COND_NS;
3539 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3540 // X < 0 -> X == 0, jump on sign.
3543 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3545 RHS = DAG.getConstant(0, RHS.getValueType());
3546 return X86::COND_LE;
3550 switch (SetCCOpcode) {
3551 default: llvm_unreachable("Invalid integer condition!");
3552 case ISD::SETEQ: return X86::COND_E;
3553 case ISD::SETGT: return X86::COND_G;
3554 case ISD::SETGE: return X86::COND_GE;
3555 case ISD::SETLT: return X86::COND_L;
3556 case ISD::SETLE: return X86::COND_LE;
3557 case ISD::SETNE: return X86::COND_NE;
3558 case ISD::SETULT: return X86::COND_B;
3559 case ISD::SETUGT: return X86::COND_A;
3560 case ISD::SETULE: return X86::COND_BE;
3561 case ISD::SETUGE: return X86::COND_AE;
3565 // First determine if it is required or is profitable to flip the operands.
3567 // If LHS is a foldable load, but RHS is not, flip the condition.
3568 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3569 !ISD::isNON_EXTLoad(RHS.getNode())) {
3570 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3571 std::swap(LHS, RHS);
3574 switch (SetCCOpcode) {
3580 std::swap(LHS, RHS);
3584 // On a floating point condition, the flags are set as follows:
3586 // 0 | 0 | 0 | X > Y
3587 // 0 | 0 | 1 | X < Y
3588 // 1 | 0 | 0 | X == Y
3589 // 1 | 1 | 1 | unordered
3590 switch (SetCCOpcode) {
3591 default: llvm_unreachable("Condcode should be pre-legalized away");
3593 case ISD::SETEQ: return X86::COND_E;
3594 case ISD::SETOLT: // flipped
3596 case ISD::SETGT: return X86::COND_A;
3597 case ISD::SETOLE: // flipped
3599 case ISD::SETGE: return X86::COND_AE;
3600 case ISD::SETUGT: // flipped
3602 case ISD::SETLT: return X86::COND_B;
3603 case ISD::SETUGE: // flipped
3605 case ISD::SETLE: return X86::COND_BE;
3607 case ISD::SETNE: return X86::COND_NE;
3608 case ISD::SETUO: return X86::COND_P;
3609 case ISD::SETO: return X86::COND_NP;
3611 case ISD::SETUNE: return X86::COND_INVALID;
3615 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3616 /// code. Current x86 isa includes the following FP cmov instructions:
3617 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3618 static bool hasFPCMov(unsigned X86CC) {
3634 /// isFPImmLegal - Returns true if the target can instruction select the
3635 /// specified FP immediate natively. If false, the legalizer will
3636 /// materialize the FP immediate as a load from a constant pool.
3637 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3638 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3639 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3645 /// \brief Returns true if it is beneficial to convert a load of a constant
3646 /// to just the constant itself.
3647 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3649 assert(Ty->isIntegerTy());
3651 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3652 if (BitSize == 0 || BitSize > 64)
3657 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3658 /// the specified range (L, H].
3659 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3660 return (Val < 0) || (Val >= Low && Val < Hi);
3663 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3664 /// specified value.
3665 static bool isUndefOrEqual(int Val, int CmpVal) {
3666 return (Val < 0 || Val == CmpVal);
3669 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3670 /// from position Pos and ending in Pos+Size, falls within the specified
3671 /// sequential range (L, L+Pos]. or is undef.
3672 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3673 unsigned Pos, unsigned Size, int Low) {
3674 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3675 if (!isUndefOrEqual(Mask[i], Low))
3680 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3682 /// the second operand.
3683 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3684 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3685 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3686 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3687 return (Mask[0] < 2 && Mask[1] < 2);
3691 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3692 /// is suitable for input to PSHUFHW.
3693 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3694 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3697 // Lower quadword copied in order or undef.
3698 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3701 // Upper quadword shuffled.
3702 for (unsigned i = 4; i != 8; ++i)
3703 if (!isUndefOrInRange(Mask[i], 4, 8))
3706 if (VT == MVT::v16i16) {
3707 // Lower quadword copied in order or undef.
3708 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3711 // Upper quadword shuffled.
3712 for (unsigned i = 12; i != 16; ++i)
3713 if (!isUndefOrInRange(Mask[i], 12, 16))
3720 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3721 /// is suitable for input to PSHUFLW.
3722 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3723 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3726 // Upper quadword copied in order.
3727 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3730 // Lower quadword shuffled.
3731 for (unsigned i = 0; i != 4; ++i)
3732 if (!isUndefOrInRange(Mask[i], 0, 4))
3735 if (VT == MVT::v16i16) {
3736 // Upper quadword copied in order.
3737 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3740 // Lower quadword shuffled.
3741 for (unsigned i = 8; i != 12; ++i)
3742 if (!isUndefOrInRange(Mask[i], 8, 12))
3749 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3750 /// is suitable for input to PALIGNR.
3751 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3752 const X86Subtarget *Subtarget) {
3753 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3754 (VT.is256BitVector() && !Subtarget->hasInt256()))
3757 unsigned NumElts = VT.getVectorNumElements();
3758 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3759 unsigned NumLaneElts = NumElts/NumLanes;
3761 // Do not handle 64-bit element shuffles with palignr.
3762 if (NumLaneElts == 2)
3765 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3767 for (i = 0; i != NumLaneElts; ++i) {
3772 // Lane is all undef, go to next lane
3773 if (i == NumLaneElts)
3776 int Start = Mask[i+l];
3778 // Make sure its in this lane in one of the sources
3779 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3780 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3783 // If not lane 0, then we must match lane 0
3784 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3787 // Correct second source to be contiguous with first source
3788 if (Start >= (int)NumElts)
3789 Start -= NumElts - NumLaneElts;
3791 // Make sure we're shifting in the right direction.
3792 if (Start <= (int)(i+l))
3797 // Check the rest of the elements to see if they are consecutive.
3798 for (++i; i != NumLaneElts; ++i) {
3799 int Idx = Mask[i+l];
3801 // Make sure its in this lane
3802 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3803 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3806 // If not lane 0, then we must match lane 0
3807 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3810 if (Idx >= (int)NumElts)
3811 Idx -= NumElts - NumLaneElts;
3813 if (!isUndefOrEqual(Idx, Start+i))
3822 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3823 /// the two vector operands have swapped position.
3824 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3825 unsigned NumElems) {
3826 for (unsigned i = 0; i != NumElems; ++i) {
3830 else if (idx < (int)NumElems)
3831 Mask[i] = idx + NumElems;
3833 Mask[i] = idx - NumElems;
3837 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3838 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3839 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3840 /// reverse of what x86 shuffles want.
3841 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3843 unsigned NumElems = VT.getVectorNumElements();
3844 unsigned NumLanes = VT.getSizeInBits()/128;
3845 unsigned NumLaneElems = NumElems/NumLanes;
3847 if (NumLaneElems != 2 && NumLaneElems != 4)
3850 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3851 bool symetricMaskRequired =
3852 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3854 // VSHUFPSY divides the resulting vector into 4 chunks.
3855 // The sources are also splitted into 4 chunks, and each destination
3856 // chunk must come from a different source chunk.
3858 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3859 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3861 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3862 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3864 // VSHUFPDY divides the resulting vector into 4 chunks.
3865 // The sources are also splitted into 4 chunks, and each destination
3866 // chunk must come from a different source chunk.
3868 // SRC1 => X3 X2 X1 X0
3869 // SRC2 => Y3 Y2 Y1 Y0
3871 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3873 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3874 unsigned HalfLaneElems = NumLaneElems/2;
3875 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3876 for (unsigned i = 0; i != NumLaneElems; ++i) {
3877 int Idx = Mask[i+l];
3878 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3879 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3881 // For VSHUFPSY, the mask of the second half must be the same as the
3882 // first but with the appropriate offsets. This works in the same way as
3883 // VPERMILPS works with masks.
3884 if (!symetricMaskRequired || Idx < 0)
3886 if (MaskVal[i] < 0) {
3887 MaskVal[i] = Idx - l;
3890 if ((signed)(Idx - l) != MaskVal[i])
3898 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3899 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3900 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3901 if (!VT.is128BitVector())
3904 unsigned NumElems = VT.getVectorNumElements();
3909 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3910 return isUndefOrEqual(Mask[0], 6) &&
3911 isUndefOrEqual(Mask[1], 7) &&
3912 isUndefOrEqual(Mask[2], 2) &&
3913 isUndefOrEqual(Mask[3], 3);
3916 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3917 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3919 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3920 if (!VT.is128BitVector())
3923 unsigned NumElems = VT.getVectorNumElements();
3928 return isUndefOrEqual(Mask[0], 2) &&
3929 isUndefOrEqual(Mask[1], 3) &&
3930 isUndefOrEqual(Mask[2], 2) &&
3931 isUndefOrEqual(Mask[3], 3);
3934 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3935 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3936 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3937 if (!VT.is128BitVector())
3940 unsigned NumElems = VT.getVectorNumElements();
3942 if (NumElems != 2 && NumElems != 4)
3945 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3946 if (!isUndefOrEqual(Mask[i], i + NumElems))
3949 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3950 if (!isUndefOrEqual(Mask[i], i))
3956 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3957 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3958 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3959 if (!VT.is128BitVector())
3962 unsigned NumElems = VT.getVectorNumElements();
3964 if (NumElems != 2 && NumElems != 4)
3967 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3968 if (!isUndefOrEqual(Mask[i], i))
3971 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3972 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3978 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3980 /// i. e: If all but one element come from the same vector.
3981 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3982 // TODO: Deal with AVX's VINSERTPS
3983 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3986 unsigned CorrectPosV1 = 0;
3987 unsigned CorrectPosV2 = 0;
3988 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3989 if (Mask[i] == -1) {
3997 else if (Mask[i] == i + 4)
4001 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4002 // We have 3 elements (undefs count as elements from any vector) from one
4003 // vector, and one from another.
4010 // Some special combinations that can be optimized.
4013 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4014 SelectionDAG &DAG) {
4015 MVT VT = SVOp->getSimpleValueType(0);
4018 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4021 ArrayRef<int> Mask = SVOp->getMask();
4023 // These are the special masks that may be optimized.
4024 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4025 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4026 bool MatchEvenMask = true;
4027 bool MatchOddMask = true;
4028 for (int i=0; i<8; ++i) {
4029 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4030 MatchEvenMask = false;
4031 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4032 MatchOddMask = false;
4035 if (!MatchEvenMask && !MatchOddMask)
4038 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4040 SDValue Op0 = SVOp->getOperand(0);
4041 SDValue Op1 = SVOp->getOperand(1);
4043 if (MatchEvenMask) {
4044 // Shift the second operand right to 32 bits.
4045 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4046 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4048 // Shift the first operand left to 32 bits.
4049 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4050 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4052 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4053 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4056 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4057 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4058 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4059 bool HasInt256, bool V2IsSplat = false) {
4061 assert(VT.getSizeInBits() >= 128 &&
4062 "Unsupported vector type for unpckl");
4064 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4066 unsigned NumOf256BitLanes;
4067 unsigned NumElts = VT.getVectorNumElements();
4068 if (VT.is256BitVector()) {
4069 if (NumElts != 4 && NumElts != 8 &&
4070 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4073 NumOf256BitLanes = 1;
4074 } else if (VT.is512BitVector()) {
4075 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4076 "Unsupported vector type for unpckh");
4078 NumOf256BitLanes = 2;
4081 NumOf256BitLanes = 1;
4084 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4085 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4087 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4088 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4089 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4090 int BitI = Mask[l256*NumEltsInStride+l+i];
4091 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4092 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4094 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4096 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4104 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4105 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4106 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4107 bool HasInt256, bool V2IsSplat = false) {
4108 assert(VT.getSizeInBits() >= 128 &&
4109 "Unsupported vector type for unpckh");
4111 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4113 unsigned NumOf256BitLanes;
4114 unsigned NumElts = VT.getVectorNumElements();
4115 if (VT.is256BitVector()) {
4116 if (NumElts != 4 && NumElts != 8 &&
4117 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4120 NumOf256BitLanes = 1;
4121 } else if (VT.is512BitVector()) {
4122 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4123 "Unsupported vector type for unpckh");
4125 NumOf256BitLanes = 2;
4128 NumOf256BitLanes = 1;
4131 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4132 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4134 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4135 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4136 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4137 int BitI = Mask[l256*NumEltsInStride+l+i];
4138 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4139 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4141 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4143 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4151 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4152 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4154 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4155 unsigned NumElts = VT.getVectorNumElements();
4156 bool Is256BitVec = VT.is256BitVector();
4158 if (VT.is512BitVector())
4160 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4161 "Unsupported vector type for unpckh");
4163 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4164 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4167 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4168 // FIXME: Need a better way to get rid of this, there's no latency difference
4169 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4170 // the former later. We should also remove the "_undef" special mask.
4171 if (NumElts == 4 && Is256BitVec)
4174 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4175 // independently on 128-bit lanes.
4176 unsigned NumLanes = VT.getSizeInBits()/128;
4177 unsigned NumLaneElts = NumElts/NumLanes;
4179 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4180 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4181 int BitI = Mask[l+i];
4182 int BitI1 = Mask[l+i+1];
4184 if (!isUndefOrEqual(BitI, j))
4186 if (!isUndefOrEqual(BitI1, j))
4194 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4195 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4197 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4198 unsigned NumElts = VT.getVectorNumElements();
4200 if (VT.is512BitVector())
4203 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4204 "Unsupported vector type for unpckh");
4206 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4207 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4210 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4211 // independently on 128-bit lanes.
4212 unsigned NumLanes = VT.getSizeInBits()/128;
4213 unsigned NumLaneElts = NumElts/NumLanes;
4215 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4216 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4217 int BitI = Mask[l+i];
4218 int BitI1 = Mask[l+i+1];
4219 if (!isUndefOrEqual(BitI, j))
4221 if (!isUndefOrEqual(BitI1, j))
4228 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4229 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4230 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4231 if (!VT.is512BitVector())
4234 unsigned NumElts = VT.getVectorNumElements();
4235 unsigned HalfSize = NumElts/2;
4236 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4237 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4242 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4243 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4251 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4252 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4253 /// MOVSD, and MOVD, i.e. setting the lowest element.
4254 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4255 if (VT.getVectorElementType().getSizeInBits() < 32)
4257 if (!VT.is128BitVector())
4260 unsigned NumElts = VT.getVectorNumElements();
4262 if (!isUndefOrEqual(Mask[0], NumElts))
4265 for (unsigned i = 1; i != NumElts; ++i)
4266 if (!isUndefOrEqual(Mask[i], i))
4272 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4273 /// as permutations between 128-bit chunks or halves. As an example: this
4275 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4276 /// The first half comes from the second half of V1 and the second half from the
4277 /// the second half of V2.
4278 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4279 if (!HasFp256 || !VT.is256BitVector())
4282 // The shuffle result is divided into half A and half B. In total the two
4283 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4284 // B must come from C, D, E or F.
4285 unsigned HalfSize = VT.getVectorNumElements()/2;
4286 bool MatchA = false, MatchB = false;
4288 // Check if A comes from one of C, D, E, F.
4289 for (unsigned Half = 0; Half != 4; ++Half) {
4290 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4296 // Check if B comes from one of C, D, E, F.
4297 for (unsigned Half = 0; Half != 4; ++Half) {
4298 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4304 return MatchA && MatchB;
4307 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4308 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4309 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4310 MVT VT = SVOp->getSimpleValueType(0);
4312 unsigned HalfSize = VT.getVectorNumElements()/2;
4314 unsigned FstHalf = 0, SndHalf = 0;
4315 for (unsigned i = 0; i < HalfSize; ++i) {
4316 if (SVOp->getMaskElt(i) > 0) {
4317 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4321 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4322 if (SVOp->getMaskElt(i) > 0) {
4323 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4328 return (FstHalf | (SndHalf << 4));
4331 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4332 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4333 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4337 unsigned NumElts = VT.getVectorNumElements();
4339 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4340 for (unsigned i = 0; i != NumElts; ++i) {
4343 Imm8 |= Mask[i] << (i*2);
4348 unsigned LaneSize = 4;
4349 SmallVector<int, 4> MaskVal(LaneSize, -1);
4351 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4352 for (unsigned i = 0; i != LaneSize; ++i) {
4353 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4357 if (MaskVal[i] < 0) {
4358 MaskVal[i] = Mask[i+l] - l;
4359 Imm8 |= MaskVal[i] << (i*2);
4362 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4369 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4370 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4371 /// Note that VPERMIL mask matching is different depending whether theunderlying
4372 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4373 /// to the same elements of the low, but to the higher half of the source.
4374 /// In VPERMILPD the two lanes could be shuffled independently of each other
4375 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4376 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4377 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4378 if (VT.getSizeInBits() < 256 || EltSize < 32)
4380 bool symetricMaskRequired = (EltSize == 32);
4381 unsigned NumElts = VT.getVectorNumElements();
4383 unsigned NumLanes = VT.getSizeInBits()/128;
4384 unsigned LaneSize = NumElts/NumLanes;
4385 // 2 or 4 elements in one lane
4387 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4388 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4389 for (unsigned i = 0; i != LaneSize; ++i) {
4390 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4392 if (symetricMaskRequired) {
4393 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4394 ExpectedMaskVal[i] = Mask[i+l] - l;
4397 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4405 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4406 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4407 /// element of vector 2 and the other elements to come from vector 1 in order.
4408 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4409 bool V2IsSplat = false, bool V2IsUndef = false) {
4410 if (!VT.is128BitVector())
4413 unsigned NumOps = VT.getVectorNumElements();
4414 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4417 if (!isUndefOrEqual(Mask[0], 0))
4420 for (unsigned i = 1; i != NumOps; ++i)
4421 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4422 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4423 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4429 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4430 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4431 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4432 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4433 const X86Subtarget *Subtarget) {
4434 if (!Subtarget->hasSSE3())
4437 unsigned NumElems = VT.getVectorNumElements();
4439 if ((VT.is128BitVector() && NumElems != 4) ||
4440 (VT.is256BitVector() && NumElems != 8) ||
4441 (VT.is512BitVector() && NumElems != 16))
4444 // "i+1" is the value the indexed mask element must have
4445 for (unsigned i = 0; i != NumElems; i += 2)
4446 if (!isUndefOrEqual(Mask[i], i+1) ||
4447 !isUndefOrEqual(Mask[i+1], i+1))
4453 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4454 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4455 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4456 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4457 const X86Subtarget *Subtarget) {
4458 if (!Subtarget->hasSSE3())
4461 unsigned NumElems = VT.getVectorNumElements();
4463 if ((VT.is128BitVector() && NumElems != 4) ||
4464 (VT.is256BitVector() && NumElems != 8) ||
4465 (VT.is512BitVector() && NumElems != 16))
4468 // "i" is the value the indexed mask element must have
4469 for (unsigned i = 0; i != NumElems; i += 2)
4470 if (!isUndefOrEqual(Mask[i], i) ||
4471 !isUndefOrEqual(Mask[i+1], i))
4477 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4478 /// specifies a shuffle of elements that is suitable for input to 256-bit
4479 /// version of MOVDDUP.
4480 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4481 if (!HasFp256 || !VT.is256BitVector())
4484 unsigned NumElts = VT.getVectorNumElements();
4488 for (unsigned i = 0; i != NumElts/2; ++i)
4489 if (!isUndefOrEqual(Mask[i], 0))
4491 for (unsigned i = NumElts/2; i != NumElts; ++i)
4492 if (!isUndefOrEqual(Mask[i], NumElts/2))
4497 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4498 /// specifies a shuffle of elements that is suitable for input to 128-bit
4499 /// version of MOVDDUP.
4500 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4501 if (!VT.is128BitVector())
4504 unsigned e = VT.getVectorNumElements() / 2;
4505 for (unsigned i = 0; i != e; ++i)
4506 if (!isUndefOrEqual(Mask[i], i))
4508 for (unsigned i = 0; i != e; ++i)
4509 if (!isUndefOrEqual(Mask[e+i], i))
4514 /// isVEXTRACTIndex - Return true if the specified
4515 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4516 /// suitable for instruction that extract 128 or 256 bit vectors
4517 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4518 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4519 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4522 // The index should be aligned on a vecWidth-bit boundary.
4524 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4526 MVT VT = N->getSimpleValueType(0);
4527 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4528 bool Result = (Index * ElSize) % vecWidth == 0;
4533 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4534 /// operand specifies a subvector insert that is suitable for input to
4535 /// insertion of 128 or 256-bit subvectors
4536 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4537 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4538 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4540 // The index should be aligned on a vecWidth-bit boundary.
4542 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4544 MVT VT = N->getSimpleValueType(0);
4545 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4546 bool Result = (Index * ElSize) % vecWidth == 0;
4551 bool X86::isVINSERT128Index(SDNode *N) {
4552 return isVINSERTIndex(N, 128);
4555 bool X86::isVINSERT256Index(SDNode *N) {
4556 return isVINSERTIndex(N, 256);
4559 bool X86::isVEXTRACT128Index(SDNode *N) {
4560 return isVEXTRACTIndex(N, 128);
4563 bool X86::isVEXTRACT256Index(SDNode *N) {
4564 return isVEXTRACTIndex(N, 256);
4567 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4568 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4569 /// Handles 128-bit and 256-bit.
4570 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4571 MVT VT = N->getSimpleValueType(0);
4573 assert((VT.getSizeInBits() >= 128) &&
4574 "Unsupported vector type for PSHUF/SHUFP");
4576 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4577 // independently on 128-bit lanes.
4578 unsigned NumElts = VT.getVectorNumElements();
4579 unsigned NumLanes = VT.getSizeInBits()/128;
4580 unsigned NumLaneElts = NumElts/NumLanes;
4582 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4583 "Only supports 2, 4 or 8 elements per lane");
4585 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4587 for (unsigned i = 0; i != NumElts; ++i) {
4588 int Elt = N->getMaskElt(i);
4589 if (Elt < 0) continue;
4590 Elt &= NumLaneElts - 1;
4591 unsigned ShAmt = (i << Shift) % 8;
4592 Mask |= Elt << ShAmt;
4598 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4599 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4600 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4601 MVT VT = N->getSimpleValueType(0);
4603 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4604 "Unsupported vector type for PSHUFHW");
4606 unsigned NumElts = VT.getVectorNumElements();
4609 for (unsigned l = 0; l != NumElts; l += 8) {
4610 // 8 nodes per lane, but we only care about the last 4.
4611 for (unsigned i = 0; i < 4; ++i) {
4612 int Elt = N->getMaskElt(l+i+4);
4613 if (Elt < 0) continue;
4614 Elt &= 0x3; // only 2-bits.
4615 Mask |= Elt << (i * 2);
4622 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4623 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4624 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4625 MVT VT = N->getSimpleValueType(0);
4627 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4628 "Unsupported vector type for PSHUFHW");
4630 unsigned NumElts = VT.getVectorNumElements();
4633 for (unsigned l = 0; l != NumElts; l += 8) {
4634 // 8 nodes per lane, but we only care about the first 4.
4635 for (unsigned i = 0; i < 4; ++i) {
4636 int Elt = N->getMaskElt(l+i);
4637 if (Elt < 0) continue;
4638 Elt &= 0x3; // only 2-bits
4639 Mask |= Elt << (i * 2);
4646 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4647 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4648 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4649 MVT VT = SVOp->getSimpleValueType(0);
4650 unsigned EltSize = VT.is512BitVector() ? 1 :
4651 VT.getVectorElementType().getSizeInBits() >> 3;
4653 unsigned NumElts = VT.getVectorNumElements();
4654 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4655 unsigned NumLaneElts = NumElts/NumLanes;
4659 for (i = 0; i != NumElts; ++i) {
4660 Val = SVOp->getMaskElt(i);
4664 if (Val >= (int)NumElts)
4665 Val -= NumElts - NumLaneElts;
4667 assert(Val - i > 0 && "PALIGNR imm should be positive");
4668 return (Val - i) * EltSize;
4671 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4672 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4673 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4674 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4677 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4679 MVT VecVT = N->getOperand(0).getSimpleValueType();
4680 MVT ElVT = VecVT.getVectorElementType();
4682 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4683 return Index / NumElemsPerChunk;
4686 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4687 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4688 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4689 llvm_unreachable("Illegal insert subvector for VINSERT");
4692 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4694 MVT VecVT = N->getSimpleValueType(0);
4695 MVT ElVT = VecVT.getVectorElementType();
4697 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4698 return Index / NumElemsPerChunk;
4701 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4702 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4703 /// and VINSERTI128 instructions.
4704 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4705 return getExtractVEXTRACTImmediate(N, 128);
4708 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4709 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4710 /// and VINSERTI64x4 instructions.
4711 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4712 return getExtractVEXTRACTImmediate(N, 256);
4715 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4716 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4717 /// and VINSERTI128 instructions.
4718 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4719 return getInsertVINSERTImmediate(N, 128);
4722 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4723 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4724 /// and VINSERTI64x4 instructions.
4725 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4726 return getInsertVINSERTImmediate(N, 256);
4729 /// isZero - Returns true if Elt is a constant integer zero
4730 static bool isZero(SDValue V) {
4731 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4732 return C && C->isNullValue();
4735 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4737 bool X86::isZeroNode(SDValue Elt) {
4740 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4741 return CFP->getValueAPF().isPosZero();
4745 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4746 /// their permute mask.
4747 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4748 SelectionDAG &DAG) {
4749 MVT VT = SVOp->getSimpleValueType(0);
4750 unsigned NumElems = VT.getVectorNumElements();
4751 SmallVector<int, 8> MaskVec;
4753 for (unsigned i = 0; i != NumElems; ++i) {
4754 int Idx = SVOp->getMaskElt(i);
4756 if (Idx < (int)NumElems)
4761 MaskVec.push_back(Idx);
4763 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4764 SVOp->getOperand(0), &MaskVec[0]);
4767 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4768 /// match movhlps. The lower half elements should come from upper half of
4769 /// V1 (and in order), and the upper half elements should come from the upper
4770 /// half of V2 (and in order).
4771 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4772 if (!VT.is128BitVector())
4774 if (VT.getVectorNumElements() != 4)
4776 for (unsigned i = 0, e = 2; i != e; ++i)
4777 if (!isUndefOrEqual(Mask[i], i+2))
4779 for (unsigned i = 2; i != 4; ++i)
4780 if (!isUndefOrEqual(Mask[i], i+4))
4785 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4786 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4788 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4789 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4791 N = N->getOperand(0).getNode();
4792 if (!ISD::isNON_EXTLoad(N))
4795 *LD = cast<LoadSDNode>(N);
4799 // Test whether the given value is a vector value which will be legalized
4801 static bool WillBeConstantPoolLoad(SDNode *N) {
4802 if (N->getOpcode() != ISD::BUILD_VECTOR)
4805 // Check for any non-constant elements.
4806 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4807 switch (N->getOperand(i).getNode()->getOpcode()) {
4809 case ISD::ConstantFP:
4816 // Vectors of all-zeros and all-ones are materialized with special
4817 // instructions rather than being loaded.
4818 return !ISD::isBuildVectorAllZeros(N) &&
4819 !ISD::isBuildVectorAllOnes(N);
4822 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4823 /// match movlp{s|d}. The lower half elements should come from lower half of
4824 /// V1 (and in order), and the upper half elements should come from the upper
4825 /// half of V2 (and in order). And since V1 will become the source of the
4826 /// MOVLP, it must be either a vector load or a scalar load to vector.
4827 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4828 ArrayRef<int> Mask, MVT VT) {
4829 if (!VT.is128BitVector())
4832 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4834 // Is V2 is a vector load, don't do this transformation. We will try to use
4835 // load folding shufps op.
4836 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4839 unsigned NumElems = VT.getVectorNumElements();
4841 if (NumElems != 2 && NumElems != 4)
4843 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4844 if (!isUndefOrEqual(Mask[i], i))
4846 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4847 if (!isUndefOrEqual(Mask[i], i+NumElems))
4852 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4854 static bool isSplatVector(SDNode *N) {
4855 if (N->getOpcode() != ISD::BUILD_VECTOR)
4858 SDValue SplatValue = N->getOperand(0);
4859 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4860 if (N->getOperand(i) != SplatValue)
4865 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4866 /// to an zero vector.
4867 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4868 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4869 SDValue V1 = N->getOperand(0);
4870 SDValue V2 = N->getOperand(1);
4871 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4872 for (unsigned i = 0; i != NumElems; ++i) {
4873 int Idx = N->getMaskElt(i);
4874 if (Idx >= (int)NumElems) {
4875 unsigned Opc = V2.getOpcode();
4876 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4878 if (Opc != ISD::BUILD_VECTOR ||
4879 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4881 } else if (Idx >= 0) {
4882 unsigned Opc = V1.getOpcode();
4883 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4885 if (Opc != ISD::BUILD_VECTOR ||
4886 !X86::isZeroNode(V1.getOperand(Idx)))
4893 /// getZeroVector - Returns a vector of specified type with all zero elements.
4895 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4896 SelectionDAG &DAG, SDLoc dl) {
4897 assert(VT.isVector() && "Expected a vector type");
4899 // Always build SSE zero vectors as <4 x i32> bitcasted
4900 // to their dest type. This ensures they get CSE'd.
4902 if (VT.is128BitVector()) { // SSE
4903 if (Subtarget->hasSSE2()) { // SSE2
4904 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4905 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4907 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4908 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4910 } else if (VT.is256BitVector()) { // AVX
4911 if (Subtarget->hasInt256()) { // AVX2
4912 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4913 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4916 // 256-bit logic and arithmetic instructions in AVX are all
4917 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4918 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4919 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4922 } else if (VT.is512BitVector()) { // AVX-512
4923 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4924 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4925 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4926 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4927 } else if (VT.getScalarType() == MVT::i1) {
4928 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4929 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4930 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4931 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4933 llvm_unreachable("Unexpected vector type");
4935 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4938 /// getOnesVector - Returns a vector of specified type with all bits set.
4939 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4940 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4941 /// Then bitcast to their original type, ensuring they get CSE'd.
4942 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4944 assert(VT.isVector() && "Expected a vector type");
4946 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4948 if (VT.is256BitVector()) {
4949 if (HasInt256) { // AVX2
4950 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4951 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4953 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4954 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4956 } else if (VT.is128BitVector()) {
4957 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4959 llvm_unreachable("Unexpected vector type");
4961 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4964 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4965 /// that point to V2 points to its first element.
4966 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4967 for (unsigned i = 0; i != NumElems; ++i) {
4968 if (Mask[i] > (int)NumElems) {
4974 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4975 /// operation of specified width.
4976 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4978 unsigned NumElems = VT.getVectorNumElements();
4979 SmallVector<int, 8> Mask;
4980 Mask.push_back(NumElems);
4981 for (unsigned i = 1; i != NumElems; ++i)
4983 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4986 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4987 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4989 unsigned NumElems = VT.getVectorNumElements();
4990 SmallVector<int, 8> Mask;
4991 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4993 Mask.push_back(i + NumElems);
4995 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4998 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4999 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5001 unsigned NumElems = VT.getVectorNumElements();
5002 SmallVector<int, 8> Mask;
5003 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5004 Mask.push_back(i + Half);
5005 Mask.push_back(i + NumElems + Half);
5007 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5010 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5011 // a generic shuffle instruction because the target has no such instructions.
5012 // Generate shuffles which repeat i16 and i8 several times until they can be
5013 // represented by v4f32 and then be manipulated by target suported shuffles.
5014 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5015 MVT VT = V.getSimpleValueType();
5016 int NumElems = VT.getVectorNumElements();
5019 while (NumElems > 4) {
5020 if (EltNo < NumElems/2) {
5021 V = getUnpackl(DAG, dl, VT, V, V);
5023 V = getUnpackh(DAG, dl, VT, V, V);
5024 EltNo -= NumElems/2;
5031 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5032 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5033 MVT VT = V.getSimpleValueType();
5036 if (VT.is128BitVector()) {
5037 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5038 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5039 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5041 } else if (VT.is256BitVector()) {
5042 // To use VPERMILPS to splat scalars, the second half of indicies must
5043 // refer to the higher part, which is a duplication of the lower one,
5044 // because VPERMILPS can only handle in-lane permutations.
5045 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5046 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5048 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5049 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5052 llvm_unreachable("Vector size not supported");
5054 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5057 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5058 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5059 MVT SrcVT = SV->getSimpleValueType(0);
5060 SDValue V1 = SV->getOperand(0);
5063 int EltNo = SV->getSplatIndex();
5064 int NumElems = SrcVT.getVectorNumElements();
5065 bool Is256BitVec = SrcVT.is256BitVector();
5067 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5068 "Unknown how to promote splat for type");
5070 // Extract the 128-bit part containing the splat element and update
5071 // the splat element index when it refers to the higher register.
5073 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5074 if (EltNo >= NumElems/2)
5075 EltNo -= NumElems/2;
5078 // All i16 and i8 vector types can't be used directly by a generic shuffle
5079 // instruction because the target has no such instruction. Generate shuffles
5080 // which repeat i16 and i8 several times until they fit in i32, and then can
5081 // be manipulated by target suported shuffles.
5082 MVT EltVT = SrcVT.getVectorElementType();
5083 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5084 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5086 // Recreate the 256-bit vector and place the same 128-bit vector
5087 // into the low and high part. This is necessary because we want
5088 // to use VPERM* to shuffle the vectors
5090 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5093 return getLegalSplat(DAG, V1, EltNo);
5096 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5097 /// vector of zero or undef vector. This produces a shuffle where the low
5098 /// element of V2 is swizzled into the zero/undef vector, landing at element
5099 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5100 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5102 const X86Subtarget *Subtarget,
5103 SelectionDAG &DAG) {
5104 MVT VT = V2.getSimpleValueType();
5106 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5107 unsigned NumElems = VT.getVectorNumElements();
5108 SmallVector<int, 16> MaskVec;
5109 for (unsigned i = 0; i != NumElems; ++i)
5110 // If this is the insertion idx, put the low elt of V2 here.
5111 MaskVec.push_back(i == Idx ? NumElems : i);
5112 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5115 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5116 /// target specific opcode. Returns true if the Mask could be calculated.
5117 /// Sets IsUnary to true if only uses one source.
5118 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5119 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5120 unsigned NumElems = VT.getVectorNumElements();
5124 switch(N->getOpcode()) {
5126 ImmN = N->getOperand(N->getNumOperands()-1);
5127 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5129 case X86ISD::UNPCKH:
5130 DecodeUNPCKHMask(VT, Mask);
5132 case X86ISD::UNPCKL:
5133 DecodeUNPCKLMask(VT, Mask);
5135 case X86ISD::MOVHLPS:
5136 DecodeMOVHLPSMask(NumElems, Mask);
5138 case X86ISD::MOVLHPS:
5139 DecodeMOVLHPSMask(NumElems, Mask);
5141 case X86ISD::PALIGNR:
5142 ImmN = N->getOperand(N->getNumOperands()-1);
5143 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145 case X86ISD::PSHUFD:
5146 case X86ISD::VPERMILP:
5147 ImmN = N->getOperand(N->getNumOperands()-1);
5148 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5151 case X86ISD::PSHUFHW:
5152 ImmN = N->getOperand(N->getNumOperands()-1);
5153 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5156 case X86ISD::PSHUFLW:
5157 ImmN = N->getOperand(N->getNumOperands()-1);
5158 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5161 case X86ISD::VPERMI:
5162 ImmN = N->getOperand(N->getNumOperands()-1);
5163 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5167 case X86ISD::MOVSD: {
5168 // The index 0 always comes from the first element of the second source,
5169 // this is why MOVSS and MOVSD are used in the first place. The other
5170 // elements come from the other positions of the first source vector
5171 Mask.push_back(NumElems);
5172 for (unsigned i = 1; i != NumElems; ++i) {
5177 case X86ISD::VPERM2X128:
5178 ImmN = N->getOperand(N->getNumOperands()-1);
5179 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180 if (Mask.empty()) return false;
5182 case X86ISD::MOVDDUP:
5183 case X86ISD::MOVLHPD:
5184 case X86ISD::MOVLPD:
5185 case X86ISD::MOVLPS:
5186 case X86ISD::MOVSHDUP:
5187 case X86ISD::MOVSLDUP:
5188 // Not yet implemented
5190 default: llvm_unreachable("unknown target shuffle node");
5196 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5197 /// element of the result of the vector shuffle.
5198 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5201 return SDValue(); // Limit search depth.
5203 SDValue V = SDValue(N, 0);
5204 EVT VT = V.getValueType();
5205 unsigned Opcode = V.getOpcode();
5207 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5208 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5209 int Elt = SV->getMaskElt(Index);
5212 return DAG.getUNDEF(VT.getVectorElementType());
5214 unsigned NumElems = VT.getVectorNumElements();
5215 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5216 : SV->getOperand(1);
5217 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5220 // Recurse into target specific vector shuffles to find scalars.
5221 if (isTargetShuffle(Opcode)) {
5222 MVT ShufVT = V.getSimpleValueType();
5223 unsigned NumElems = ShufVT.getVectorNumElements();
5224 SmallVector<int, 16> ShuffleMask;
5227 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5230 int Elt = ShuffleMask[Index];
5232 return DAG.getUNDEF(ShufVT.getVectorElementType());
5234 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5236 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5240 // Actual nodes that may contain scalar elements
5241 if (Opcode == ISD::BITCAST) {
5242 V = V.getOperand(0);
5243 EVT SrcVT = V.getValueType();
5244 unsigned NumElems = VT.getVectorNumElements();
5246 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5250 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5251 return (Index == 0) ? V.getOperand(0)
5252 : DAG.getUNDEF(VT.getVectorElementType());
5254 if (V.getOpcode() == ISD::BUILD_VECTOR)
5255 return V.getOperand(Index);
5260 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5261 /// shuffle operation which come from a consecutively from a zero. The
5262 /// search can start in two different directions, from left or right.
5263 /// We count undefs as zeros until PreferredNum is reached.
5264 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5265 unsigned NumElems, bool ZerosFromLeft,
5267 unsigned PreferredNum = -1U) {
5268 unsigned NumZeros = 0;
5269 for (unsigned i = 0; i != NumElems; ++i) {
5270 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5271 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5275 if (X86::isZeroNode(Elt))
5277 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5278 NumZeros = std::min(NumZeros + 1, PreferredNum);
5286 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5287 /// correspond consecutively to elements from one of the vector operands,
5288 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5290 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5291 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5292 unsigned NumElems, unsigned &OpNum) {
5293 bool SeenV1 = false;
5294 bool SeenV2 = false;
5296 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5297 int Idx = SVOp->getMaskElt(i);
5298 // Ignore undef indicies
5302 if (Idx < (int)NumElems)
5307 // Only accept consecutive elements from the same vector
5308 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5312 OpNum = SeenV1 ? 0 : 1;
5316 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5317 /// logical left shift of a vector.
5318 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5319 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5321 SVOp->getSimpleValueType(0).getVectorNumElements();
5322 unsigned NumZeros = getNumOfConsecutiveZeros(
5323 SVOp, NumElems, false /* check zeros from right */, DAG,
5324 SVOp->getMaskElt(0));
5330 // Considering the elements in the mask that are not consecutive zeros,
5331 // check if they consecutively come from only one of the source vectors.
5333 // V1 = {X, A, B, C} 0
5335 // vector_shuffle V1, V2 <1, 2, 3, X>
5337 if (!isShuffleMaskConsecutive(SVOp,
5338 0, // Mask Start Index
5339 NumElems-NumZeros, // Mask End Index(exclusive)
5340 NumZeros, // Where to start looking in the src vector
5341 NumElems, // Number of elements in vector
5342 OpSrc)) // Which source operand ?
5347 ShVal = SVOp->getOperand(OpSrc);
5351 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5352 /// logical left shift of a vector.
5353 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5354 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5356 SVOp->getSimpleValueType(0).getVectorNumElements();
5357 unsigned NumZeros = getNumOfConsecutiveZeros(
5358 SVOp, NumElems, true /* check zeros from left */, DAG,
5359 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5365 // Considering the elements in the mask that are not consecutive zeros,
5366 // check if they consecutively come from only one of the source vectors.
5368 // 0 { A, B, X, X } = V2
5370 // vector_shuffle V1, V2 <X, X, 4, 5>
5372 if (!isShuffleMaskConsecutive(SVOp,
5373 NumZeros, // Mask Start Index
5374 NumElems, // Mask End Index(exclusive)
5375 0, // Where to start looking in the src vector
5376 NumElems, // Number of elements in vector
5377 OpSrc)) // Which source operand ?
5382 ShVal = SVOp->getOperand(OpSrc);
5386 /// isVectorShift - Returns true if the shuffle can be implemented as a
5387 /// logical left or right shift of a vector.
5388 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5389 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5390 // Although the logic below support any bitwidth size, there are no
5391 // shift instructions which handle more than 128-bit vectors.
5392 if (!SVOp->getSimpleValueType(0).is128BitVector())
5395 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5396 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5402 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5404 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5405 unsigned NumNonZero, unsigned NumZero,
5407 const X86Subtarget* Subtarget,
5408 const TargetLowering &TLI) {
5415 for (unsigned i = 0; i < 16; ++i) {
5416 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5417 if (ThisIsNonZero && First) {
5419 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5421 V = DAG.getUNDEF(MVT::v8i16);
5426 SDValue ThisElt, LastElt;
5427 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5428 if (LastIsNonZero) {
5429 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5430 MVT::i16, Op.getOperand(i-1));
5432 if (ThisIsNonZero) {
5433 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5434 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5435 ThisElt, DAG.getConstant(8, MVT::i8));
5437 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5441 if (ThisElt.getNode())
5442 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5443 DAG.getIntPtrConstant(i/2));
5447 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5450 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5452 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5453 unsigned NumNonZero, unsigned NumZero,
5455 const X86Subtarget* Subtarget,
5456 const TargetLowering &TLI) {
5463 for (unsigned i = 0; i < 8; ++i) {
5464 bool isNonZero = (NonZeros & (1 << i)) != 0;
5468 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5470 V = DAG.getUNDEF(MVT::v8i16);
5473 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5474 MVT::v8i16, V, Op.getOperand(i),
5475 DAG.getIntPtrConstant(i));
5482 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5483 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5484 unsigned NonZeros, unsigned NumNonZero,
5485 unsigned NumZero, SelectionDAG &DAG,
5486 const X86Subtarget *Subtarget,
5487 const TargetLowering &TLI) {
5488 // We know there's at least one non-zero element
5489 unsigned FirstNonZeroIdx = 0;
5490 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5492 X86::isZeroNode(FirstNonZero)) {
5494 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5497 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5498 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5501 SDValue V = FirstNonZero.getOperand(0);
5502 MVT VVT = V.getSimpleValueType();
5503 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5506 unsigned FirstNonZeroDst =
5507 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5508 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5509 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5510 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5512 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5513 SDValue Elem = Op.getOperand(Idx);
5514 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5517 // TODO: What else can be here? Deal with it.
5518 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5521 // TODO: Some optimizations are still possible here
5522 // ex: Getting one element from a vector, and the rest from another.
5523 if (Elem.getOperand(0) != V)
5526 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5529 else if (IncorrectIdx == -1U) {
5533 // There was already one element with an incorrect index.
5534 // We can't optimize this case to an insertps.
5538 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5540 EVT VT = Op.getSimpleValueType();
5541 unsigned ElementMoveMask = 0;
5542 if (IncorrectIdx == -1U)
5543 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5545 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5547 SDValue InsertpsMask =
5548 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5549 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5555 /// getVShift - Return a vector logical shift node.
5557 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5558 unsigned NumBits, SelectionDAG &DAG,
5559 const TargetLowering &TLI, SDLoc dl) {
5560 assert(VT.is128BitVector() && "Unknown type for VShift");
5561 EVT ShVT = MVT::v2i64;
5562 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5563 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5564 return DAG.getNode(ISD::BITCAST, dl, VT,
5565 DAG.getNode(Opc, dl, ShVT, SrcOp,
5566 DAG.getConstant(NumBits,
5567 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5571 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5573 // Check if the scalar load can be widened into a vector load. And if
5574 // the address is "base + cst" see if the cst can be "absorbed" into
5575 // the shuffle mask.
5576 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5577 SDValue Ptr = LD->getBasePtr();
5578 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5580 EVT PVT = LD->getValueType(0);
5581 if (PVT != MVT::i32 && PVT != MVT::f32)
5586 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5587 FI = FINode->getIndex();
5589 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5590 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5591 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5592 Offset = Ptr.getConstantOperandVal(1);
5593 Ptr = Ptr.getOperand(0);
5598 // FIXME: 256-bit vector instructions don't require a strict alignment,
5599 // improve this code to support it better.
5600 unsigned RequiredAlign = VT.getSizeInBits()/8;
5601 SDValue Chain = LD->getChain();
5602 // Make sure the stack object alignment is at least 16 or 32.
5603 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5604 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5605 if (MFI->isFixedObjectIndex(FI)) {
5606 // Can't change the alignment. FIXME: It's possible to compute
5607 // the exact stack offset and reference FI + adjust offset instead.
5608 // If someone *really* cares about this. That's the way to implement it.
5611 MFI->setObjectAlignment(FI, RequiredAlign);
5615 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5616 // Ptr + (Offset & ~15).
5619 if ((Offset % RequiredAlign) & 3)
5621 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5623 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5624 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5626 int EltNo = (Offset - StartOffset) >> 2;
5627 unsigned NumElems = VT.getVectorNumElements();
5629 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5630 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5631 LD->getPointerInfo().getWithOffset(StartOffset),
5632 false, false, false, 0);
5634 SmallVector<int, 8> Mask;
5635 for (unsigned i = 0; i != NumElems; ++i)
5636 Mask.push_back(EltNo);
5638 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5644 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5645 /// vector of type 'VT', see if the elements can be replaced by a single large
5646 /// load which has the same value as a build_vector whose operands are 'elts'.
5648 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5650 /// FIXME: we'd also like to handle the case where the last elements are zero
5651 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5652 /// There's even a handy isZeroNode for that purpose.
5653 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5654 SDLoc &DL, SelectionDAG &DAG,
5655 bool isAfterLegalize) {
5656 EVT EltVT = VT.getVectorElementType();
5657 unsigned NumElems = Elts.size();
5659 LoadSDNode *LDBase = nullptr;
5660 unsigned LastLoadedElt = -1U;
5662 // For each element in the initializer, see if we've found a load or an undef.
5663 // If we don't find an initial load element, or later load elements are
5664 // non-consecutive, bail out.
5665 for (unsigned i = 0; i < NumElems; ++i) {
5666 SDValue Elt = Elts[i];
5668 if (!Elt.getNode() ||
5669 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5672 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5674 LDBase = cast<LoadSDNode>(Elt.getNode());
5678 if (Elt.getOpcode() == ISD::UNDEF)
5681 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5682 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5687 // If we have found an entire vector of loads and undefs, then return a large
5688 // load of the entire vector width starting at the base pointer. If we found
5689 // consecutive loads for the low half, generate a vzext_load node.
5690 if (LastLoadedElt == NumElems - 1) {
5692 if (isAfterLegalize &&
5693 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5696 SDValue NewLd = SDValue();
5698 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5699 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5700 LDBase->getPointerInfo(),
5701 LDBase->isVolatile(), LDBase->isNonTemporal(),
5702 LDBase->isInvariant(), 0);
5703 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5704 LDBase->getPointerInfo(),
5705 LDBase->isVolatile(), LDBase->isNonTemporal(),
5706 LDBase->isInvariant(), LDBase->getAlignment());
5708 if (LDBase->hasAnyUseOfValue(1)) {
5709 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5711 SDValue(NewLd.getNode(), 1));
5712 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5713 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5714 SDValue(NewLd.getNode(), 1));
5719 if (NumElems == 4 && LastLoadedElt == 1 &&
5720 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5721 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5722 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5724 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5725 LDBase->getPointerInfo(),
5726 LDBase->getAlignment(),
5727 false/*isVolatile*/, true/*ReadMem*/,
5730 // Make sure the newly-created LOAD is in the same position as LDBase in
5731 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5732 // update uses of LDBase's output chain to use the TokenFactor.
5733 if (LDBase->hasAnyUseOfValue(1)) {
5734 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5735 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5736 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5737 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5738 SDValue(ResNode.getNode(), 1));
5741 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5746 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5747 /// to generate a splat value for the following cases:
5748 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5749 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5750 /// a scalar load, or a constant.
5751 /// The VBROADCAST node is returned when a pattern is found,
5752 /// or SDValue() otherwise.
5753 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5754 SelectionDAG &DAG) {
5755 if (!Subtarget->hasFp256())
5758 MVT VT = Op.getSimpleValueType();
5761 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5762 "Unsupported vector type for broadcast.");
5767 switch (Op.getOpcode()) {
5769 // Unknown pattern found.
5772 case ISD::BUILD_VECTOR: {
5773 // The BUILD_VECTOR node must be a splat.
5774 if (!isSplatVector(Op.getNode()))
5777 Ld = Op.getOperand(0);
5778 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5779 Ld.getOpcode() == ISD::ConstantFP);
5781 // The suspected load node has several users. Make sure that all
5782 // of its users are from the BUILD_VECTOR node.
5783 // Constants may have multiple users.
5784 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5789 case ISD::VECTOR_SHUFFLE: {
5790 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5792 // Shuffles must have a splat mask where the first element is
5794 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5797 SDValue Sc = Op.getOperand(0);
5798 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5799 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5801 if (!Subtarget->hasInt256())
5804 // Use the register form of the broadcast instruction available on AVX2.
5805 if (VT.getSizeInBits() >= 256)
5806 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5807 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5810 Ld = Sc.getOperand(0);
5811 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5812 Ld.getOpcode() == ISD::ConstantFP);
5814 // The scalar_to_vector node and the suspected
5815 // load node must have exactly one user.
5816 // Constants may have multiple users.
5818 // AVX-512 has register version of the broadcast
5819 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5820 Ld.getValueType().getSizeInBits() >= 32;
5821 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5828 bool IsGE256 = (VT.getSizeInBits() >= 256);
5830 // Handle the broadcasting a single constant scalar from the constant pool
5831 // into a vector. On Sandybridge it is still better to load a constant vector
5832 // from the constant pool and not to broadcast it from a scalar.
5833 if (ConstSplatVal && Subtarget->hasInt256()) {
5834 EVT CVT = Ld.getValueType();
5835 assert(!CVT.isVector() && "Must not broadcast a vector type");
5836 unsigned ScalarSize = CVT.getSizeInBits();
5838 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5839 const Constant *C = nullptr;
5840 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5841 C = CI->getConstantIntValue();
5842 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5843 C = CF->getConstantFPValue();
5845 assert(C && "Invalid constant type");
5847 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5848 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5849 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5850 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5851 MachinePointerInfo::getConstantPool(),
5852 false, false, false, Alignment);
5854 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5858 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5859 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5861 // Handle AVX2 in-register broadcasts.
5862 if (!IsLoad && Subtarget->hasInt256() &&
5863 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5864 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5866 // The scalar source must be a normal load.
5870 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5871 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5873 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5874 // double since there is no vbroadcastsd xmm
5875 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5876 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5877 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5880 // Unsupported broadcast.
5884 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5885 /// underlying vector and index.
5887 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5889 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5891 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5892 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5895 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5897 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5899 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5900 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5903 // In this case the vector is the extract_subvector expression and the index
5904 // is 2, as specified by the shuffle.
5905 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5906 SDValue ShuffleVec = SVOp->getOperand(0);
5907 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5908 assert(ShuffleVecVT.getVectorElementType() ==
5909 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5911 int ShuffleIdx = SVOp->getMaskElt(Idx);
5912 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5913 ExtractedFromVec = ShuffleVec;
5919 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5920 MVT VT = Op.getSimpleValueType();
5922 // Skip if insert_vec_elt is not supported.
5923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5924 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5928 unsigned NumElems = Op.getNumOperands();
5932 SmallVector<unsigned, 4> InsertIndices;
5933 SmallVector<int, 8> Mask(NumElems, -1);
5935 for (unsigned i = 0; i != NumElems; ++i) {
5936 unsigned Opc = Op.getOperand(i).getOpcode();
5938 if (Opc == ISD::UNDEF)
5941 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5942 // Quit if more than 1 elements need inserting.
5943 if (InsertIndices.size() > 1)
5946 InsertIndices.push_back(i);
5950 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5951 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5952 // Quit if non-constant index.
5953 if (!isa<ConstantSDNode>(ExtIdx))
5955 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5957 // Quit if extracted from vector of different type.
5958 if (ExtractedFromVec.getValueType() != VT)
5961 if (!VecIn1.getNode())
5962 VecIn1 = ExtractedFromVec;
5963 else if (VecIn1 != ExtractedFromVec) {
5964 if (!VecIn2.getNode())
5965 VecIn2 = ExtractedFromVec;
5966 else if (VecIn2 != ExtractedFromVec)
5967 // Quit if more than 2 vectors to shuffle
5971 if (ExtractedFromVec == VecIn1)
5973 else if (ExtractedFromVec == VecIn2)
5974 Mask[i] = Idx + NumElems;
5977 if (!VecIn1.getNode())
5980 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5981 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5982 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5983 unsigned Idx = InsertIndices[i];
5984 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5985 DAG.getIntPtrConstant(Idx));
5991 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5993 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5995 MVT VT = Op.getSimpleValueType();
5996 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5997 "Unexpected type in LowerBUILD_VECTORvXi1!");
6000 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6001 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6002 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6006 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6007 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6008 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6009 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6012 bool AllContants = true;
6013 uint64_t Immediate = 0;
6014 int NonConstIdx = -1;
6015 bool IsSplat = true;
6016 unsigned NumNonConsts = 0;
6017 unsigned NumConsts = 0;
6018 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6019 SDValue In = Op.getOperand(idx);
6020 if (In.getOpcode() == ISD::UNDEF)
6022 if (!isa<ConstantSDNode>(In)) {
6023 AllContants = false;
6029 if (cast<ConstantSDNode>(In)->getZExtValue())
6030 Immediate |= (1ULL << idx);
6032 if (In != Op.getOperand(0))
6037 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6038 DAG.getConstant(Immediate, MVT::i16));
6039 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6040 DAG.getIntPtrConstant(0));
6043 if (NumNonConsts == 1 && NonConstIdx != 0) {
6046 SDValue VecAsImm = DAG.getConstant(Immediate,
6047 MVT::getIntegerVT(VT.getSizeInBits()));
6048 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6051 DstVec = DAG.getUNDEF(VT);
6052 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6053 Op.getOperand(NonConstIdx),
6054 DAG.getIntPtrConstant(NonConstIdx));
6056 if (!IsSplat && (NonConstIdx != 0))
6057 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6058 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6061 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6062 DAG.getConstant(-1, SelectVT),
6063 DAG.getConstant(0, SelectVT));
6065 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6066 DAG.getConstant((Immediate | 1), SelectVT),
6067 DAG.getConstant(Immediate, SelectVT));
6068 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6071 /// \brief Return true if \p N implements a horizontal binop and return the
6072 /// operands for the horizontal binop into V0 and V1.
6074 /// This is a helper function of PerformBUILD_VECTORCombine.
6075 /// This function checks that the build_vector \p N in input implements a
6076 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6077 /// operation to match.
6078 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6079 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6080 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6083 /// This function only analyzes elements of \p N whose indices are
6084 /// in range [BaseIdx, LastIdx).
6085 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6087 unsigned BaseIdx, unsigned LastIdx,
6088 SDValue &V0, SDValue &V1) {
6089 EVT VT = N->getValueType(0);
6091 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6092 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6093 "Invalid Vector in input!");
6095 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6096 bool CanFold = true;
6097 unsigned ExpectedVExtractIdx = BaseIdx;
6098 unsigned NumElts = LastIdx - BaseIdx;
6099 V0 = DAG.getUNDEF(VT);
6100 V1 = DAG.getUNDEF(VT);
6102 // Check if N implements a horizontal binop.
6103 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6104 SDValue Op = N->getOperand(i + BaseIdx);
6107 if (Op->getOpcode() == ISD::UNDEF) {
6108 // Update the expected vector extract index.
6109 if (i * 2 == NumElts)
6110 ExpectedVExtractIdx = BaseIdx;
6111 ExpectedVExtractIdx += 2;
6115 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6120 SDValue Op0 = Op.getOperand(0);
6121 SDValue Op1 = Op.getOperand(1);
6123 // Try to match the following pattern:
6124 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6125 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6126 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6127 Op0.getOperand(0) == Op1.getOperand(0) &&
6128 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6129 isa<ConstantSDNode>(Op1.getOperand(1)));
6133 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6134 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6136 if (i * 2 < NumElts) {
6137 if (V0.getOpcode() == ISD::UNDEF)
6138 V0 = Op0.getOperand(0);
6140 if (V1.getOpcode() == ISD::UNDEF)
6141 V1 = Op0.getOperand(0);
6142 if (i * 2 == NumElts)
6143 ExpectedVExtractIdx = BaseIdx;
6146 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6147 if (I0 == ExpectedVExtractIdx)
6148 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6149 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6150 // Try to match the following dag sequence:
6151 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6152 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6156 ExpectedVExtractIdx += 2;
6162 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6163 /// a concat_vector.
6165 /// This is a helper function of PerformBUILD_VECTORCombine.
6166 /// This function expects two 256-bit vectors called V0 and V1.
6167 /// At first, each vector is split into two separate 128-bit vectors.
6168 /// Then, the resulting 128-bit vectors are used to implement two
6169 /// horizontal binary operations.
6171 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6173 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6174 /// the two new horizontal binop.
6175 /// When Mode is set, the first horizontal binop dag node would take as input
6176 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6177 /// horizontal binop dag node would take as input the lower 128-bit of V1
6178 /// and the upper 128-bit of V1.
6180 /// HADD V0_LO, V0_HI
6181 /// HADD V1_LO, V1_HI
6183 /// Otherwise, the first horizontal binop dag node takes as input the lower
6184 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6185 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6187 /// HADD V0_LO, V1_LO
6188 /// HADD V0_HI, V1_HI
6190 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6191 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6192 /// the upper 128-bits of the result.
6193 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6194 SDLoc DL, SelectionDAG &DAG,
6195 unsigned X86Opcode, bool Mode,
6196 bool isUndefLO, bool isUndefHI) {
6197 EVT VT = V0.getValueType();
6198 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6199 "Invalid nodes in input!");
6201 unsigned NumElts = VT.getVectorNumElements();
6202 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6203 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6204 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6205 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6206 EVT NewVT = V0_LO.getValueType();
6208 SDValue LO = DAG.getUNDEF(NewVT);
6209 SDValue HI = DAG.getUNDEF(NewVT);
6212 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6214 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6215 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6216 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6218 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6219 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6220 V1_LO->getOpcode() != ISD::UNDEF))
6221 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6223 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6224 V1_HI->getOpcode() != ISD::UNDEF))
6225 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6228 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6231 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6232 /// sequence of 'vadd + vsub + blendi'.
6233 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6234 const X86Subtarget *Subtarget) {
6236 EVT VT = BV->getValueType(0);
6237 unsigned NumElts = VT.getVectorNumElements();
6238 SDValue InVec0 = DAG.getUNDEF(VT);
6239 SDValue InVec1 = DAG.getUNDEF(VT);
6241 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6242 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6244 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6245 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6246 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6249 // Odd-numbered elements in the input build vector are obtained from
6250 // adding two integer/float elements.
6251 // Even-numbered elements in the input build vector are obtained from
6252 // subtracting two integer/float elements.
6253 unsigned ExpectedOpcode = ISD::FSUB;
6254 unsigned NextExpectedOpcode = ISD::FADD;
6255 bool AddFound = false;
6256 bool SubFound = false;
6258 for (unsigned i = 0, e = NumElts; i != e; i++) {
6259 SDValue Op = BV->getOperand(i);
6261 // Skip 'undef' values.
6262 unsigned Opcode = Op.getOpcode();
6263 if (Opcode == ISD::UNDEF) {
6264 std::swap(ExpectedOpcode, NextExpectedOpcode);
6268 // Early exit if we found an unexpected opcode.
6269 if (Opcode != ExpectedOpcode)
6272 SDValue Op0 = Op.getOperand(0);
6273 SDValue Op1 = Op.getOperand(1);
6275 // Try to match the following pattern:
6276 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6277 // Early exit if we cannot match that sequence.
6278 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6279 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6280 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6281 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6282 Op0.getOperand(1) != Op1.getOperand(1))
6285 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6289 // We found a valid add/sub node. Update the information accordingly.
6295 // Update InVec0 and InVec1.
6296 if (InVec0.getOpcode() == ISD::UNDEF)
6297 InVec0 = Op0.getOperand(0);
6298 if (InVec1.getOpcode() == ISD::UNDEF)
6299 InVec1 = Op1.getOperand(0);
6301 // Make sure that operands in input to each add/sub node always
6302 // come from a same pair of vectors.
6303 if (InVec0 != Op0.getOperand(0)) {
6304 if (ExpectedOpcode == ISD::FSUB)
6307 // FADD is commutable. Try to commute the operands
6308 // and then test again.
6309 std::swap(Op0, Op1);
6310 if (InVec0 != Op0.getOperand(0))
6314 if (InVec1 != Op1.getOperand(0))
6317 // Update the pair of expected opcodes.
6318 std::swap(ExpectedOpcode, NextExpectedOpcode);
6321 // Don't try to fold this build_vector into a VSELECT if it has
6322 // too many UNDEF operands.
6323 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6324 InVec1.getOpcode() != ISD::UNDEF) {
6325 // Emit a sequence of vector add and sub followed by a VSELECT.
6326 // The new VSELECT will be lowered into a BLENDI.
6327 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6328 // and emit a single ADDSUB instruction.
6329 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6330 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6332 // Construct the VSELECT mask.
6333 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6334 EVT SVT = MaskVT.getVectorElementType();
6335 unsigned SVTBits = SVT.getSizeInBits();
6336 SmallVector<SDValue, 8> Ops;
6338 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6339 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6340 APInt::getAllOnesValue(SVTBits);
6341 SDValue Constant = DAG.getConstant(Value, SVT);
6342 Ops.push_back(Constant);
6345 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6346 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6353 const X86Subtarget *Subtarget) {
6355 EVT VT = N->getValueType(0);
6356 unsigned NumElts = VT.getVectorNumElements();
6357 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6358 SDValue InVec0, InVec1;
6360 // Try to match an ADDSUB.
6361 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6362 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6363 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6364 if (Value.getNode())
6368 // Try to match horizontal ADD/SUB.
6369 unsigned NumUndefsLO = 0;
6370 unsigned NumUndefsHI = 0;
6371 unsigned Half = NumElts/2;
6373 // Count the number of UNDEF operands in the build_vector in input.
6374 for (unsigned i = 0, e = Half; i != e; ++i)
6375 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6378 for (unsigned i = Half, e = NumElts; i != e; ++i)
6379 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6382 // Early exit if this is either a build_vector of all UNDEFs or all the
6383 // operands but one are UNDEF.
6384 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6387 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6388 // Try to match an SSE3 float HADD/HSUB.
6389 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6390 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6392 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6393 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6394 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6395 // Try to match an SSSE3 integer HADD/HSUB.
6396 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6397 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6399 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6400 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6403 if (!Subtarget->hasAVX())
6406 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6407 // Try to match an AVX horizontal add/sub of packed single/double
6408 // precision floating point values from 256-bit vectors.
6409 SDValue InVec2, InVec3;
6410 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6411 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6412 ((InVec0.getOpcode() == ISD::UNDEF ||
6413 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6414 ((InVec1.getOpcode() == ISD::UNDEF ||
6415 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6416 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6418 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6419 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6420 ((InVec0.getOpcode() == ISD::UNDEF ||
6421 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6422 ((InVec1.getOpcode() == ISD::UNDEF ||
6423 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6424 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6425 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6426 // Try to match an AVX2 horizontal add/sub of signed integers.
6427 SDValue InVec2, InVec3;
6429 bool CanFold = true;
6431 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6432 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6433 ((InVec0.getOpcode() == ISD::UNDEF ||
6434 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6435 ((InVec1.getOpcode() == ISD::UNDEF ||
6436 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6437 X86Opcode = X86ISD::HADD;
6438 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6439 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6440 ((InVec0.getOpcode() == ISD::UNDEF ||
6441 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6442 ((InVec1.getOpcode() == ISD::UNDEF ||
6443 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6444 X86Opcode = X86ISD::HSUB;
6449 // Fold this build_vector into a single horizontal add/sub.
6450 // Do this only if the target has AVX2.
6451 if (Subtarget->hasAVX2())
6452 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6454 // Do not try to expand this build_vector into a pair of horizontal
6455 // add/sub if we can emit a pair of scalar add/sub.
6456 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6459 // Convert this build_vector into a pair of horizontal binop followed by
6461 bool isUndefLO = NumUndefsLO == Half;
6462 bool isUndefHI = NumUndefsHI == Half;
6463 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6464 isUndefLO, isUndefHI);
6468 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6469 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6471 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6472 X86Opcode = X86ISD::HADD;
6473 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6474 X86Opcode = X86ISD::HSUB;
6475 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6476 X86Opcode = X86ISD::FHADD;
6477 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6478 X86Opcode = X86ISD::FHSUB;
6482 // Don't try to expand this build_vector into a pair of horizontal add/sub
6483 // if we can simply emit a pair of scalar add/sub.
6484 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6487 // Convert this build_vector into two horizontal add/sub followed by
6489 bool isUndefLO = NumUndefsLO == Half;
6490 bool isUndefHI = NumUndefsHI == Half;
6491 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6492 isUndefLO, isUndefHI);
6499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6502 MVT VT = Op.getSimpleValueType();
6503 MVT ExtVT = VT.getVectorElementType();
6504 unsigned NumElems = Op.getNumOperands();
6506 // Generate vectors for predicate vectors.
6507 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6508 return LowerBUILD_VECTORvXi1(Op, DAG);
6510 // Vectors containing all zeros can be matched by pxor and xorps later
6511 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6512 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6513 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6514 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6517 return getZeroVector(VT, Subtarget, DAG, dl);
6520 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6521 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6522 // vpcmpeqd on 256-bit vectors.
6523 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6524 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6527 if (!VT.is512BitVector())
6528 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6531 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6532 if (Broadcast.getNode())
6535 unsigned EVTBits = ExtVT.getSizeInBits();
6537 unsigned NumZero = 0;
6538 unsigned NumNonZero = 0;
6539 unsigned NonZeros = 0;
6540 bool IsAllConstants = true;
6541 SmallSet<SDValue, 8> Values;
6542 for (unsigned i = 0; i < NumElems; ++i) {
6543 SDValue Elt = Op.getOperand(i);
6544 if (Elt.getOpcode() == ISD::UNDEF)
6547 if (Elt.getOpcode() != ISD::Constant &&
6548 Elt.getOpcode() != ISD::ConstantFP)
6549 IsAllConstants = false;
6550 if (X86::isZeroNode(Elt))
6553 NonZeros |= (1 << i);
6558 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6559 if (NumNonZero == 0)
6560 return DAG.getUNDEF(VT);
6562 // Special case for single non-zero, non-undef, element.
6563 if (NumNonZero == 1) {
6564 unsigned Idx = countTrailingZeros(NonZeros);
6565 SDValue Item = Op.getOperand(Idx);
6567 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6568 // the value are obviously zero, truncate the value to i32 and do the
6569 // insertion that way. Only do this if the value is non-constant or if the
6570 // value is a constant being inserted into element 0. It is cheaper to do
6571 // a constant pool load than it is to do a movd + shuffle.
6572 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6573 (!IsAllConstants || Idx == 0)) {
6574 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6576 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6577 EVT VecVT = MVT::v4i32;
6578 unsigned VecElts = 4;
6580 // Truncate the value (which may itself be a constant) to i32, and
6581 // convert it to a vector with movd (S2V+shuffle to zero extend).
6582 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6583 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6584 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6586 // Now we have our 32-bit value zero extended in the low element of
6587 // a vector. If Idx != 0, swizzle it into place.
6589 SmallVector<int, 4> Mask;
6590 Mask.push_back(Idx);
6591 for (unsigned i = 1; i != VecElts; ++i)
6593 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6596 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6600 // If we have a constant or non-constant insertion into the low element of
6601 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6602 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6603 // depending on what the source datatype is.
6606 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6608 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6609 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6610 if (VT.is256BitVector() || VT.is512BitVector()) {
6611 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6612 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6613 Item, DAG.getIntPtrConstant(0));
6615 assert(VT.is128BitVector() && "Expected an SSE value type!");
6616 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6617 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6618 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6621 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6622 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6623 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6624 if (VT.is256BitVector()) {
6625 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6626 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6628 assert(VT.is128BitVector() && "Expected an SSE value type!");
6629 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6631 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6635 // Is it a vector logical left shift?
6636 if (NumElems == 2 && Idx == 1 &&
6637 X86::isZeroNode(Op.getOperand(0)) &&
6638 !X86::isZeroNode(Op.getOperand(1))) {
6639 unsigned NumBits = VT.getSizeInBits();
6640 return getVShift(true, VT,
6641 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6642 VT, Op.getOperand(1)),
6643 NumBits/2, DAG, *this, dl);
6646 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6649 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6650 // is a non-constant being inserted into an element other than the low one,
6651 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6652 // movd/movss) to move this into the low element, then shuffle it into
6654 if (EVTBits == 32) {
6655 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6657 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6658 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6659 SmallVector<int, 8> MaskVec;
6660 for (unsigned i = 0; i != NumElems; ++i)
6661 MaskVec.push_back(i == Idx ? 0 : 1);
6662 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6666 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6667 if (Values.size() == 1) {
6668 if (EVTBits == 32) {
6669 // Instead of a shuffle like this:
6670 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6671 // Check if it's possible to issue this instead.
6672 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6673 unsigned Idx = countTrailingZeros(NonZeros);
6674 SDValue Item = Op.getOperand(Idx);
6675 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6676 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6681 // A vector full of immediates; various special cases are already
6682 // handled, so this is best done with a single constant-pool load.
6686 // For AVX-length vectors, build the individual 128-bit pieces and use
6687 // shuffles to put them in place.
6688 if (VT.is256BitVector() || VT.is512BitVector()) {
6689 SmallVector<SDValue, 64> V;
6690 for (unsigned i = 0; i != NumElems; ++i)
6691 V.push_back(Op.getOperand(i));
6693 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6695 // Build both the lower and upper subvector.
6696 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6697 makeArrayRef(&V[0], NumElems/2));
6698 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6699 makeArrayRef(&V[NumElems / 2], NumElems/2));
6701 // Recreate the wider vector with the lower and upper part.
6702 if (VT.is256BitVector())
6703 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6704 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6707 // Let legalizer expand 2-wide build_vectors.
6708 if (EVTBits == 64) {
6709 if (NumNonZero == 1) {
6710 // One half is zero or undef.
6711 unsigned Idx = countTrailingZeros(NonZeros);
6712 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6713 Op.getOperand(Idx));
6714 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6719 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6720 if (EVTBits == 8 && NumElems == 16) {
6721 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6723 if (V.getNode()) return V;
6726 if (EVTBits == 16 && NumElems == 8) {
6727 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6729 if (V.getNode()) return V;
6732 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6733 if (EVTBits == 32 && NumElems == 4) {
6734 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6735 NumZero, DAG, Subtarget, *this);
6740 // If element VT is == 32 bits, turn it into a number of shuffles.
6741 SmallVector<SDValue, 8> V(NumElems);
6742 if (NumElems == 4 && NumZero > 0) {
6743 for (unsigned i = 0; i < 4; ++i) {
6744 bool isZero = !(NonZeros & (1 << i));
6746 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6748 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6751 for (unsigned i = 0; i < 2; ++i) {
6752 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6755 V[i] = V[i*2]; // Must be a zero vector.
6758 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6761 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6764 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6769 bool Reverse1 = (NonZeros & 0x3) == 2;
6770 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6774 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6775 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6777 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6780 if (Values.size() > 1 && VT.is128BitVector()) {
6781 // Check for a build vector of consecutive loads.
6782 for (unsigned i = 0; i < NumElems; ++i)
6783 V[i] = Op.getOperand(i);
6785 // Check for elements which are consecutive loads.
6786 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6790 // Check for a build vector from mostly shuffle plus few inserting.
6791 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6795 // For SSE 4.1, use insertps to put the high elements into the low element.
6796 if (getSubtarget()->hasSSE41()) {
6798 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6799 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6801 Result = DAG.getUNDEF(VT);
6803 for (unsigned i = 1; i < NumElems; ++i) {
6804 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6805 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6806 Op.getOperand(i), DAG.getIntPtrConstant(i));
6811 // Otherwise, expand into a number of unpckl*, start by extending each of
6812 // our (non-undef) elements to the full vector width with the element in the
6813 // bottom slot of the vector (which generates no code for SSE).
6814 for (unsigned i = 0; i < NumElems; ++i) {
6815 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6816 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6818 V[i] = DAG.getUNDEF(VT);
6821 // Next, we iteratively mix elements, e.g. for v4f32:
6822 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6823 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6824 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6825 unsigned EltStride = NumElems >> 1;
6826 while (EltStride != 0) {
6827 for (unsigned i = 0; i < EltStride; ++i) {
6828 // If V[i+EltStride] is undef and this is the first round of mixing,
6829 // then it is safe to just drop this shuffle: V[i] is already in the
6830 // right place, the one element (since it's the first round) being
6831 // inserted as undef can be dropped. This isn't safe for successive
6832 // rounds because they will permute elements within both vectors.
6833 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6834 EltStride == NumElems/2)
6837 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6846 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6847 // to create 256-bit vectors from two other 128-bit ones.
6848 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6850 MVT ResVT = Op.getSimpleValueType();
6852 assert((ResVT.is256BitVector() ||
6853 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6855 SDValue V1 = Op.getOperand(0);
6856 SDValue V2 = Op.getOperand(1);
6857 unsigned NumElems = ResVT.getVectorNumElements();
6858 if(ResVT.is256BitVector())
6859 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6861 if (Op.getNumOperands() == 4) {
6862 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6863 ResVT.getVectorNumElements()/2);
6864 SDValue V3 = Op.getOperand(2);
6865 SDValue V4 = Op.getOperand(3);
6866 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6867 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6869 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6872 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6873 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6874 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6875 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6876 Op.getNumOperands() == 4)));
6878 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6879 // from two other 128-bit ones.
6881 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6882 return LowerAVXCONCAT_VECTORS(Op, DAG);
6886 //===----------------------------------------------------------------------===//
6887 // Vector shuffle lowering
6889 // This is an experimental code path for lowering vector shuffles on x86. It is
6890 // designed to handle arbitrary vector shuffles and blends, gracefully
6891 // degrading performance as necessary. It works hard to recognize idiomatic
6892 // shuffles and lower them to optimal instruction patterns without leaving
6893 // a framework that allows reasonably efficient handling of all vector shuffle
6895 //===----------------------------------------------------------------------===//
6897 /// \brief Tiny helper function to identify a no-op mask.
6899 /// This is a somewhat boring predicate function. It checks whether the mask
6900 /// array input, which is assumed to be a single-input shuffle mask of the kind
6901 /// used by the X86 shuffle instructions (not a fully general
6902 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6903 /// in-place shuffle are 'no-op's.
6904 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6905 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6906 if (Mask[i] != -1 && Mask[i] != i)
6911 /// \brief Helper function to classify a mask as a single-input mask.
6913 /// This isn't a generic single-input test because in the vector shuffle
6914 /// lowering we canonicalize single inputs to be the first input operand. This
6915 /// means we can more quickly test for a single input by only checking whether
6916 /// an input from the second operand exists. We also assume that the size of
6917 /// mask corresponds to the size of the input vectors which isn't true in the
6918 /// fully general case.
6919 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6921 if (M >= (int)Mask.size())
6926 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6928 /// This helper function produces an 8-bit shuffle immediate corresponding to
6929 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6930 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6933 /// NB: We rely heavily on "undef" masks preserving the input lane.
6934 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6935 SelectionDAG &DAG) {
6936 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6937 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6938 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6939 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6940 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6943 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6944 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6945 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6946 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6947 return DAG.getConstant(Imm, MVT::i8);
6950 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6952 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6953 /// support for floating point shuffles but not integer shuffles. These
6954 /// instructions will incur a domain crossing penalty on some chips though so
6955 /// it is better to avoid lowering through this for integer vectors where
6957 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6958 const X86Subtarget *Subtarget,
6959 SelectionDAG &DAG) {
6961 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6962 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6963 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6964 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6965 ArrayRef<int> Mask = SVOp->getMask();
6966 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6968 if (isSingleInputShuffleMask(Mask)) {
6969 // Straight shuffle of a single input vector. Simulate this by using the
6970 // single input as both of the "inputs" to this instruction..
6971 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6972 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6973 DAG.getConstant(SHUFPDMask, MVT::i8));
6975 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6976 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6978 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6979 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6980 DAG.getConstant(SHUFPDMask, MVT::i8));
6983 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6985 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6986 /// the integer unit to minimize domain crossing penalties. However, for blends
6987 /// it falls back to the floating point shuffle operation with appropriate bit
6989 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6990 const X86Subtarget *Subtarget,
6991 SelectionDAG &DAG) {
6993 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6994 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6995 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6996 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6997 ArrayRef<int> Mask = SVOp->getMask();
6998 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7000 if (isSingleInputShuffleMask(Mask)) {
7001 // Straight shuffle of a single input vector. For everything from SSE2
7002 // onward this has a single fast instruction with no scary immediates.
7003 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7004 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7005 int WidenedMask[4] = {
7006 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7007 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7009 ISD::BITCAST, DL, MVT::v2i64,
7010 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7011 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7014 // We implement this with SHUFPD which is pretty lame because it will likely
7015 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7016 // However, all the alternatives are still more cycles and newer chips don't
7017 // have this problem. It would be really nice if x86 had better shuffles here.
7018 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7019 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7020 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7021 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7024 /// \brief Lower 4-lane 32-bit floating point shuffles.
7026 /// Uses instructions exclusively from the floating point unit to minimize
7027 /// domain crossing penalties, as these are sufficient to implement all v4f32
7029 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7030 const X86Subtarget *Subtarget,
7031 SelectionDAG &DAG) {
7033 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7034 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7035 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7036 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7037 ArrayRef<int> Mask = SVOp->getMask();
7038 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7040 SDValue LowV = V1, HighV = V2;
7041 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7044 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7046 if (NumV2Elements == 0)
7047 // Straight shuffle of a single input vector. We pass the input vector to
7048 // both operands to simulate this with a SHUFPS.
7049 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7050 getV4X86ShuffleImm8ForMask(Mask, DAG));
7052 if (NumV2Elements == 1) {
7054 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7056 // Compute the index adjacent to V2Index and in the same half by toggling
7058 int V2AdjIndex = V2Index ^ 1;
7060 if (Mask[V2AdjIndex] == -1) {
7061 // Handles all the cases where we have a single V2 element and an undef.
7062 // This will only ever happen in the high lanes because we commute the
7063 // vector otherwise.
7065 std::swap(LowV, HighV);
7066 NewMask[V2Index] -= 4;
7068 // Handle the case where the V2 element ends up adjacent to a V1 element.
7069 // To make this work, blend them together as the first step.
7070 int V1Index = V2AdjIndex;
7071 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7072 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7073 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7075 // Now proceed to reconstruct the final blend as we have the necessary
7076 // high or low half formed.
7083 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7084 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7086 } else if (NumV2Elements == 2) {
7087 if (Mask[0] < 4 && Mask[1] < 4) {
7088 // Handle the easy case where we have V1 in the low lanes and V2 in the
7089 // high lanes. We never see this reversed because we sort the shuffle.
7093 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7094 // trying to place elements directly, just blend them and set up the final
7095 // shuffle to place them.
7097 // The first two blend mask elements are for V1, the second two are for
7099 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7100 Mask[2] < 4 ? Mask[2] : Mask[3],
7101 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7102 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7103 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7104 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7106 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7109 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7110 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7111 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7112 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7115 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7116 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7119 /// \brief Lower 4-lane i32 vector shuffles.
7121 /// We try to handle these with integer-domain shuffles where we can, but for
7122 /// blends we use the floating point domain blend instructions.
7123 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7124 const X86Subtarget *Subtarget,
7125 SelectionDAG &DAG) {
7127 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7128 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7129 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7130 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131 ArrayRef<int> Mask = SVOp->getMask();
7132 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7134 if (isSingleInputShuffleMask(Mask))
7135 // Straight shuffle of a single input vector. For everything from SSE2
7136 // onward this has a single fast instruction with no scary immediates.
7137 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7138 getV4X86ShuffleImm8ForMask(Mask, DAG));
7140 // We implement this with SHUFPS because it can blend from two vectors.
7141 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7142 // up the inputs, bypassing domain shift penalties that we would encur if we
7143 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7145 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7146 DAG.getVectorShuffle(
7148 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7149 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7152 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7153 /// shuffle lowering, and the most complex part.
7155 /// The lowering strategy is to try to form pairs of input lanes which are
7156 /// targeted at the same half of the final vector, and then use a dword shuffle
7157 /// to place them onto the right half, and finally unpack the paired lanes into
7158 /// their final position.
7160 /// The exact breakdown of how to form these dword pairs and align them on the
7161 /// correct sides is really tricky. See the comments within the function for
7162 /// more of the details.
7163 static SDValue lowerV8I16SingleInputVectorShuffle(
7164 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7165 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7166 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7167 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7168 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7170 auto isLo = [](int M) { return M >= 0 && M < 4; };
7171 auto isHi = [](int M) { return M >= 4; };
7173 SmallVector<int, 4> LoInputs;
7174 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7175 [](int M) { return M >= 0; });
7176 std::sort(LoInputs.begin(), LoInputs.end());
7177 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7178 SmallVector<int, 4> HiInputs;
7179 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7180 [](int M) { return M >= 0; });
7181 std::sort(HiInputs.begin(), HiInputs.end());
7182 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7184 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7185 int NumHToL = LoInputs.size() - NumLToL;
7187 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7188 int NumHToH = HiInputs.size() - NumLToH;
7189 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7190 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7191 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7192 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7194 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7195 // such inputs we can swap two of the dwords across the half mark and end up
7196 // with <=2 inputs to each half in each half. Once there, we can fall through
7197 // to the generic code below. For example:
7199 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7200 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7202 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7204 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7205 int ThreeInputHalfSum, int OneInputHalfOffset) {
7206 // Compute the index of dword with only one word among the three inputs in
7207 // a half by taking the sum of the half with three inputs and subtracting
7208 // the sum of the actual three inputs. The difference is the remaining
7210 int DWordA = (ThreeInputHalfSum -
7211 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7213 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7215 int PSHUFDMask[] = {0, 1, 2, 3};
7216 PSHUFDMask[DWordA] = DWordB;
7217 PSHUFDMask[DWordB] = DWordA;
7218 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7219 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7220 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7221 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7223 // Adjust the mask to match the new locations of A and B.
7225 if (M != -1 && M/2 == DWordA)
7226 M = 2 * DWordB + M % 2;
7227 else if (M != -1 && M/2 == DWordB)
7228 M = 2 * DWordA + M % 2;
7230 // Recurse back into this routine to re-compute state now that this isn't
7231 // a 3 and 1 problem.
7232 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7235 if (NumLToL == 3 && NumHToL == 1)
7236 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7237 else if (NumLToL == 1 && NumHToL == 3)
7238 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7239 else if (NumLToH == 1 && NumHToH == 3)
7240 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7241 else if (NumLToH == 3 && NumHToH == 1)
7242 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7244 // At this point there are at most two inputs to the low and high halves from
7245 // each half. That means the inputs can always be grouped into dwords and
7246 // those dwords can then be moved to the correct half with a dword shuffle.
7247 // We use at most one low and one high word shuffle to collect these paired
7248 // inputs into dwords, and finally a dword shuffle to place them.
7249 int PSHUFLMask[4] = {-1, -1, -1, -1};
7250 int PSHUFHMask[4] = {-1, -1, -1, -1};
7251 int PSHUFDMask[4] = {-1, -1, -1, -1};
7253 // First fix the masks for all the inputs that are staying in their
7254 // original halves. This will then dictate the targets of the cross-half
7256 auto fixInPlaceInputs = [&PSHUFDMask](
7257 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7258 MutableArrayRef<int> HalfMask, int HalfOffset) {
7259 if (InPlaceInputs.empty())
7261 if (InPlaceInputs.size() == 1) {
7262 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7263 InPlaceInputs[0] - HalfOffset;
7264 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7268 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7269 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7270 InPlaceInputs[0] - HalfOffset;
7271 // Put the second input next to the first so that they are packed into
7272 // a dword. We find the adjacent index by toggling the low bit.
7273 int AdjIndex = InPlaceInputs[0] ^ 1;
7274 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7275 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7276 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7278 if (!HToLInputs.empty())
7279 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7280 if (!LToHInputs.empty())
7281 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7283 // Now gather the cross-half inputs and place them into a free dword of
7284 // their target half.
7285 // FIXME: This operation could almost certainly be simplified dramatically to
7286 // look more like the 3-1 fixing operation.
7287 auto moveInputsToRightHalf = [&PSHUFDMask](
7288 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7289 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7290 int SourceOffset, int DestOffset) {
7291 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7292 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7294 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7296 int LowWord = Word & ~1;
7297 int HighWord = Word | 1;
7298 return isWordClobbered(SourceHalfMask, LowWord) ||
7299 isWordClobbered(SourceHalfMask, HighWord);
7302 if (IncomingInputs.empty())
7305 if (ExistingInputs.empty()) {
7306 // Map any dwords with inputs from them into the right half.
7307 for (int Input : IncomingInputs) {
7308 // If the source half mask maps over the inputs, turn those into
7309 // swaps and use the swapped lane.
7310 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7311 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7312 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7313 Input - SourceOffset;
7314 // We have to swap the uses in our half mask in one sweep.
7315 for (int &M : HalfMask)
7316 if (M == SourceHalfMask[Input - SourceOffset])
7318 else if (M == Input)
7319 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7321 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7322 Input - SourceOffset &&
7323 "Previous placement doesn't match!");
7325 // Note that this correctly re-maps both when we do a swap and when
7326 // we observe the other side of the swap above. We rely on that to
7327 // avoid swapping the members of the input list directly.
7328 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7331 // Map the input's dword into the correct half.
7332 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7333 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7335 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7337 "Previous placement doesn't match!");
7340 // And just directly shift any other-half mask elements to be same-half
7341 // as we will have mirrored the dword containing the element into the
7342 // same position within that half.
7343 for (int &M : HalfMask)
7344 if (M >= SourceOffset && M < SourceOffset + 4) {
7345 M = M - SourceOffset + DestOffset;
7346 assert(M >= 0 && "This should never wrap below zero!");
7351 // Ensure we have the input in a viable dword of its current half. This
7352 // is particularly tricky because the original position may be clobbered
7353 // by inputs being moved and *staying* in that half.
7354 if (IncomingInputs.size() == 1) {
7355 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7356 int InputFixed = std::find(std::begin(SourceHalfMask),
7357 std::end(SourceHalfMask), -1) -
7358 std::begin(SourceHalfMask) + SourceOffset;
7359 SourceHalfMask[InputFixed - SourceOffset] =
7360 IncomingInputs[0] - SourceOffset;
7361 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7363 IncomingInputs[0] = InputFixed;
7365 } else if (IncomingInputs.size() == 2) {
7366 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7367 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7368 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7369 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7370 "Not all dwords can be clobbered!");
7371 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7372 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7373 for (int &M : HalfMask)
7374 if (M == IncomingInputs[0])
7375 M = SourceDWordBase + SourceOffset;
7376 else if (M == IncomingInputs[1])
7377 M = SourceDWordBase + 1 + SourceOffset;
7378 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7379 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7382 llvm_unreachable("Unhandled input size!");
7385 // Now hoist the DWord down to the right half.
7386 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7387 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7388 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7389 for (int Input : IncomingInputs)
7390 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7391 FreeDWord * 2 + Input % 2);
7393 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7394 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7395 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7396 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7398 // Now enact all the shuffles we've computed to move the inputs into their
7400 if (!isNoopShuffleMask(PSHUFLMask))
7401 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7402 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7403 if (!isNoopShuffleMask(PSHUFHMask))
7404 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7405 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7406 if (!isNoopShuffleMask(PSHUFDMask))
7407 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7408 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7409 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7410 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7412 // At this point, each half should contain all its inputs, and we can then
7413 // just shuffle them into their final position.
7414 assert(std::count_if(LoMask.begin(), LoMask.end(), isHi) == 0 &&
7415 "Failed to lift all the high half inputs to the low mask!");
7416 assert(std::count_if(HiMask.begin(), HiMask.end(), isLo) == 0 &&
7417 "Failed to lift all the low half inputs to the high mask!");
7419 // Do a half shuffle for the low mask.
7420 if (!isNoopShuffleMask(LoMask))
7421 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7422 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7424 // Do a half shuffle with the high mask after shifting its values down.
7425 for (int &M : HiMask)
7428 if (!isNoopShuffleMask(HiMask))
7429 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7430 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7435 /// \brief Detect whether the mask pattern should be lowered through
7438 /// This essentially tests whether viewing the mask as an interleaving of two
7439 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7440 /// lowering it through interleaving is a significantly better strategy.
7441 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7442 int NumEvenInputs[2] = {0, 0};
7443 int NumOddInputs[2] = {0, 0};
7444 int NumLoInputs[2] = {0, 0};
7445 int NumHiInputs[2] = {0, 0};
7446 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7450 int InputIdx = Mask[i] >= Size;
7453 ++NumLoInputs[InputIdx];
7455 ++NumHiInputs[InputIdx];
7458 ++NumEvenInputs[InputIdx];
7460 ++NumOddInputs[InputIdx];
7463 // The minimum number of cross-input results for both the interleaved and
7464 // split cases. If interleaving results in fewer cross-input results, return
7466 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7467 NumEvenInputs[0] + NumOddInputs[1]);
7468 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7469 NumLoInputs[0] + NumHiInputs[1]);
7470 return InterleavedCrosses < SplitCrosses;
7473 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7475 /// This strategy only works when the inputs from each vector fit into a single
7476 /// half of that vector, and generally there are not so many inputs as to leave
7477 /// the in-place shuffles required highly constrained (and thus expensive). It
7478 /// shifts all the inputs into a single side of both input vectors and then
7479 /// uses an unpack to interleave these inputs in a single vector. At that
7480 /// point, we will fall back on the generic single input shuffle lowering.
7481 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7483 MutableArrayRef<int> Mask,
7484 const X86Subtarget *Subtarget,
7485 SelectionDAG &DAG) {
7486 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7487 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7488 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7489 for (int i = 0; i < 8; ++i)
7490 if (Mask[i] >= 0 && Mask[i] < 4)
7491 LoV1Inputs.push_back(i);
7492 else if (Mask[i] >= 4 && Mask[i] < 8)
7493 HiV1Inputs.push_back(i);
7494 else if (Mask[i] >= 8 && Mask[i] < 12)
7495 LoV2Inputs.push_back(i);
7496 else if (Mask[i] >= 12)
7497 HiV2Inputs.push_back(i);
7499 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7500 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7502 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7503 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7504 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7506 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7507 HiV1Inputs.size() + HiV2Inputs.size();
7509 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7510 ArrayRef<int> HiInputs, bool MoveToLo,
7512 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7513 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7514 if (BadInputs.empty())
7517 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7518 int MoveOffset = MoveToLo ? 0 : 4;
7520 if (GoodInputs.empty()) {
7521 for (int BadInput : BadInputs) {
7522 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7523 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7526 if (GoodInputs.size() == 2) {
7527 // If the low inputs are spread across two dwords, pack them into
7529 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7530 Mask[GoodInputs[0]] - MaskOffset;
7531 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7532 Mask[GoodInputs[1]] - MaskOffset;
7533 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7534 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7536 // Otherwise pin the low inputs.
7537 for (int GoodInput : GoodInputs)
7538 MoveMask[Mask[GoodInput]] = Mask[GoodInput] - MaskOffset;
7542 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7543 std::begin(MoveMask);
7544 assert(MoveMaskIdx >= MoveOffset && "Established above");
7546 if (BadInputs.size() == 2) {
7547 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7548 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7549 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7550 Mask[BadInputs[0]] - MaskOffset;
7551 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7552 Mask[BadInputs[1]] - MaskOffset;
7553 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7554 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7556 assert(BadInputs.size() == 1 && "All sizes handled");
7557 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7558 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7562 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7565 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7567 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7570 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7571 // cross-half traffic in the final shuffle.
7573 // Munge the mask to be a single-input mask after the unpack merges the
7577 M = 2 * (M % 4) + (M / 8);
7579 return DAG.getVectorShuffle(
7580 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7581 DL, MVT::v8i16, V1, V2),
7582 DAG.getUNDEF(MVT::v8i16), Mask);
7585 /// \brief Generic lowering of 8-lane i16 shuffles.
7587 /// This handles both single-input shuffles and combined shuffle/blends with
7588 /// two inputs. The single input shuffles are immediately delegated to
7589 /// a dedicated lowering routine.
7591 /// The blends are lowered in one of three fundamental ways. If there are few
7592 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7593 /// of the input is significantly cheaper when lowered as an interleaving of
7594 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7595 /// halves of the inputs separately (making them have relatively few inputs)
7596 /// and then concatenate them.
7597 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7598 const X86Subtarget *Subtarget,
7599 SelectionDAG &DAG) {
7601 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7602 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7603 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7604 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7605 ArrayRef<int> OrigMask = SVOp->getMask();
7606 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7607 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7608 MutableArrayRef<int> Mask(MaskStorage);
7610 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7612 int Size = Mask.size();
7613 assert(Size == 8 && "Unexpected mask size for v8 shuffle!");
7615 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7616 auto isV2 = [](int M) { return M >= 8; };
7618 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7619 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7621 if (NumV2Inputs == 0)
7622 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7624 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7625 "to be V1-input shuffles.");
7627 if (NumV1Inputs + NumV2Inputs <= 4)
7628 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7630 // Check whether an interleaving lowering is likely to be more efficient.
7631 // This isn't perfect but it is a strong heuristic that tends to work well on
7632 // the kinds of shuffles that show up in practice.
7634 // FIXME: Handle 1x, 2x, and 4x interleaving.
7635 if (shouldLowerAsInterleaving(Mask)) {
7636 // FIXME: Figure out whether we should pack these into the low or high
7639 int EMask[8], OMask[8];
7640 for (int i = 0; i < 4; ++i) {
7641 EMask[i] = Mask[2*i];
7642 OMask[i] = Mask[2*i + 1];
7647 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7648 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7650 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7653 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7654 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7656 for (int i = 0; i < 4; ++i) {
7657 LoBlendMask[i] = Mask[i];
7658 HiBlendMask[i] = Mask[i + 4];
7661 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7662 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7663 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7664 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7666 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7667 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7670 /// \brief Generic lowering of v16i8 shuffles.
7672 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7673 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7674 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7675 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7677 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7678 const X86Subtarget *Subtarget,
7679 SelectionDAG &DAG) {
7681 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7682 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7683 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7684 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7685 ArrayRef<int> OrigMask = SVOp->getMask();
7686 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7687 int MaskStorage[16] = {
7688 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7689 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7690 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7691 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7692 MutableArrayRef<int> Mask(MaskStorage);
7693 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7694 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7696 // Check whether an interleaving lowering is likely to be more efficient.
7697 // This isn't perfect but it is a strong heuristic that tends to work well on
7698 // the kinds of shuffles that show up in practice.
7700 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7701 if (shouldLowerAsInterleaving(Mask)) {
7702 // FIXME: Figure out whether we should pack these into the low or high
7705 int EMask[16], OMask[16];
7706 for (int i = 0; i < 8; ++i) {
7707 EMask[i] = Mask[2*i];
7708 OMask[i] = Mask[2*i + 1];
7713 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7714 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7716 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7719 SDValue LoV1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7720 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1,
7721 DAG.getUNDEF(MVT::v8i16)));
7722 SDValue HiV1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7723 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1,
7724 DAG.getUNDEF(MVT::v8i16)));
7725 SDValue LoV2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7726 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2,
7727 DAG.getUNDEF(MVT::v8i16)));
7728 SDValue HiV2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7729 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2,
7730 DAG.getUNDEF(MVT::v8i16)));
7732 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7733 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7734 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7735 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7737 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7738 MutableArrayRef<int> V1HalfBlendMask,
7739 MutableArrayRef<int> V2HalfBlendMask) {
7740 for (int i = 0; i < 8; ++i)
7741 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7742 V1HalfBlendMask[i] = HalfMask[i];
7744 } else if (HalfMask[i] >= 16) {
7745 V2HalfBlendMask[i] = HalfMask[i] - 16;
7746 HalfMask[i] = i + 8;
7749 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7750 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7752 SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7753 SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7754 SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7755 SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7757 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7758 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7760 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7763 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7765 /// This routine breaks down the specific type of 128-bit shuffle and
7766 /// dispatches to the lowering routines accordingly.
7767 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7768 MVT VT, const X86Subtarget *Subtarget,
7769 SelectionDAG &DAG) {
7770 switch (VT.SimpleTy) {
7772 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7774 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7776 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7778 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7780 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7782 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7785 llvm_unreachable("Unimplemented!");
7789 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7790 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7791 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7792 if (Mask[i] + 1 != Mask[i+1])
7798 /// \brief Top-level lowering for x86 vector shuffles.
7800 /// This handles decomposition, canonicalization, and lowering of all x86
7801 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7802 /// above in helper routines. The canonicalization attempts to widen shuffles
7803 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7804 /// s.t. only one of the two inputs needs to be tested, etc.
7805 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7806 SelectionDAG &DAG) {
7807 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7808 ArrayRef<int> Mask = SVOp->getMask();
7809 SDValue V1 = Op.getOperand(0);
7810 SDValue V2 = Op.getOperand(1);
7811 MVT VT = Op.getSimpleValueType();
7812 int NumElements = VT.getVectorNumElements();
7815 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7817 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7818 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7819 if (V1IsUndef && V2IsUndef)
7820 return DAG.getUNDEF(VT);
7822 // When we create a shuffle node we put the UNDEF node to second operand,
7823 // but in some cases the first operand may be transformed to UNDEF.
7824 // In this case we should just commute the node.
7826 return CommuteVectorShuffle(SVOp, DAG);
7828 // Check for non-undef masks pointing at an undef vector and make the masks
7829 // undef as well. This makes it easier to match the shuffle based solely on
7833 if (M >= NumElements) {
7834 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7835 for (int &M : NewMask)
7836 if (M >= NumElements)
7838 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7841 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7842 // lanes but wider integers. We cap this to not form integers larger than i64
7843 // but it might be interesting to form i128 integers to handle flipping the
7844 // low and high halves of AVX 256-bit vectors.
7845 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7846 areAdjacentMasksSequential(Mask)) {
7847 SmallVector<int, 8> NewMask;
7848 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7849 NewMask.push_back(Mask[i] / 2);
7851 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7852 VT.getVectorNumElements() / 2);
7853 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7854 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7855 return DAG.getNode(ISD::BITCAST, dl, VT,
7856 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7859 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7860 for (int M : SVOp->getMask())
7863 else if (M < NumElements)
7868 // Commute the shuffle as needed such that more elements come from V1 than
7869 // V2. This allows us to match the shuffle pattern strictly on how many
7870 // elements come from V1 without handling the symmetric cases.
7871 if (NumV2Elements > NumV1Elements)
7872 return CommuteVectorShuffle(SVOp, DAG);
7874 // When the number of V1 and V2 elements are the same, try to minimize the
7875 // number of uses of V2 in the low half of the vector.
7876 if (NumV1Elements == NumV2Elements) {
7877 int LowV1Elements = 0, LowV2Elements = 0;
7878 for (int M : SVOp->getMask().slice(0, NumElements / 2))
7879 if (M >= NumElements)
7883 if (LowV2Elements > LowV1Elements)
7884 return CommuteVectorShuffle(SVOp, DAG);
7887 // For each vector width, delegate to a specialized lowering routine.
7888 if (VT.getSizeInBits() == 128)
7889 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7891 llvm_unreachable("Unimplemented!");
7895 //===----------------------------------------------------------------------===//
7896 // Legacy vector shuffle lowering
7898 // This code is the legacy code handling vector shuffles until the above
7899 // replaces its functionality and performance.
7900 //===----------------------------------------------------------------------===//
7902 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7903 bool hasInt256, unsigned *MaskOut = nullptr) {
7904 MVT EltVT = VT.getVectorElementType();
7906 // There is no blend with immediate in AVX-512.
7907 if (VT.is512BitVector())
7910 if (!hasSSE41 || EltVT == MVT::i8)
7912 if (!hasInt256 && VT == MVT::v16i16)
7915 unsigned MaskValue = 0;
7916 unsigned NumElems = VT.getVectorNumElements();
7917 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7918 unsigned NumLanes = (NumElems - 1) / 8 + 1;
7919 unsigned NumElemsInLane = NumElems / NumLanes;
7921 // Blend for v16i16 should be symetric for the both lanes.
7922 for (unsigned i = 0; i < NumElemsInLane; ++i) {
7924 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
7925 int EltIdx = MaskVals[i];
7927 if ((EltIdx < 0 || EltIdx == (int)i) &&
7928 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
7931 if (((unsigned)EltIdx == (i + NumElems)) &&
7932 (SndLaneEltIdx < 0 ||
7933 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
7934 MaskValue |= (1 << i);
7940 *MaskOut = MaskValue;
7944 // Try to lower a shuffle node into a simple blend instruction.
7945 // This function assumes isBlendMask returns true for this
7946 // SuffleVectorSDNode
7947 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
7949 const X86Subtarget *Subtarget,
7950 SelectionDAG &DAG) {
7951 MVT VT = SVOp->getSimpleValueType(0);
7952 MVT EltVT = VT.getVectorElementType();
7953 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
7954 Subtarget->hasInt256() && "Trying to lower a "
7955 "VECTOR_SHUFFLE to a Blend but "
7956 "with the wrong mask"));
7957 SDValue V1 = SVOp->getOperand(0);
7958 SDValue V2 = SVOp->getOperand(1);
7960 unsigned NumElems = VT.getVectorNumElements();
7962 // Convert i32 vectors to floating point if it is not AVX2.
7963 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
7965 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
7966 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
7968 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
7969 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
7972 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
7973 DAG.getConstant(MaskValue, MVT::i32));
7974 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
7977 /// In vector type \p VT, return true if the element at index \p InputIdx
7978 /// falls on a different 128-bit lane than \p OutputIdx.
7979 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
7980 unsigned OutputIdx) {
7981 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
7982 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
7985 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
7986 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
7987 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
7988 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
7990 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
7991 SelectionDAG &DAG) {
7992 MVT VT = V1.getSimpleValueType();
7993 assert(VT.is128BitVector() || VT.is256BitVector());
7995 MVT EltVT = VT.getVectorElementType();
7996 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
7997 unsigned NumElts = VT.getVectorNumElements();
7999 SmallVector<SDValue, 32> PshufbMask;
8000 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8001 int InputIdx = MaskVals[OutputIdx];
8002 unsigned InputByteIdx;
8004 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8005 InputByteIdx = 0x80;
8007 // Cross lane is not allowed.
8008 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8010 InputByteIdx = InputIdx * EltSizeInBytes;
8011 // Index is an byte offset within the 128-bit lane.
8012 InputByteIdx &= 0xf;
8015 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8016 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8017 if (InputByteIdx != 0x80)
8022 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8024 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8025 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8026 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8029 // v8i16 shuffles - Prefer shuffles in the following order:
8030 // 1. [all] pshuflw, pshufhw, optional move
8031 // 2. [ssse3] 1 x pshufb
8032 // 3. [ssse3] 2 x pshufb + 1 x por
8033 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8035 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8036 SelectionDAG &DAG) {
8037 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8038 SDValue V1 = SVOp->getOperand(0);
8039 SDValue V2 = SVOp->getOperand(1);
8041 SmallVector<int, 8> MaskVals;
8043 // Determine if more than 1 of the words in each of the low and high quadwords
8044 // of the result come from the same quadword of one of the two inputs. Undef
8045 // mask values count as coming from any quadword, for better codegen.
8047 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8048 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8049 unsigned LoQuad[] = { 0, 0, 0, 0 };
8050 unsigned HiQuad[] = { 0, 0, 0, 0 };
8051 // Indices of quads used.
8052 std::bitset<4> InputQuads;
8053 for (unsigned i = 0; i < 8; ++i) {
8054 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8055 int EltIdx = SVOp->getMaskElt(i);
8056 MaskVals.push_back(EltIdx);
8065 InputQuads.set(EltIdx / 4);
8068 int BestLoQuad = -1;
8069 unsigned MaxQuad = 1;
8070 for (unsigned i = 0; i < 4; ++i) {
8071 if (LoQuad[i] > MaxQuad) {
8073 MaxQuad = LoQuad[i];
8077 int BestHiQuad = -1;
8079 for (unsigned i = 0; i < 4; ++i) {
8080 if (HiQuad[i] > MaxQuad) {
8082 MaxQuad = HiQuad[i];
8086 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8087 // of the two input vectors, shuffle them into one input vector so only a
8088 // single pshufb instruction is necessary. If there are more than 2 input
8089 // quads, disable the next transformation since it does not help SSSE3.
8090 bool V1Used = InputQuads[0] || InputQuads[1];
8091 bool V2Used = InputQuads[2] || InputQuads[3];
8092 if (Subtarget->hasSSSE3()) {
8093 if (InputQuads.count() == 2 && V1Used && V2Used) {
8094 BestLoQuad = InputQuads[0] ? 0 : 1;
8095 BestHiQuad = InputQuads[2] ? 2 : 3;
8097 if (InputQuads.count() > 2) {
8103 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8104 // the shuffle mask. If a quad is scored as -1, that means that it contains
8105 // words from all 4 input quadwords.
8107 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8109 BestLoQuad < 0 ? 0 : BestLoQuad,
8110 BestHiQuad < 0 ? 1 : BestHiQuad
8112 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8113 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8114 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8115 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8117 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8118 // source words for the shuffle, to aid later transformations.
8119 bool AllWordsInNewV = true;
8120 bool InOrder[2] = { true, true };
8121 for (unsigned i = 0; i != 8; ++i) {
8122 int idx = MaskVals[i];
8124 InOrder[i/4] = false;
8125 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8127 AllWordsInNewV = false;
8131 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8132 if (AllWordsInNewV) {
8133 for (int i = 0; i != 8; ++i) {
8134 int idx = MaskVals[i];
8137 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8138 if ((idx != i) && idx < 4)
8140 if ((idx != i) && idx > 3)
8149 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8150 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8151 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8152 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8153 unsigned TargetMask = 0;
8154 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8155 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8156 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8157 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8158 getShufflePSHUFLWImmediate(SVOp);
8159 V1 = NewV.getOperand(0);
8160 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8164 // Promote splats to a larger type which usually leads to more efficient code.
8165 // FIXME: Is this true if pshufb is available?
8166 if (SVOp->isSplat())
8167 return PromoteSplat(SVOp, DAG);
8169 // If we have SSSE3, and all words of the result are from 1 input vector,
8170 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8171 // is present, fall back to case 4.
8172 if (Subtarget->hasSSSE3()) {
8173 SmallVector<SDValue,16> pshufbMask;
8175 // If we have elements from both input vectors, set the high bit of the
8176 // shuffle mask element to zero out elements that come from V2 in the V1
8177 // mask, and elements that come from V1 in the V2 mask, so that the two
8178 // results can be OR'd together.
8179 bool TwoInputs = V1Used && V2Used;
8180 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8182 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8184 // Calculate the shuffle mask for the second input, shuffle it, and
8185 // OR it with the first shuffled input.
8186 CommuteVectorShuffleMask(MaskVals, 8);
8187 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8188 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8189 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8192 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8193 // and update MaskVals with new element order.
8194 std::bitset<8> InOrder;
8195 if (BestLoQuad >= 0) {
8196 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8197 for (int i = 0; i != 4; ++i) {
8198 int idx = MaskVals[i];
8201 } else if ((idx / 4) == BestLoQuad) {
8206 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8209 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8210 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8211 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8213 getShufflePSHUFLWImmediate(SVOp), DAG);
8217 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8218 // and update MaskVals with the new element order.
8219 if (BestHiQuad >= 0) {
8220 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8221 for (unsigned i = 4; i != 8; ++i) {
8222 int idx = MaskVals[i];
8225 } else if ((idx / 4) == BestHiQuad) {
8226 MaskV[i] = (idx & 3) + 4;
8230 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8233 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8234 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8235 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8237 getShufflePSHUFHWImmediate(SVOp), DAG);
8241 // In case BestHi & BestLo were both -1, which means each quadword has a word
8242 // from each of the four input quadwords, calculate the InOrder bitvector now
8243 // before falling through to the insert/extract cleanup.
8244 if (BestLoQuad == -1 && BestHiQuad == -1) {
8246 for (int i = 0; i != 8; ++i)
8247 if (MaskVals[i] < 0 || MaskVals[i] == i)
8251 // The other elements are put in the right place using pextrw and pinsrw.
8252 for (unsigned i = 0; i != 8; ++i) {
8255 int EltIdx = MaskVals[i];
8258 SDValue ExtOp = (EltIdx < 8) ?
8259 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8260 DAG.getIntPtrConstant(EltIdx)) :
8261 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8262 DAG.getIntPtrConstant(EltIdx - 8));
8263 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8264 DAG.getIntPtrConstant(i));
8269 /// \brief v16i16 shuffles
8271 /// FIXME: We only support generation of a single pshufb currently. We can
8272 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8273 /// well (e.g 2 x pshufb + 1 x por).
8275 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8276 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8277 SDValue V1 = SVOp->getOperand(0);
8278 SDValue V2 = SVOp->getOperand(1);
8281 if (V2.getOpcode() != ISD::UNDEF)
8284 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8285 return getPSHUFB(MaskVals, V1, dl, DAG);
8288 // v16i8 shuffles - Prefer shuffles in the following order:
8289 // 1. [ssse3] 1 x pshufb
8290 // 2. [ssse3] 2 x pshufb + 1 x por
8291 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8292 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8293 const X86Subtarget* Subtarget,
8294 SelectionDAG &DAG) {
8295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8296 SDValue V1 = SVOp->getOperand(0);
8297 SDValue V2 = SVOp->getOperand(1);
8299 ArrayRef<int> MaskVals = SVOp->getMask();
8301 // Promote splats to a larger type which usually leads to more efficient code.
8302 // FIXME: Is this true if pshufb is available?
8303 if (SVOp->isSplat())
8304 return PromoteSplat(SVOp, DAG);
8306 // If we have SSSE3, case 1 is generated when all result bytes come from
8307 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8308 // present, fall back to case 3.
8310 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8311 if (Subtarget->hasSSSE3()) {
8312 SmallVector<SDValue,16> pshufbMask;
8314 // If all result elements are from one input vector, then only translate
8315 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8317 // Otherwise, we have elements from both input vectors, and must zero out
8318 // elements that come from V2 in the first mask, and V1 in the second mask
8319 // so that we can OR them together.
8320 for (unsigned i = 0; i != 16; ++i) {
8321 int EltIdx = MaskVals[i];
8322 if (EltIdx < 0 || EltIdx >= 16)
8324 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8326 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8327 DAG.getNode(ISD::BUILD_VECTOR, dl,
8328 MVT::v16i8, pshufbMask));
8330 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8331 // the 2nd operand if it's undefined or zero.
8332 if (V2.getOpcode() == ISD::UNDEF ||
8333 ISD::isBuildVectorAllZeros(V2.getNode()))
8336 // Calculate the shuffle mask for the second input, shuffle it, and
8337 // OR it with the first shuffled input.
8339 for (unsigned i = 0; i != 16; ++i) {
8340 int EltIdx = MaskVals[i];
8341 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8342 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8344 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8345 DAG.getNode(ISD::BUILD_VECTOR, dl,
8346 MVT::v16i8, pshufbMask));
8347 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8350 // No SSSE3 - Calculate in place words and then fix all out of place words
8351 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8352 // the 16 different words that comprise the two doublequadword input vectors.
8353 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8354 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8356 for (int i = 0; i != 8; ++i) {
8357 int Elt0 = MaskVals[i*2];
8358 int Elt1 = MaskVals[i*2+1];
8360 // This word of the result is all undef, skip it.
8361 if (Elt0 < 0 && Elt1 < 0)
8364 // This word of the result is already in the correct place, skip it.
8365 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8368 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8369 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8372 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8373 // using a single extract together, load it and store it.
8374 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8375 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8376 DAG.getIntPtrConstant(Elt1 / 2));
8377 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8378 DAG.getIntPtrConstant(i));
8382 // If Elt1 is defined, extract it from the appropriate source. If the
8383 // source byte is not also odd, shift the extracted word left 8 bits
8384 // otherwise clear the bottom 8 bits if we need to do an or.
8386 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8387 DAG.getIntPtrConstant(Elt1 / 2));
8388 if ((Elt1 & 1) == 0)
8389 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8391 TLI.getShiftAmountTy(InsElt.getValueType())));
8393 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8394 DAG.getConstant(0xFF00, MVT::i16));
8396 // If Elt0 is defined, extract it from the appropriate source. If the
8397 // source byte is not also even, shift the extracted word right 8 bits. If
8398 // Elt1 was also defined, OR the extracted values together before
8399 // inserting them in the result.
8401 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8402 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8403 if ((Elt0 & 1) != 0)
8404 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8406 TLI.getShiftAmountTy(InsElt0.getValueType())));
8408 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8409 DAG.getConstant(0x00FF, MVT::i16));
8410 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8413 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8414 DAG.getIntPtrConstant(i));
8416 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8419 // v32i8 shuffles - Translate to VPSHUFB if possible.
8421 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8422 const X86Subtarget *Subtarget,
8423 SelectionDAG &DAG) {
8424 MVT VT = SVOp->getSimpleValueType(0);
8425 SDValue V1 = SVOp->getOperand(0);
8426 SDValue V2 = SVOp->getOperand(1);
8428 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8430 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8431 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8432 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8434 // VPSHUFB may be generated if
8435 // (1) one of input vector is undefined or zeroinitializer.
8436 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8437 // And (2) the mask indexes don't cross the 128-bit lane.
8438 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8439 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8442 if (V1IsAllZero && !V2IsAllZero) {
8443 CommuteVectorShuffleMask(MaskVals, 32);
8446 return getPSHUFB(MaskVals, V1, dl, DAG);
8449 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8450 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8451 /// done when every pair / quad of shuffle mask elements point to elements in
8452 /// the right sequence. e.g.
8453 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8455 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8456 SelectionDAG &DAG) {
8457 MVT VT = SVOp->getSimpleValueType(0);
8459 unsigned NumElems = VT.getVectorNumElements();
8462 switch (VT.SimpleTy) {
8463 default: llvm_unreachable("Unexpected!");
8466 return SDValue(SVOp, 0);
8467 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8468 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8469 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8470 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8471 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8472 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8475 SmallVector<int, 8> MaskVec;
8476 for (unsigned i = 0; i != NumElems; i += Scale) {
8478 for (unsigned j = 0; j != Scale; ++j) {
8479 int EltIdx = SVOp->getMaskElt(i+j);
8483 StartIdx = (EltIdx / Scale);
8484 if (EltIdx != (int)(StartIdx*Scale + j))
8487 MaskVec.push_back(StartIdx);
8490 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8491 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8492 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8495 /// getVZextMovL - Return a zero-extending vector move low node.
8497 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8498 SDValue SrcOp, SelectionDAG &DAG,
8499 const X86Subtarget *Subtarget, SDLoc dl) {
8500 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8501 LoadSDNode *LD = nullptr;
8502 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8503 LD = dyn_cast<LoadSDNode>(SrcOp);
8505 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8507 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8508 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8509 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8510 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8511 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8513 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8514 return DAG.getNode(ISD::BITCAST, dl, VT,
8515 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8516 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8524 return DAG.getNode(ISD::BITCAST, dl, VT,
8525 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8526 DAG.getNode(ISD::BITCAST, dl,
8530 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8531 /// which could not be matched by any known target speficic shuffle
8533 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8535 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8536 if (NewOp.getNode())
8539 MVT VT = SVOp->getSimpleValueType(0);
8541 unsigned NumElems = VT.getVectorNumElements();
8542 unsigned NumLaneElems = NumElems / 2;
8545 MVT EltVT = VT.getVectorElementType();
8546 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8549 SmallVector<int, 16> Mask;
8550 for (unsigned l = 0; l < 2; ++l) {
8551 // Build a shuffle mask for the output, discovering on the fly which
8552 // input vectors to use as shuffle operands (recorded in InputUsed).
8553 // If building a suitable shuffle vector proves too hard, then bail
8554 // out with UseBuildVector set.
8555 bool UseBuildVector = false;
8556 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8557 unsigned LaneStart = l * NumLaneElems;
8558 for (unsigned i = 0; i != NumLaneElems; ++i) {
8559 // The mask element. This indexes into the input.
8560 int Idx = SVOp->getMaskElt(i+LaneStart);
8562 // the mask element does not index into any input vector.
8567 // The input vector this mask element indexes into.
8568 int Input = Idx / NumLaneElems;
8570 // Turn the index into an offset from the start of the input vector.
8571 Idx -= Input * NumLaneElems;
8573 // Find or create a shuffle vector operand to hold this input.
8575 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8576 if (InputUsed[OpNo] == Input)
8577 // This input vector is already an operand.
8579 if (InputUsed[OpNo] < 0) {
8580 // Create a new operand for this input vector.
8581 InputUsed[OpNo] = Input;
8586 if (OpNo >= array_lengthof(InputUsed)) {
8587 // More than two input vectors used! Give up on trying to create a
8588 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8589 UseBuildVector = true;
8593 // Add the mask index for the new shuffle vector.
8594 Mask.push_back(Idx + OpNo * NumLaneElems);
8597 if (UseBuildVector) {
8598 SmallVector<SDValue, 16> SVOps;
8599 for (unsigned i = 0; i != NumLaneElems; ++i) {
8600 // The mask element. This indexes into the input.
8601 int Idx = SVOp->getMaskElt(i+LaneStart);
8603 SVOps.push_back(DAG.getUNDEF(EltVT));
8607 // The input vector this mask element indexes into.
8608 int Input = Idx / NumElems;
8610 // Turn the index into an offset from the start of the input vector.
8611 Idx -= Input * NumElems;
8613 // Extract the vector element by hand.
8614 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8615 SVOp->getOperand(Input),
8616 DAG.getIntPtrConstant(Idx)));
8619 // Construct the output using a BUILD_VECTOR.
8620 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8621 } else if (InputUsed[0] < 0) {
8622 // No input vectors were used! The result is undefined.
8623 Output[l] = DAG.getUNDEF(NVT);
8625 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8626 (InputUsed[0] % 2) * NumLaneElems,
8628 // If only one input was used, use an undefined vector for the other.
8629 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8630 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8631 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8632 // At least one input vector was used. Create a new shuffle vector.
8633 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8639 // Concatenate the result back
8640 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8643 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8644 /// 4 elements, and match them with several different shuffle types.
8646 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8647 SDValue V1 = SVOp->getOperand(0);
8648 SDValue V2 = SVOp->getOperand(1);
8650 MVT VT = SVOp->getSimpleValueType(0);
8652 assert(VT.is128BitVector() && "Unsupported vector size");
8654 std::pair<int, int> Locs[4];
8655 int Mask1[] = { -1, -1, -1, -1 };
8656 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8660 for (unsigned i = 0; i != 4; ++i) {
8661 int Idx = PermMask[i];
8663 Locs[i] = std::make_pair(-1, -1);
8665 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8667 Locs[i] = std::make_pair(0, NumLo);
8671 Locs[i] = std::make_pair(1, NumHi);
8673 Mask1[2+NumHi] = Idx;
8679 if (NumLo <= 2 && NumHi <= 2) {
8680 // If no more than two elements come from either vector. This can be
8681 // implemented with two shuffles. First shuffle gather the elements.
8682 // The second shuffle, which takes the first shuffle as both of its
8683 // vector operands, put the elements into the right order.
8684 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8686 int Mask2[] = { -1, -1, -1, -1 };
8688 for (unsigned i = 0; i != 4; ++i)
8689 if (Locs[i].first != -1) {
8690 unsigned Idx = (i < 2) ? 0 : 4;
8691 Idx += Locs[i].first * 2 + Locs[i].second;
8695 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8698 if (NumLo == 3 || NumHi == 3) {
8699 // Otherwise, we must have three elements from one vector, call it X, and
8700 // one element from the other, call it Y. First, use a shufps to build an
8701 // intermediate vector with the one element from Y and the element from X
8702 // that will be in the same half in the final destination (the indexes don't
8703 // matter). Then, use a shufps to build the final vector, taking the half
8704 // containing the element from Y from the intermediate, and the other half
8707 // Normalize it so the 3 elements come from V1.
8708 CommuteVectorShuffleMask(PermMask, 4);
8712 // Find the element from V2.
8714 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8715 int Val = PermMask[HiIndex];
8722 Mask1[0] = PermMask[HiIndex];
8724 Mask1[2] = PermMask[HiIndex^1];
8726 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8729 Mask1[0] = PermMask[0];
8730 Mask1[1] = PermMask[1];
8731 Mask1[2] = HiIndex & 1 ? 6 : 4;
8732 Mask1[3] = HiIndex & 1 ? 4 : 6;
8733 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8736 Mask1[0] = HiIndex & 1 ? 2 : 0;
8737 Mask1[1] = HiIndex & 1 ? 0 : 2;
8738 Mask1[2] = PermMask[2];
8739 Mask1[3] = PermMask[3];
8744 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8747 // Break it into (shuffle shuffle_hi, shuffle_lo).
8748 int LoMask[] = { -1, -1, -1, -1 };
8749 int HiMask[] = { -1, -1, -1, -1 };
8751 int *MaskPtr = LoMask;
8752 unsigned MaskIdx = 0;
8755 for (unsigned i = 0; i != 4; ++i) {
8762 int Idx = PermMask[i];
8764 Locs[i] = std::make_pair(-1, -1);
8765 } else if (Idx < 4) {
8766 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8767 MaskPtr[LoIdx] = Idx;
8770 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8771 MaskPtr[HiIdx] = Idx;
8776 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8777 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8778 int MaskOps[] = { -1, -1, -1, -1 };
8779 for (unsigned i = 0; i != 4; ++i)
8780 if (Locs[i].first != -1)
8781 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8782 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8785 static bool MayFoldVectorLoad(SDValue V) {
8786 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8787 V = V.getOperand(0);
8789 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8790 V = V.getOperand(0);
8791 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8792 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8793 // BUILD_VECTOR (load), undef
8794 V = V.getOperand(0);
8796 return MayFoldLoad(V);
8800 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8801 MVT VT = Op.getSimpleValueType();
8803 // Canonizalize to v2f64.
8804 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8805 return DAG.getNode(ISD::BITCAST, dl, VT,
8806 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8811 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8813 SDValue V1 = Op.getOperand(0);
8814 SDValue V2 = Op.getOperand(1);
8815 MVT VT = Op.getSimpleValueType();
8817 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8819 if (HasSSE2 && VT == MVT::v2f64)
8820 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8822 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8823 return DAG.getNode(ISD::BITCAST, dl, VT,
8824 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8825 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8826 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8830 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8831 SDValue V1 = Op.getOperand(0);
8832 SDValue V2 = Op.getOperand(1);
8833 MVT VT = Op.getSimpleValueType();
8835 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8836 "unsupported shuffle type");
8838 if (V2.getOpcode() == ISD::UNDEF)
8842 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8846 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8847 SDValue V1 = Op.getOperand(0);
8848 SDValue V2 = Op.getOperand(1);
8849 MVT VT = Op.getSimpleValueType();
8850 unsigned NumElems = VT.getVectorNumElements();
8852 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8853 // operand of these instructions is only memory, so check if there's a
8854 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8856 bool CanFoldLoad = false;
8858 // Trivial case, when V2 comes from a load.
8859 if (MayFoldVectorLoad(V2))
8862 // When V1 is a load, it can be folded later into a store in isel, example:
8863 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8865 // (MOVLPSmr addr:$src1, VR128:$src2)
8866 // So, recognize this potential and also use MOVLPS or MOVLPD
8867 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8870 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8872 if (HasSSE2 && NumElems == 2)
8873 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8876 // If we don't care about the second element, proceed to use movss.
8877 if (SVOp->getMaskElt(1) != -1)
8878 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8881 // movl and movlp will both match v2i64, but v2i64 is never matched by
8882 // movl earlier because we make it strict to avoid messing with the movlp load
8883 // folding logic (see the code above getMOVLP call). Match it here then,
8884 // this is horrible, but will stay like this until we move all shuffle
8885 // matching to x86 specific nodes. Note that for the 1st condition all
8886 // types are matched with movsd.
8888 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8889 // as to remove this logic from here, as much as possible
8890 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8891 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8892 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8895 assert(VT != MVT::v4i32 && "unsupported shuffle type");
8897 // Invert the operand order and use SHUFPS to match it.
8898 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8899 getShuffleSHUFImmediate(SVOp), DAG);
8902 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8903 SelectionDAG &DAG) {
8905 MVT VT = Load->getSimpleValueType(0);
8906 MVT EVT = VT.getVectorElementType();
8907 SDValue Addr = Load->getOperand(1);
8908 SDValue NewAddr = DAG.getNode(
8909 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8910 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8913 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8914 DAG.getMachineFunction().getMachineMemOperand(
8915 Load->getMemOperand(), 0, EVT.getStoreSize()));
8919 // It is only safe to call this function if isINSERTPSMask is true for
8920 // this shufflevector mask.
8921 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
8922 SelectionDAG &DAG) {
8923 // Generate an insertps instruction when inserting an f32 from memory onto a
8924 // v4f32 or when copying a member from one v4f32 to another.
8925 // We also use it for transferring i32 from one register to another,
8926 // since it simply copies the same bits.
8927 // If we're transferring an i32 from memory to a specific element in a
8928 // register, we output a generic DAG that will match the PINSRD
8930 MVT VT = SVOp->getSimpleValueType(0);
8931 MVT EVT = VT.getVectorElementType();
8932 SDValue V1 = SVOp->getOperand(0);
8933 SDValue V2 = SVOp->getOperand(1);
8934 auto Mask = SVOp->getMask();
8935 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
8936 "unsupported vector type for insertps/pinsrd");
8938 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
8939 auto FromV2Predicate = [](const int &i) { return i >= 4; };
8940 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
8948 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
8951 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
8952 "More than one element from V1 and from V2, or no elements from one "
8953 "of the vectors. This case should not have returned true from "
8958 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
8961 unsigned SrcIndex = Mask[DestIndex] % 4;
8962 if (MayFoldLoad(From)) {
8963 // Trivial case, when From comes from a load and is only used by the
8964 // shuffle. Make it use insertps from the vector that we need from that
8967 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
8968 if (!NewLoad.getNode())
8971 if (EVT == MVT::f32) {
8972 // Create this as a scalar to vector to match the instruction pattern.
8973 SDValue LoadScalarToVector =
8974 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
8975 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
8976 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
8978 } else { // EVT == MVT::i32
8979 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
8980 // instruction, to match the PINSRD instruction, which loads an i32 to a
8981 // certain vector element.
8982 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
8983 DAG.getConstant(DestIndex, MVT::i32));
8987 // Vector-element-to-vector
8988 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
8989 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
8992 // Reduce a vector shuffle to zext.
8993 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
8994 SelectionDAG &DAG) {
8995 // PMOVZX is only available from SSE41.
8996 if (!Subtarget->hasSSE41())
8999 MVT VT = Op.getSimpleValueType();
9001 // Only AVX2 support 256-bit vector integer extending.
9002 if (!Subtarget->hasInt256() && VT.is256BitVector())
9005 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9007 SDValue V1 = Op.getOperand(0);
9008 SDValue V2 = Op.getOperand(1);
9009 unsigned NumElems = VT.getVectorNumElements();
9011 // Extending is an unary operation and the element type of the source vector
9012 // won't be equal to or larger than i64.
9013 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9014 VT.getVectorElementType() == MVT::i64)
9017 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9018 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9019 while ((1U << Shift) < NumElems) {
9020 if (SVOp->getMaskElt(1U << Shift) == 1)
9023 // The maximal ratio is 8, i.e. from i8 to i64.
9028 // Check the shuffle mask.
9029 unsigned Mask = (1U << Shift) - 1;
9030 for (unsigned i = 0; i != NumElems; ++i) {
9031 int EltIdx = SVOp->getMaskElt(i);
9032 if ((i & Mask) != 0 && EltIdx != -1)
9034 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9038 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9039 MVT NeVT = MVT::getIntegerVT(NBits);
9040 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9042 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9045 // Simplify the operand as it's prepared to be fed into shuffle.
9046 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9047 if (V1.getOpcode() == ISD::BITCAST &&
9048 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9049 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9050 V1.getOperand(0).getOperand(0)
9051 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9052 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9053 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9054 ConstantSDNode *CIdx =
9055 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9056 // If it's foldable, i.e. normal load with single use, we will let code
9057 // selection to fold it. Otherwise, we will short the conversion sequence.
9058 if (CIdx && CIdx->getZExtValue() == 0 &&
9059 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9060 MVT FullVT = V.getSimpleValueType();
9061 MVT V1VT = V1.getSimpleValueType();
9062 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9063 // The "ext_vec_elt" node is wider than the result node.
9064 // In this case we should extract subvector from V.
9065 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9066 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9067 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9068 FullVT.getVectorNumElements()/Ratio);
9069 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9070 DAG.getIntPtrConstant(0));
9072 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9076 return DAG.getNode(ISD::BITCAST, DL, VT,
9077 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9080 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9081 SelectionDAG &DAG) {
9082 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9083 MVT VT = Op.getSimpleValueType();
9085 SDValue V1 = Op.getOperand(0);
9086 SDValue V2 = Op.getOperand(1);
9088 if (isZeroShuffle(SVOp))
9089 return getZeroVector(VT, Subtarget, DAG, dl);
9091 // Handle splat operations
9092 if (SVOp->isSplat()) {
9093 // Use vbroadcast whenever the splat comes from a foldable load
9094 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9095 if (Broadcast.getNode())
9099 // Check integer expanding shuffles.
9100 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9101 if (NewOp.getNode())
9104 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9106 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9108 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9109 if (NewOp.getNode())
9110 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9111 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9112 // FIXME: Figure out a cleaner way to do this.
9113 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9114 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9115 if (NewOp.getNode()) {
9116 MVT NewVT = NewOp.getSimpleValueType();
9117 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9118 NewVT, true, false))
9119 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9122 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9123 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9124 if (NewOp.getNode()) {
9125 MVT NewVT = NewOp.getSimpleValueType();
9126 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9127 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9136 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9138 SDValue V1 = Op.getOperand(0);
9139 SDValue V2 = Op.getOperand(1);
9140 MVT VT = Op.getSimpleValueType();
9142 unsigned NumElems = VT.getVectorNumElements();
9143 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9144 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9145 bool V1IsSplat = false;
9146 bool V2IsSplat = false;
9147 bool HasSSE2 = Subtarget->hasSSE2();
9148 bool HasFp256 = Subtarget->hasFp256();
9149 bool HasInt256 = Subtarget->hasInt256();
9150 MachineFunction &MF = DAG.getMachineFunction();
9151 bool OptForSize = MF.getFunction()->getAttributes().
9152 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9154 // Check if we should use the experimental vector shuffle lowering. If so,
9155 // delegate completely to that code path.
9156 if (ExperimentalVectorShuffleLowering)
9157 return lowerVectorShuffle(Op, Subtarget, DAG);
9159 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9161 if (V1IsUndef && V2IsUndef)
9162 return DAG.getUNDEF(VT);
9164 // When we create a shuffle node we put the UNDEF node to second operand,
9165 // but in some cases the first operand may be transformed to UNDEF.
9166 // In this case we should just commute the node.
9168 return CommuteVectorShuffle(SVOp, DAG);
9170 // Vector shuffle lowering takes 3 steps:
9172 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9173 // narrowing and commutation of operands should be handled.
9174 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9176 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9177 // so the shuffle can be broken into other shuffles and the legalizer can
9178 // try the lowering again.
9180 // The general idea is that no vector_shuffle operation should be left to
9181 // be matched during isel, all of them must be converted to a target specific
9184 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9185 // narrowing and commutation of operands should be handled. The actual code
9186 // doesn't include all of those, work in progress...
9187 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9188 if (NewOp.getNode())
9191 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9193 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9194 // unpckh_undef). Only use pshufd if speed is more important than size.
9195 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9196 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9197 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9198 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9200 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9201 V2IsUndef && MayFoldVectorLoad(V1))
9202 return getMOVDDup(Op, dl, V1, DAG);
9204 if (isMOVHLPS_v_undef_Mask(M, VT))
9205 return getMOVHighToLow(Op, dl, DAG);
9207 // Use to match splats
9208 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9209 (VT == MVT::v2f64 || VT == MVT::v2i64))
9210 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9212 if (isPSHUFDMask(M, VT)) {
9213 // The actual implementation will match the mask in the if above and then
9214 // during isel it can match several different instructions, not only pshufd
9215 // as its name says, sad but true, emulate the behavior for now...
9216 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9217 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9219 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9221 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9222 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9224 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9225 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9228 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9232 if (isPALIGNRMask(M, VT, Subtarget))
9233 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9234 getShufflePALIGNRImmediate(SVOp),
9237 // Check if this can be converted into a logical shift.
9238 bool isLeft = false;
9241 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9242 if (isShift && ShVal.hasOneUse()) {
9243 // If the shifted value has multiple uses, it may be cheaper to use
9244 // v_set0 + movlhps or movhlps, etc.
9245 MVT EltVT = VT.getVectorElementType();
9246 ShAmt *= EltVT.getSizeInBits();
9247 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9250 if (isMOVLMask(M, VT)) {
9251 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9252 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9253 if (!isMOVLPMask(M, VT)) {
9254 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9255 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9257 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9258 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9262 // FIXME: fold these into legal mask.
9263 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9264 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9266 if (isMOVHLPSMask(M, VT))
9267 return getMOVHighToLow(Op, dl, DAG);
9269 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9270 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9272 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9273 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9275 if (isMOVLPMask(M, VT))
9276 return getMOVLP(Op, dl, DAG, HasSSE2);
9278 if (ShouldXformToMOVHLPS(M, VT) ||
9279 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9280 return CommuteVectorShuffle(SVOp, DAG);
9283 // No better options. Use a vshldq / vsrldq.
9284 MVT EltVT = VT.getVectorElementType();
9285 ShAmt *= EltVT.getSizeInBits();
9286 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9289 bool Commuted = false;
9290 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9291 // 1,1,1,1 -> v8i16 though.
9292 V1IsSplat = isSplatVector(V1.getNode());
9293 V2IsSplat = isSplatVector(V2.getNode());
9295 // Canonicalize the splat or undef, if present, to be on the RHS.
9296 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9297 CommuteVectorShuffleMask(M, NumElems);
9299 std::swap(V1IsSplat, V2IsSplat);
9303 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9304 // Shuffling low element of v1 into undef, just return v1.
9307 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9308 // the instruction selector will not match, so get a canonical MOVL with
9309 // swapped operands to undo the commute.
9310 return getMOVL(DAG, dl, VT, V2, V1);
9313 if (isUNPCKLMask(M, VT, HasInt256))
9314 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9316 if (isUNPCKHMask(M, VT, HasInt256))
9317 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9320 // Normalize mask so all entries that point to V2 points to its first
9321 // element then try to match unpck{h|l} again. If match, return a
9322 // new vector_shuffle with the corrected mask.p
9323 SmallVector<int, 8> NewMask(M.begin(), M.end());
9324 NormalizeMask(NewMask, NumElems);
9325 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9326 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9327 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9328 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9332 // Commute is back and try unpck* again.
9333 // FIXME: this seems wrong.
9334 CommuteVectorShuffleMask(M, NumElems);
9336 std::swap(V1IsSplat, V2IsSplat);
9338 if (isUNPCKLMask(M, VT, HasInt256))
9339 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9341 if (isUNPCKHMask(M, VT, HasInt256))
9342 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9345 // Normalize the node to match x86 shuffle ops if needed
9346 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9347 return CommuteVectorShuffle(SVOp, DAG);
9349 // The checks below are all present in isShuffleMaskLegal, but they are
9350 // inlined here right now to enable us to directly emit target specific
9351 // nodes, and remove one by one until they don't return Op anymore.
9353 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9354 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9355 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9356 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9359 if (isPSHUFHWMask(M, VT, HasInt256))
9360 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9361 getShufflePSHUFHWImmediate(SVOp),
9364 if (isPSHUFLWMask(M, VT, HasInt256))
9365 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9366 getShufflePSHUFLWImmediate(SVOp),
9370 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9372 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9374 if (isSHUFPMask(M, VT))
9375 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9376 getShuffleSHUFImmediate(SVOp), DAG);
9378 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9379 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9380 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9381 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9383 //===--------------------------------------------------------------------===//
9384 // Generate target specific nodes for 128 or 256-bit shuffles only
9385 // supported in the AVX instruction set.
9388 // Handle VMOVDDUPY permutations
9389 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9390 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9392 // Handle VPERMILPS/D* permutations
9393 if (isVPERMILPMask(M, VT)) {
9394 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9395 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9396 getShuffleSHUFImmediate(SVOp), DAG);
9397 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9398 getShuffleSHUFImmediate(SVOp), DAG);
9402 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9403 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9404 Idx*(NumElems/2), DAG, dl);
9406 // Handle VPERM2F128/VPERM2I128 permutations
9407 if (isVPERM2X128Mask(M, VT, HasFp256))
9408 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9409 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9411 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9412 return getINSERTPS(SVOp, dl, DAG);
9415 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9416 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9418 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9419 VT.is512BitVector()) {
9420 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9421 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9422 SmallVector<SDValue, 16> permclMask;
9423 for (unsigned i = 0; i != NumElems; ++i) {
9424 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9427 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9429 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9430 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9431 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9432 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9433 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9436 //===--------------------------------------------------------------------===//
9437 // Since no target specific shuffle was selected for this generic one,
9438 // lower it into other known shuffles. FIXME: this isn't true yet, but
9439 // this is the plan.
9442 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9443 if (VT == MVT::v8i16) {
9444 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9445 if (NewOp.getNode())
9449 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9450 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9451 if (NewOp.getNode())
9455 if (VT == MVT::v16i8) {
9456 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9457 if (NewOp.getNode())
9461 if (VT == MVT::v32i8) {
9462 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9463 if (NewOp.getNode())
9467 // Handle all 128-bit wide vectors with 4 elements, and match them with
9468 // several different shuffle types.
9469 if (NumElems == 4 && VT.is128BitVector())
9470 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9472 // Handle general 256-bit shuffles
9473 if (VT.is256BitVector())
9474 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9479 // This function assumes its argument is a BUILD_VECTOR of constants or
9480 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9482 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9483 unsigned &MaskValue) {
9485 unsigned NumElems = BuildVector->getNumOperands();
9486 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9487 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9488 unsigned NumElemsInLane = NumElems / NumLanes;
9490 // Blend for v16i16 should be symetric for the both lanes.
9491 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9492 SDValue EltCond = BuildVector->getOperand(i);
9493 SDValue SndLaneEltCond =
9494 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9496 int Lane1Cond = -1, Lane2Cond = -1;
9497 if (isa<ConstantSDNode>(EltCond))
9498 Lane1Cond = !isZero(EltCond);
9499 if (isa<ConstantSDNode>(SndLaneEltCond))
9500 Lane2Cond = !isZero(SndLaneEltCond);
9502 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9503 // Lane1Cond != 0, means we want the first argument.
9504 // Lane1Cond == 0, means we want the second argument.
9505 // The encoding of this argument is 0 for the first argument, 1
9506 // for the second. Therefore, invert the condition.
9507 MaskValue |= !Lane1Cond << i;
9508 else if (Lane1Cond < 0)
9509 MaskValue |= !Lane2Cond << i;
9516 // Try to lower a vselect node into a simple blend instruction.
9517 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9518 SelectionDAG &DAG) {
9519 SDValue Cond = Op.getOperand(0);
9520 SDValue LHS = Op.getOperand(1);
9521 SDValue RHS = Op.getOperand(2);
9523 MVT VT = Op.getSimpleValueType();
9524 MVT EltVT = VT.getVectorElementType();
9525 unsigned NumElems = VT.getVectorNumElements();
9527 // There is no blend with immediate in AVX-512.
9528 if (VT.is512BitVector())
9531 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9533 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9536 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9539 // Check the mask for BLEND and build the value.
9540 unsigned MaskValue = 0;
9541 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9544 // Convert i32 vectors to floating point if it is not AVX2.
9545 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9547 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9548 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9550 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9551 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9554 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9555 DAG.getConstant(MaskValue, MVT::i32));
9556 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9559 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9560 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9561 if (BlendOp.getNode())
9564 // Some types for vselect were previously set to Expand, not Legal or
9565 // Custom. Return an empty SDValue so we fall-through to Expand, after
9566 // the Custom lowering phase.
9567 MVT VT = Op.getSimpleValueType();
9568 switch (VT.SimpleTy) {
9576 // We couldn't create a "Blend with immediate" node.
9577 // This node should still be legal, but we'll have to emit a blendv*
9582 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9583 MVT VT = Op.getSimpleValueType();
9586 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9589 if (VT.getSizeInBits() == 8) {
9590 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9591 Op.getOperand(0), Op.getOperand(1));
9592 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9593 DAG.getValueType(VT));
9594 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9597 if (VT.getSizeInBits() == 16) {
9598 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9599 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9601 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9602 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9603 DAG.getNode(ISD::BITCAST, dl,
9607 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9608 Op.getOperand(0), Op.getOperand(1));
9609 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9610 DAG.getValueType(VT));
9611 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9614 if (VT == MVT::f32) {
9615 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9616 // the result back to FR32 register. It's only worth matching if the
9617 // result has a single use which is a store or a bitcast to i32. And in
9618 // the case of a store, it's not worth it if the index is a constant 0,
9619 // because a MOVSSmr can be used instead, which is smaller and faster.
9620 if (!Op.hasOneUse())
9622 SDNode *User = *Op.getNode()->use_begin();
9623 if ((User->getOpcode() != ISD::STORE ||
9624 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9625 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9626 (User->getOpcode() != ISD::BITCAST ||
9627 User->getValueType(0) != MVT::i32))
9629 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9630 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9633 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9636 if (VT == MVT::i32 || VT == MVT::i64) {
9637 // ExtractPS/pextrq works with constant index.
9638 if (isa<ConstantSDNode>(Op.getOperand(1)))
9644 /// Extract one bit from mask vector, like v16i1 or v8i1.
9645 /// AVX-512 feature.
9647 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9648 SDValue Vec = Op.getOperand(0);
9650 MVT VecVT = Vec.getSimpleValueType();
9651 SDValue Idx = Op.getOperand(1);
9652 MVT EltVT = Op.getSimpleValueType();
9654 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9656 // variable index can't be handled in mask registers,
9657 // extend vector to VR512
9658 if (!isa<ConstantSDNode>(Idx)) {
9659 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9660 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9661 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9662 ExtVT.getVectorElementType(), Ext, Idx);
9663 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9666 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9667 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9668 unsigned MaxSift = rc->getSize()*8 - 1;
9669 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9670 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9671 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9672 DAG.getConstant(MaxSift, MVT::i8));
9673 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9674 DAG.getIntPtrConstant(0));
9678 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9679 SelectionDAG &DAG) const {
9681 SDValue Vec = Op.getOperand(0);
9682 MVT VecVT = Vec.getSimpleValueType();
9683 SDValue Idx = Op.getOperand(1);
9685 if (Op.getSimpleValueType() == MVT::i1)
9686 return ExtractBitFromMaskVector(Op, DAG);
9688 if (!isa<ConstantSDNode>(Idx)) {
9689 if (VecVT.is512BitVector() ||
9690 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9691 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9694 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9695 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9696 MaskEltVT.getSizeInBits());
9698 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9699 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9700 getZeroVector(MaskVT, Subtarget, DAG, dl),
9701 Idx, DAG.getConstant(0, getPointerTy()));
9702 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9703 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9704 Perm, DAG.getConstant(0, getPointerTy()));
9709 // If this is a 256-bit vector result, first extract the 128-bit vector and
9710 // then extract the element from the 128-bit vector.
9711 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9713 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9714 // Get the 128-bit vector.
9715 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9716 MVT EltVT = VecVT.getVectorElementType();
9718 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9720 //if (IdxVal >= NumElems/2)
9721 // IdxVal -= NumElems/2;
9722 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9723 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9724 DAG.getConstant(IdxVal, MVT::i32));
9727 assert(VecVT.is128BitVector() && "Unexpected vector length");
9729 if (Subtarget->hasSSE41()) {
9730 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9735 MVT VT = Op.getSimpleValueType();
9736 // TODO: handle v16i8.
9737 if (VT.getSizeInBits() == 16) {
9738 SDValue Vec = Op.getOperand(0);
9739 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9741 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9742 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9743 DAG.getNode(ISD::BITCAST, dl,
9746 // Transform it so it match pextrw which produces a 32-bit result.
9747 MVT EltVT = MVT::i32;
9748 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9749 Op.getOperand(0), Op.getOperand(1));
9750 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9751 DAG.getValueType(VT));
9752 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9755 if (VT.getSizeInBits() == 32) {
9756 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9760 // SHUFPS the element to the lowest double word, then movss.
9761 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9762 MVT VVT = Op.getOperand(0).getSimpleValueType();
9763 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9764 DAG.getUNDEF(VVT), Mask);
9765 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9766 DAG.getIntPtrConstant(0));
9769 if (VT.getSizeInBits() == 64) {
9770 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9771 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9772 // to match extract_elt for f64.
9773 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9777 // UNPCKHPD the element to the lowest double word, then movsd.
9778 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9779 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9780 int Mask[2] = { 1, -1 };
9781 MVT VVT = Op.getOperand(0).getSimpleValueType();
9782 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9783 DAG.getUNDEF(VVT), Mask);
9784 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9785 DAG.getIntPtrConstant(0));
9791 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9792 MVT VT = Op.getSimpleValueType();
9793 MVT EltVT = VT.getVectorElementType();
9796 SDValue N0 = Op.getOperand(0);
9797 SDValue N1 = Op.getOperand(1);
9798 SDValue N2 = Op.getOperand(2);
9800 if (!VT.is128BitVector())
9803 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9804 isa<ConstantSDNode>(N2)) {
9806 if (VT == MVT::v8i16)
9807 Opc = X86ISD::PINSRW;
9808 else if (VT == MVT::v16i8)
9809 Opc = X86ISD::PINSRB;
9811 Opc = X86ISD::PINSRB;
9813 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9815 if (N1.getValueType() != MVT::i32)
9816 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9817 if (N2.getValueType() != MVT::i32)
9818 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9819 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9822 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9823 // Bits [7:6] of the constant are the source select. This will always be
9824 // zero here. The DAG Combiner may combine an extract_elt index into these
9825 // bits. For example (insert (extract, 3), 2) could be matched by putting
9826 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9827 // Bits [5:4] of the constant are the destination select. This is the
9828 // value of the incoming immediate.
9829 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9830 // combine either bitwise AND or insert of float 0.0 to set these bits.
9831 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9832 // Create this as a scalar to vector..
9833 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9834 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9837 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9838 // PINSR* works with constant index.
9844 /// Insert one bit to mask vector, like v16i1 or v8i1.
9845 /// AVX-512 feature.
9847 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9849 SDValue Vec = Op.getOperand(0);
9850 SDValue Elt = Op.getOperand(1);
9851 SDValue Idx = Op.getOperand(2);
9852 MVT VecVT = Vec.getSimpleValueType();
9854 if (!isa<ConstantSDNode>(Idx)) {
9855 // Non constant index. Extend source and destination,
9856 // insert element and then truncate the result.
9857 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9858 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
9859 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
9860 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9861 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9862 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9865 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9866 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9867 if (Vec.getOpcode() == ISD::UNDEF)
9868 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9869 DAG.getConstant(IdxVal, MVT::i8));
9870 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9871 unsigned MaxSift = rc->getSize()*8 - 1;
9872 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9873 DAG.getConstant(MaxSift, MVT::i8));
9874 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9875 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9876 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9879 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9880 MVT VT = Op.getSimpleValueType();
9881 MVT EltVT = VT.getVectorElementType();
9883 if (EltVT == MVT::i1)
9884 return InsertBitToMaskVector(Op, DAG);
9887 SDValue N0 = Op.getOperand(0);
9888 SDValue N1 = Op.getOperand(1);
9889 SDValue N2 = Op.getOperand(2);
9891 // If this is a 256-bit vector result, first extract the 128-bit vector,
9892 // insert the element into the extracted half and then place it back.
9893 if (VT.is256BitVector() || VT.is512BitVector()) {
9894 if (!isa<ConstantSDNode>(N2))
9897 // Get the desired 128-bit vector half.
9898 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9899 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9901 // Insert the element into the desired half.
9902 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9903 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9905 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9906 DAG.getConstant(IdxIn128, MVT::i32));
9908 // Insert the changed part back to the 256-bit vector
9909 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9912 if (Subtarget->hasSSE41())
9913 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9915 if (EltVT == MVT::i8)
9918 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
9919 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
9920 // as its second argument.
9921 if (N1.getValueType() != MVT::i32)
9922 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9923 if (N2.getValueType() != MVT::i32)
9924 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9925 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
9930 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
9932 MVT OpVT = Op.getSimpleValueType();
9934 // If this is a 256-bit vector result, first insert into a 128-bit
9935 // vector and then insert into the 256-bit vector.
9936 if (!OpVT.is128BitVector()) {
9937 // Insert into a 128-bit vector.
9938 unsigned SizeFactor = OpVT.getSizeInBits()/128;
9939 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
9940 OpVT.getVectorNumElements() / SizeFactor);
9942 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
9944 // Insert the 128-bit vector.
9945 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
9948 if (OpVT == MVT::v1i64 &&
9949 Op.getOperand(0).getValueType() == MVT::i64)
9950 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
9952 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
9953 assert(OpVT.is128BitVector() && "Expected an SSE type!");
9954 return DAG.getNode(ISD::BITCAST, dl, OpVT,
9955 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
9958 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
9959 // a simple subregister reference or explicit instructions to grab
9960 // upper bits of a vector.
9961 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
9962 SelectionDAG &DAG) {
9964 SDValue In = Op.getOperand(0);
9965 SDValue Idx = Op.getOperand(1);
9966 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9967 MVT ResVT = Op.getSimpleValueType();
9968 MVT InVT = In.getSimpleValueType();
9970 if (Subtarget->hasFp256()) {
9971 if (ResVT.is128BitVector() &&
9972 (InVT.is256BitVector() || InVT.is512BitVector()) &&
9973 isa<ConstantSDNode>(Idx)) {
9974 return Extract128BitVector(In, IdxVal, DAG, dl);
9976 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
9977 isa<ConstantSDNode>(Idx)) {
9978 return Extract256BitVector(In, IdxVal, DAG, dl);
9984 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
9985 // simple superregister reference or explicit instructions to insert
9986 // the upper bits of a vector.
9987 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
9988 SelectionDAG &DAG) {
9989 if (Subtarget->hasFp256()) {
9990 SDLoc dl(Op.getNode());
9991 SDValue Vec = Op.getNode()->getOperand(0);
9992 SDValue SubVec = Op.getNode()->getOperand(1);
9993 SDValue Idx = Op.getNode()->getOperand(2);
9995 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
9996 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
9997 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
9998 isa<ConstantSDNode>(Idx)) {
9999 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10000 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10003 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10004 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10005 isa<ConstantSDNode>(Idx)) {
10006 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10007 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10013 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10014 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10015 // one of the above mentioned nodes. It has to be wrapped because otherwise
10016 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10017 // be used to form addressing mode. These wrapped nodes will be selected
10020 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10021 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10023 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10024 // global base reg.
10025 unsigned char OpFlag = 0;
10026 unsigned WrapperKind = X86ISD::Wrapper;
10027 CodeModel::Model M = DAG.getTarget().getCodeModel();
10029 if (Subtarget->isPICStyleRIPRel() &&
10030 (M == CodeModel::Small || M == CodeModel::Kernel))
10031 WrapperKind = X86ISD::WrapperRIP;
10032 else if (Subtarget->isPICStyleGOT())
10033 OpFlag = X86II::MO_GOTOFF;
10034 else if (Subtarget->isPICStyleStubPIC())
10035 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10037 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10038 CP->getAlignment(),
10039 CP->getOffset(), OpFlag);
10041 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10042 // With PIC, the address is actually $g + Offset.
10044 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10045 DAG.getNode(X86ISD::GlobalBaseReg,
10046 SDLoc(), getPointerTy()),
10053 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10054 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10056 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10057 // global base reg.
10058 unsigned char OpFlag = 0;
10059 unsigned WrapperKind = X86ISD::Wrapper;
10060 CodeModel::Model M = DAG.getTarget().getCodeModel();
10062 if (Subtarget->isPICStyleRIPRel() &&
10063 (M == CodeModel::Small || M == CodeModel::Kernel))
10064 WrapperKind = X86ISD::WrapperRIP;
10065 else if (Subtarget->isPICStyleGOT())
10066 OpFlag = X86II::MO_GOTOFF;
10067 else if (Subtarget->isPICStyleStubPIC())
10068 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10070 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10073 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10075 // With PIC, the address is actually $g + Offset.
10077 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10078 DAG.getNode(X86ISD::GlobalBaseReg,
10079 SDLoc(), getPointerTy()),
10086 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10087 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10089 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10090 // global base reg.
10091 unsigned char OpFlag = 0;
10092 unsigned WrapperKind = X86ISD::Wrapper;
10093 CodeModel::Model M = DAG.getTarget().getCodeModel();
10095 if (Subtarget->isPICStyleRIPRel() &&
10096 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10097 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10098 OpFlag = X86II::MO_GOTPCREL;
10099 WrapperKind = X86ISD::WrapperRIP;
10100 } else if (Subtarget->isPICStyleGOT()) {
10101 OpFlag = X86II::MO_GOT;
10102 } else if (Subtarget->isPICStyleStubPIC()) {
10103 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10104 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10105 OpFlag = X86II::MO_DARWIN_NONLAZY;
10108 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10111 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10113 // With PIC, the address is actually $g + Offset.
10114 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10115 !Subtarget->is64Bit()) {
10116 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10117 DAG.getNode(X86ISD::GlobalBaseReg,
10118 SDLoc(), getPointerTy()),
10122 // For symbols that require a load from a stub to get the address, emit the
10124 if (isGlobalStubReference(OpFlag))
10125 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10126 MachinePointerInfo::getGOT(), false, false, false, 0);
10132 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10133 // Create the TargetBlockAddressAddress node.
10134 unsigned char OpFlags =
10135 Subtarget->ClassifyBlockAddressReference();
10136 CodeModel::Model M = DAG.getTarget().getCodeModel();
10137 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10138 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10140 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10143 if (Subtarget->isPICStyleRIPRel() &&
10144 (M == CodeModel::Small || M == CodeModel::Kernel))
10145 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10147 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10149 // With PIC, the address is actually $g + Offset.
10150 if (isGlobalRelativeToPICBase(OpFlags)) {
10151 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10152 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10160 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10161 int64_t Offset, SelectionDAG &DAG) const {
10162 // Create the TargetGlobalAddress node, folding in the constant
10163 // offset if it is legal.
10164 unsigned char OpFlags =
10165 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10166 CodeModel::Model M = DAG.getTarget().getCodeModel();
10168 if (OpFlags == X86II::MO_NO_FLAG &&
10169 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10170 // A direct static reference to a global.
10171 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10174 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10177 if (Subtarget->isPICStyleRIPRel() &&
10178 (M == CodeModel::Small || M == CodeModel::Kernel))
10179 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10181 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10183 // With PIC, the address is actually $g + Offset.
10184 if (isGlobalRelativeToPICBase(OpFlags)) {
10185 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10186 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10190 // For globals that require a load from a stub to get the address, emit the
10192 if (isGlobalStubReference(OpFlags))
10193 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10194 MachinePointerInfo::getGOT(), false, false, false, 0);
10196 // If there was a non-zero offset that we didn't fold, create an explicit
10197 // addition for it.
10199 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10200 DAG.getConstant(Offset, getPointerTy()));
10206 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10207 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10208 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10209 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10213 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10214 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10215 unsigned char OperandFlags, bool LocalDynamic = false) {
10216 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10217 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10219 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10220 GA->getValueType(0),
10224 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10228 SDValue Ops[] = { Chain, TGA, *InFlag };
10229 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10231 SDValue Ops[] = { Chain, TGA };
10232 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10235 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10236 MFI->setAdjustsStack(true);
10238 SDValue Flag = Chain.getValue(1);
10239 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10242 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10244 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10247 SDLoc dl(GA); // ? function entry point might be better
10248 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10249 DAG.getNode(X86ISD::GlobalBaseReg,
10250 SDLoc(), PtrVT), InFlag);
10251 InFlag = Chain.getValue(1);
10253 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10256 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10258 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10260 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10261 X86::RAX, X86II::MO_TLSGD);
10264 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10270 // Get the start address of the TLS block for this module.
10271 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10272 .getInfo<X86MachineFunctionInfo>();
10273 MFI->incNumLocalDynamicTLSAccesses();
10277 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10278 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10281 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10282 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10283 InFlag = Chain.getValue(1);
10284 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10285 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10288 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10292 unsigned char OperandFlags = X86II::MO_DTPOFF;
10293 unsigned WrapperKind = X86ISD::Wrapper;
10294 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10295 GA->getValueType(0),
10296 GA->getOffset(), OperandFlags);
10297 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10299 // Add x@dtpoff with the base.
10300 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10303 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10304 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10305 const EVT PtrVT, TLSModel::Model model,
10306 bool is64Bit, bool isPIC) {
10309 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10310 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10311 is64Bit ? 257 : 256));
10313 SDValue ThreadPointer =
10314 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10315 MachinePointerInfo(Ptr), false, false, false, 0);
10317 unsigned char OperandFlags = 0;
10318 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10320 unsigned WrapperKind = X86ISD::Wrapper;
10321 if (model == TLSModel::LocalExec) {
10322 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10323 } else if (model == TLSModel::InitialExec) {
10325 OperandFlags = X86II::MO_GOTTPOFF;
10326 WrapperKind = X86ISD::WrapperRIP;
10328 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10331 llvm_unreachable("Unexpected model");
10334 // emit "addl x@ntpoff,%eax" (local exec)
10335 // or "addl x@indntpoff,%eax" (initial exec)
10336 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10338 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10339 GA->getOffset(), OperandFlags);
10340 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10342 if (model == TLSModel::InitialExec) {
10343 if (isPIC && !is64Bit) {
10344 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10345 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10349 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10350 MachinePointerInfo::getGOT(), false, false, false, 0);
10353 // The address of the thread local variable is the add of the thread
10354 // pointer with the offset of the variable.
10355 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10359 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10361 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10362 const GlobalValue *GV = GA->getGlobal();
10364 if (Subtarget->isTargetELF()) {
10365 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10368 case TLSModel::GeneralDynamic:
10369 if (Subtarget->is64Bit())
10370 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10371 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10372 case TLSModel::LocalDynamic:
10373 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10374 Subtarget->is64Bit());
10375 case TLSModel::InitialExec:
10376 case TLSModel::LocalExec:
10377 return LowerToTLSExecModel(
10378 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10379 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10381 llvm_unreachable("Unknown TLS model.");
10384 if (Subtarget->isTargetDarwin()) {
10385 // Darwin only has one model of TLS. Lower to that.
10386 unsigned char OpFlag = 0;
10387 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10388 X86ISD::WrapperRIP : X86ISD::Wrapper;
10390 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10391 // global base reg.
10392 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10393 !Subtarget->is64Bit();
10395 OpFlag = X86II::MO_TLVP_PIC_BASE;
10397 OpFlag = X86II::MO_TLVP;
10399 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10400 GA->getValueType(0),
10401 GA->getOffset(), OpFlag);
10402 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10404 // With PIC32, the address is actually $g + Offset.
10406 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10407 DAG.getNode(X86ISD::GlobalBaseReg,
10408 SDLoc(), getPointerTy()),
10411 // Lowering the machine isd will make sure everything is in the right
10413 SDValue Chain = DAG.getEntryNode();
10414 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10415 SDValue Args[] = { Chain, Offset };
10416 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10418 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10419 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10420 MFI->setAdjustsStack(true);
10422 // And our return value (tls address) is in the standard call return value
10424 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10425 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10426 Chain.getValue(1));
10429 if (Subtarget->isTargetKnownWindowsMSVC() ||
10430 Subtarget->isTargetWindowsGNU()) {
10431 // Just use the implicit TLS architecture
10432 // Need to generate someting similar to:
10433 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10435 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10436 // mov rcx, qword [rdx+rcx*8]
10437 // mov eax, .tls$:tlsvar
10438 // [rax+rcx] contains the address
10439 // Windows 64bit: gs:0x58
10440 // Windows 32bit: fs:__tls_array
10443 SDValue Chain = DAG.getEntryNode();
10445 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10446 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10447 // use its literal value of 0x2C.
10448 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10449 ? Type::getInt8PtrTy(*DAG.getContext(),
10451 : Type::getInt32PtrTy(*DAG.getContext(),
10455 Subtarget->is64Bit()
10456 ? DAG.getIntPtrConstant(0x58)
10457 : (Subtarget->isTargetWindowsGNU()
10458 ? DAG.getIntPtrConstant(0x2C)
10459 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10461 SDValue ThreadPointer =
10462 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10463 MachinePointerInfo(Ptr), false, false, false, 0);
10465 // Load the _tls_index variable
10466 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10467 if (Subtarget->is64Bit())
10468 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10469 IDX, MachinePointerInfo(), MVT::i32,
10472 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10473 false, false, false, 0);
10475 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10477 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10479 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10480 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10481 false, false, false, 0);
10483 // Get the offset of start of .tls section
10484 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10485 GA->getValueType(0),
10486 GA->getOffset(), X86II::MO_SECREL);
10487 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10489 // The address of the thread local variable is the add of the thread
10490 // pointer with the offset of the variable.
10491 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10494 llvm_unreachable("TLS not implemented for this target.");
10497 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10498 /// and take a 2 x i32 value to shift plus a shift amount.
10499 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10500 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10501 MVT VT = Op.getSimpleValueType();
10502 unsigned VTBits = VT.getSizeInBits();
10504 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10505 SDValue ShOpLo = Op.getOperand(0);
10506 SDValue ShOpHi = Op.getOperand(1);
10507 SDValue ShAmt = Op.getOperand(2);
10508 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10509 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10511 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10512 DAG.getConstant(VTBits - 1, MVT::i8));
10513 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10514 DAG.getConstant(VTBits - 1, MVT::i8))
10515 : DAG.getConstant(0, VT);
10517 SDValue Tmp2, Tmp3;
10518 if (Op.getOpcode() == ISD::SHL_PARTS) {
10519 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10520 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10522 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10523 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10526 // If the shift amount is larger or equal than the width of a part we can't
10527 // rely on the results of shld/shrd. Insert a test and select the appropriate
10528 // values for large shift amounts.
10529 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10530 DAG.getConstant(VTBits, MVT::i8));
10531 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10532 AndNode, DAG.getConstant(0, MVT::i8));
10535 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10536 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10537 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10539 if (Op.getOpcode() == ISD::SHL_PARTS) {
10540 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10541 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10543 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10544 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10547 SDValue Ops[2] = { Lo, Hi };
10548 return DAG.getMergeValues(Ops, dl);
10551 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10552 SelectionDAG &DAG) const {
10553 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10555 if (SrcVT.isVector())
10558 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10559 "Unknown SINT_TO_FP to lower!");
10561 // These are really Legal; return the operand so the caller accepts it as
10563 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10565 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10566 Subtarget->is64Bit()) {
10571 unsigned Size = SrcVT.getSizeInBits()/8;
10572 MachineFunction &MF = DAG.getMachineFunction();
10573 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10574 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10575 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10577 MachinePointerInfo::getFixedStack(SSFI),
10579 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10582 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10584 SelectionDAG &DAG) const {
10588 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10590 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10592 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10594 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10596 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10597 MachineMemOperand *MMO;
10599 int SSFI = FI->getIndex();
10601 DAG.getMachineFunction()
10602 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10603 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10605 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10606 StackSlot = StackSlot.getOperand(1);
10608 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10609 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10611 Tys, Ops, SrcVT, MMO);
10614 Chain = Result.getValue(1);
10615 SDValue InFlag = Result.getValue(2);
10617 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10618 // shouldn't be necessary except that RFP cannot be live across
10619 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10620 MachineFunction &MF = DAG.getMachineFunction();
10621 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10622 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10623 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10624 Tys = DAG.getVTList(MVT::Other);
10626 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10628 MachineMemOperand *MMO =
10629 DAG.getMachineFunction()
10630 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10631 MachineMemOperand::MOStore, SSFISize, SSFISize);
10633 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10634 Ops, Op.getValueType(), MMO);
10635 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10636 MachinePointerInfo::getFixedStack(SSFI),
10637 false, false, false, 0);
10643 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10644 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10645 SelectionDAG &DAG) const {
10646 // This algorithm is not obvious. Here it is what we're trying to output:
10649 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10650 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10652 haddpd %xmm0, %xmm0
10654 pshufd $0x4e, %xmm0, %xmm1
10660 LLVMContext *Context = DAG.getContext();
10662 // Build some magic constants.
10663 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10664 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10665 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10667 SmallVector<Constant*,2> CV1;
10669 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10670 APInt(64, 0x4330000000000000ULL))));
10672 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10673 APInt(64, 0x4530000000000000ULL))));
10674 Constant *C1 = ConstantVector::get(CV1);
10675 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10677 // Load the 64-bit value into an XMM register.
10678 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10680 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10681 MachinePointerInfo::getConstantPool(),
10682 false, false, false, 16);
10683 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10684 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10687 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10688 MachinePointerInfo::getConstantPool(),
10689 false, false, false, 16);
10690 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10691 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10694 if (Subtarget->hasSSE3()) {
10695 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10696 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10698 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10699 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10701 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10702 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10706 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10707 DAG.getIntPtrConstant(0));
10710 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10711 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10712 SelectionDAG &DAG) const {
10714 // FP constant to bias correct the final result.
10715 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10718 // Load the 32-bit value into an XMM register.
10719 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10722 // Zero out the upper parts of the register.
10723 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10725 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10726 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10727 DAG.getIntPtrConstant(0));
10729 // Or the load with the bias.
10730 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10731 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10732 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10733 MVT::v2f64, Load)),
10734 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10735 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10736 MVT::v2f64, Bias)));
10737 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10738 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10739 DAG.getIntPtrConstant(0));
10741 // Subtract the bias.
10742 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10744 // Handle final rounding.
10745 EVT DestVT = Op.getValueType();
10747 if (DestVT.bitsLT(MVT::f64))
10748 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10749 DAG.getIntPtrConstant(0));
10750 if (DestVT.bitsGT(MVT::f64))
10751 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10753 // Handle final rounding.
10757 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10758 SelectionDAG &DAG) const {
10759 SDValue N0 = Op.getOperand(0);
10760 MVT SVT = N0.getSimpleValueType();
10763 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10764 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10765 "Custom UINT_TO_FP is not supported!");
10767 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10768 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10769 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10772 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10773 SelectionDAG &DAG) const {
10774 SDValue N0 = Op.getOperand(0);
10777 if (Op.getValueType().isVector())
10778 return lowerUINT_TO_FP_vec(Op, DAG);
10780 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10781 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10782 // the optimization here.
10783 if (DAG.SignBitIsZero(N0))
10784 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10786 MVT SrcVT = N0.getSimpleValueType();
10787 MVT DstVT = Op.getSimpleValueType();
10788 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10789 return LowerUINT_TO_FP_i64(Op, DAG);
10790 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10791 return LowerUINT_TO_FP_i32(Op, DAG);
10792 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10795 // Make a 64-bit buffer, and use it to build an FILD.
10796 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10797 if (SrcVT == MVT::i32) {
10798 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10799 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10800 getPointerTy(), StackSlot, WordOff);
10801 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10802 StackSlot, MachinePointerInfo(),
10804 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10805 OffsetSlot, MachinePointerInfo(),
10807 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10811 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10812 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10813 StackSlot, MachinePointerInfo(),
10815 // For i64 source, we need to add the appropriate power of 2 if the input
10816 // was negative. This is the same as the optimization in
10817 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10818 // we must be careful to do the computation in x87 extended precision, not
10819 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10820 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10821 MachineMemOperand *MMO =
10822 DAG.getMachineFunction()
10823 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10824 MachineMemOperand::MOLoad, 8, 8);
10826 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10827 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10828 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10831 APInt FF(32, 0x5F800000ULL);
10833 // Check whether the sign bit is set.
10834 SDValue SignSet = DAG.getSetCC(dl,
10835 getSetCCResultType(*DAG.getContext(), MVT::i64),
10836 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10839 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10840 SDValue FudgePtr = DAG.getConstantPool(
10841 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10844 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10845 SDValue Zero = DAG.getIntPtrConstant(0);
10846 SDValue Four = DAG.getIntPtrConstant(4);
10847 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10849 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10851 // Load the value out, extending it from f32 to f80.
10852 // FIXME: Avoid the extend by constructing the right constant pool?
10853 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10854 FudgePtr, MachinePointerInfo::getConstantPool(),
10855 MVT::f32, false, false, 4);
10856 // Extend everything to 80 bits to force it to be done on x87.
10857 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10858 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10861 std::pair<SDValue,SDValue>
10862 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10863 bool IsSigned, bool IsReplace) const {
10866 EVT DstTy = Op.getValueType();
10868 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10869 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10873 assert(DstTy.getSimpleVT() <= MVT::i64 &&
10874 DstTy.getSimpleVT() >= MVT::i16 &&
10875 "Unknown FP_TO_INT to lower!");
10877 // These are really Legal.
10878 if (DstTy == MVT::i32 &&
10879 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10880 return std::make_pair(SDValue(), SDValue());
10881 if (Subtarget->is64Bit() &&
10882 DstTy == MVT::i64 &&
10883 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10884 return std::make_pair(SDValue(), SDValue());
10886 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10887 // stack slot, or into the FTOL runtime function.
10888 MachineFunction &MF = DAG.getMachineFunction();
10889 unsigned MemSize = DstTy.getSizeInBits()/8;
10890 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10891 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10894 if (!IsSigned && isIntegerTypeFTOL(DstTy))
10895 Opc = X86ISD::WIN_FTOL;
10897 switch (DstTy.getSimpleVT().SimpleTy) {
10898 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10899 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10900 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10901 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10904 SDValue Chain = DAG.getEntryNode();
10905 SDValue Value = Op.getOperand(0);
10906 EVT TheVT = Op.getOperand(0).getValueType();
10907 // FIXME This causes a redundant load/store if the SSE-class value is already
10908 // in memory, such as if it is on the callstack.
10909 if (isScalarFPTypeInSSEReg(TheVT)) {
10910 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10911 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10912 MachinePointerInfo::getFixedStack(SSFI),
10914 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10916 Chain, StackSlot, DAG.getValueType(TheVT)
10919 MachineMemOperand *MMO =
10920 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10921 MachineMemOperand::MOLoad, MemSize, MemSize);
10922 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
10923 Chain = Value.getValue(1);
10924 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10925 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10928 MachineMemOperand *MMO =
10929 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10930 MachineMemOperand::MOStore, MemSize, MemSize);
10932 if (Opc != X86ISD::WIN_FTOL) {
10933 // Build the FP_TO_INT*_IN_MEM
10934 SDValue Ops[] = { Chain, Value, StackSlot };
10935 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
10937 return std::make_pair(FIST, StackSlot);
10939 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
10940 DAG.getVTList(MVT::Other, MVT::Glue),
10942 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
10943 MVT::i32, ftol.getValue(1));
10944 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
10945 MVT::i32, eax.getValue(2));
10946 SDValue Ops[] = { eax, edx };
10947 SDValue pair = IsReplace
10948 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
10949 : DAG.getMergeValues(Ops, DL);
10950 return std::make_pair(pair, SDValue());
10954 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
10955 const X86Subtarget *Subtarget) {
10956 MVT VT = Op->getSimpleValueType(0);
10957 SDValue In = Op->getOperand(0);
10958 MVT InVT = In.getSimpleValueType();
10961 // Optimize vectors in AVX mode:
10964 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
10965 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
10966 // Concat upper and lower parts.
10969 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
10970 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
10971 // Concat upper and lower parts.
10974 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
10975 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
10976 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
10979 if (Subtarget->hasInt256())
10980 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
10982 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
10983 SDValue Undef = DAG.getUNDEF(InVT);
10984 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
10985 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
10986 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
10988 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
10989 VT.getVectorNumElements()/2);
10991 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
10992 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
10994 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10997 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
10998 SelectionDAG &DAG) {
10999 MVT VT = Op->getSimpleValueType(0);
11000 SDValue In = Op->getOperand(0);
11001 MVT InVT = In.getSimpleValueType();
11003 unsigned int NumElts = VT.getVectorNumElements();
11004 if (NumElts != 8 && NumElts != 16)
11007 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11008 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11010 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11011 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11012 // Now we have only mask extension
11013 assert(InVT.getVectorElementType() == MVT::i1);
11014 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11015 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11016 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11017 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11018 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11019 MachinePointerInfo::getConstantPool(),
11020 false, false, false, Alignment);
11022 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11023 if (VT.is512BitVector())
11025 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11028 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11029 SelectionDAG &DAG) {
11030 if (Subtarget->hasFp256()) {
11031 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11039 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11040 SelectionDAG &DAG) {
11042 MVT VT = Op.getSimpleValueType();
11043 SDValue In = Op.getOperand(0);
11044 MVT SVT = In.getSimpleValueType();
11046 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11047 return LowerZERO_EXTEND_AVX512(Op, DAG);
11049 if (Subtarget->hasFp256()) {
11050 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11055 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11056 VT.getVectorNumElements() != SVT.getVectorNumElements());
11060 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11062 MVT VT = Op.getSimpleValueType();
11063 SDValue In = Op.getOperand(0);
11064 MVT InVT = In.getSimpleValueType();
11066 if (VT == MVT::i1) {
11067 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11068 "Invalid scalar TRUNCATE operation");
11069 if (InVT == MVT::i32)
11071 if (InVT.getSizeInBits() == 64)
11072 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11073 else if (InVT.getSizeInBits() < 32)
11074 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11075 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11077 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11078 "Invalid TRUNCATE operation");
11080 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11081 if (VT.getVectorElementType().getSizeInBits() >=8)
11082 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11084 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11085 unsigned NumElts = InVT.getVectorNumElements();
11086 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11087 if (InVT.getSizeInBits() < 512) {
11088 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11089 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11093 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11094 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11095 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11096 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11097 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11098 MachinePointerInfo::getConstantPool(),
11099 false, false, false, Alignment);
11100 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11101 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11102 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11105 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11106 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11107 if (Subtarget->hasInt256()) {
11108 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11109 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11110 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11112 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11113 DAG.getIntPtrConstant(0));
11116 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11117 DAG.getIntPtrConstant(0));
11118 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11119 DAG.getIntPtrConstant(2));
11120 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11121 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11122 static const int ShufMask[] = {0, 2, 4, 6};
11123 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11126 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11127 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11128 if (Subtarget->hasInt256()) {
11129 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11131 SmallVector<SDValue,32> pshufbMask;
11132 for (unsigned i = 0; i < 2; ++i) {
11133 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11134 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11135 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11136 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11137 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11138 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11139 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11140 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11141 for (unsigned j = 0; j < 8; ++j)
11142 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11144 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11145 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11146 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11148 static const int ShufMask[] = {0, 2, -1, -1};
11149 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11151 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11152 DAG.getIntPtrConstant(0));
11153 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11156 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11157 DAG.getIntPtrConstant(0));
11159 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11160 DAG.getIntPtrConstant(4));
11162 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11163 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11165 // The PSHUFB mask:
11166 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11167 -1, -1, -1, -1, -1, -1, -1, -1};
11169 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11170 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11171 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11173 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11174 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11176 // The MOVLHPS Mask:
11177 static const int ShufMask2[] = {0, 1, 4, 5};
11178 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11179 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11182 // Handle truncation of V256 to V128 using shuffles.
11183 if (!VT.is128BitVector() || !InVT.is256BitVector())
11186 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11188 unsigned NumElems = VT.getVectorNumElements();
11189 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11191 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11192 // Prepare truncation shuffle mask
11193 for (unsigned i = 0; i != NumElems; ++i)
11194 MaskVec[i] = i * 2;
11195 SDValue V = DAG.getVectorShuffle(NVT, DL,
11196 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11197 DAG.getUNDEF(NVT), &MaskVec[0]);
11198 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11199 DAG.getIntPtrConstant(0));
11202 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11203 SelectionDAG &DAG) const {
11204 assert(!Op.getSimpleValueType().isVector());
11206 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11207 /*IsSigned=*/ true, /*IsReplace=*/ false);
11208 SDValue FIST = Vals.first, StackSlot = Vals.second;
11209 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11210 if (!FIST.getNode()) return Op;
11212 if (StackSlot.getNode())
11213 // Load the result.
11214 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11215 FIST, StackSlot, MachinePointerInfo(),
11216 false, false, false, 0);
11218 // The node is the result.
11222 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11223 SelectionDAG &DAG) const {
11224 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11225 /*IsSigned=*/ false, /*IsReplace=*/ false);
11226 SDValue FIST = Vals.first, StackSlot = Vals.second;
11227 assert(FIST.getNode() && "Unexpected failure");
11229 if (StackSlot.getNode())
11230 // Load the result.
11231 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11232 FIST, StackSlot, MachinePointerInfo(),
11233 false, false, false, 0);
11235 // The node is the result.
11239 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11241 MVT VT = Op.getSimpleValueType();
11242 SDValue In = Op.getOperand(0);
11243 MVT SVT = In.getSimpleValueType();
11245 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11247 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11248 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11249 In, DAG.getUNDEF(SVT)));
11252 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11253 LLVMContext *Context = DAG.getContext();
11255 MVT VT = Op.getSimpleValueType();
11257 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11258 if (VT.isVector()) {
11259 EltVT = VT.getVectorElementType();
11260 NumElts = VT.getVectorNumElements();
11263 if (EltVT == MVT::f64)
11264 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11265 APInt(64, ~(1ULL << 63))));
11267 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11268 APInt(32, ~(1U << 31))));
11269 C = ConstantVector::getSplat(NumElts, C);
11270 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11271 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11272 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11273 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11274 MachinePointerInfo::getConstantPool(),
11275 false, false, false, Alignment);
11276 if (VT.isVector()) {
11277 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11278 return DAG.getNode(ISD::BITCAST, dl, VT,
11279 DAG.getNode(ISD::AND, dl, ANDVT,
11280 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11282 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11284 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11287 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11288 LLVMContext *Context = DAG.getContext();
11290 MVT VT = Op.getSimpleValueType();
11292 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11293 if (VT.isVector()) {
11294 EltVT = VT.getVectorElementType();
11295 NumElts = VT.getVectorNumElements();
11298 if (EltVT == MVT::f64)
11299 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11300 APInt(64, 1ULL << 63)));
11302 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11303 APInt(32, 1U << 31)));
11304 C = ConstantVector::getSplat(NumElts, C);
11305 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11306 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11307 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11308 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11309 MachinePointerInfo::getConstantPool(),
11310 false, false, false, Alignment);
11311 if (VT.isVector()) {
11312 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11313 return DAG.getNode(ISD::BITCAST, dl, VT,
11314 DAG.getNode(ISD::XOR, dl, XORVT,
11315 DAG.getNode(ISD::BITCAST, dl, XORVT,
11317 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11320 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11323 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11325 LLVMContext *Context = DAG.getContext();
11326 SDValue Op0 = Op.getOperand(0);
11327 SDValue Op1 = Op.getOperand(1);
11329 MVT VT = Op.getSimpleValueType();
11330 MVT SrcVT = Op1.getSimpleValueType();
11332 // If second operand is smaller, extend it first.
11333 if (SrcVT.bitsLT(VT)) {
11334 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11337 // And if it is bigger, shrink it first.
11338 if (SrcVT.bitsGT(VT)) {
11339 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11343 // At this point the operands and the result should have the same
11344 // type, and that won't be f80 since that is not custom lowered.
11346 // First get the sign bit of second operand.
11347 SmallVector<Constant*,4> CV;
11348 if (SrcVT == MVT::f64) {
11349 const fltSemantics &Sem = APFloat::IEEEdouble;
11350 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11351 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11353 const fltSemantics &Sem = APFloat::IEEEsingle;
11354 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11355 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11356 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11357 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11359 Constant *C = ConstantVector::get(CV);
11360 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11361 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11362 MachinePointerInfo::getConstantPool(),
11363 false, false, false, 16);
11364 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11366 // Shift sign bit right or left if the two operands have different types.
11367 if (SrcVT.bitsGT(VT)) {
11368 // Op0 is MVT::f32, Op1 is MVT::f64.
11369 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11370 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11371 DAG.getConstant(32, MVT::i32));
11372 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11373 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11374 DAG.getIntPtrConstant(0));
11377 // Clear first operand sign bit.
11379 if (VT == MVT::f64) {
11380 const fltSemantics &Sem = APFloat::IEEEdouble;
11381 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11382 APInt(64, ~(1ULL << 63)))));
11383 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11385 const fltSemantics &Sem = APFloat::IEEEsingle;
11386 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11387 APInt(32, ~(1U << 31)))));
11388 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11389 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11390 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11392 C = ConstantVector::get(CV);
11393 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11394 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11395 MachinePointerInfo::getConstantPool(),
11396 false, false, false, 16);
11397 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11399 // Or the value with the sign bit.
11400 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11403 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11404 SDValue N0 = Op.getOperand(0);
11406 MVT VT = Op.getSimpleValueType();
11408 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11409 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11410 DAG.getConstant(1, VT));
11411 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11414 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11416 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11417 SelectionDAG &DAG) {
11418 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11420 if (!Subtarget->hasSSE41())
11423 if (!Op->hasOneUse())
11426 SDNode *N = Op.getNode();
11429 SmallVector<SDValue, 8> Opnds;
11430 DenseMap<SDValue, unsigned> VecInMap;
11431 SmallVector<SDValue, 8> VecIns;
11432 EVT VT = MVT::Other;
11434 // Recognize a special case where a vector is casted into wide integer to
11436 Opnds.push_back(N->getOperand(0));
11437 Opnds.push_back(N->getOperand(1));
11439 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11440 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11441 // BFS traverse all OR'd operands.
11442 if (I->getOpcode() == ISD::OR) {
11443 Opnds.push_back(I->getOperand(0));
11444 Opnds.push_back(I->getOperand(1));
11445 // Re-evaluate the number of nodes to be traversed.
11446 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11450 // Quit if a non-EXTRACT_VECTOR_ELT
11451 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11454 // Quit if without a constant index.
11455 SDValue Idx = I->getOperand(1);
11456 if (!isa<ConstantSDNode>(Idx))
11459 SDValue ExtractedFromVec = I->getOperand(0);
11460 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11461 if (M == VecInMap.end()) {
11462 VT = ExtractedFromVec.getValueType();
11463 // Quit if not 128/256-bit vector.
11464 if (!VT.is128BitVector() && !VT.is256BitVector())
11466 // Quit if not the same type.
11467 if (VecInMap.begin() != VecInMap.end() &&
11468 VT != VecInMap.begin()->first.getValueType())
11470 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11471 VecIns.push_back(ExtractedFromVec);
11473 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11476 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11477 "Not extracted from 128-/256-bit vector.");
11479 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11481 for (DenseMap<SDValue, unsigned>::const_iterator
11482 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11483 // Quit if not all elements are used.
11484 if (I->second != FullMask)
11488 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11490 // Cast all vectors into TestVT for PTEST.
11491 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11492 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11494 // If more than one full vectors are evaluated, OR them first before PTEST.
11495 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11496 // Each iteration will OR 2 nodes and append the result until there is only
11497 // 1 node left, i.e. the final OR'd value of all vectors.
11498 SDValue LHS = VecIns[Slot];
11499 SDValue RHS = VecIns[Slot + 1];
11500 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11503 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11504 VecIns.back(), VecIns.back());
11507 /// \brief return true if \c Op has a use that doesn't just read flags.
11508 static bool hasNonFlagsUse(SDValue Op) {
11509 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11511 SDNode *User = *UI;
11512 unsigned UOpNo = UI.getOperandNo();
11513 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11514 // Look pass truncate.
11515 UOpNo = User->use_begin().getOperandNo();
11516 User = *User->use_begin();
11519 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11520 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11526 /// Emit nodes that will be selected as "test Op0,Op0", or something
11528 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11529 SelectionDAG &DAG) const {
11530 if (Op.getValueType() == MVT::i1)
11531 // KORTEST instruction should be selected
11532 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11533 DAG.getConstant(0, Op.getValueType()));
11535 // CF and OF aren't always set the way we want. Determine which
11536 // of these we need.
11537 bool NeedCF = false;
11538 bool NeedOF = false;
11541 case X86::COND_A: case X86::COND_AE:
11542 case X86::COND_B: case X86::COND_BE:
11545 case X86::COND_G: case X86::COND_GE:
11546 case X86::COND_L: case X86::COND_LE:
11547 case X86::COND_O: case X86::COND_NO: {
11548 // Check if we really need to set the
11549 // Overflow flag. If NoSignedWrap is present
11550 // that is not actually needed.
11551 switch (Op->getOpcode()) {
11556 const BinaryWithFlagsSDNode *BinNode =
11557 cast<BinaryWithFlagsSDNode>(Op.getNode());
11558 if (BinNode->hasNoSignedWrap())
11568 // See if we can use the EFLAGS value from the operand instead of
11569 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11570 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11571 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11572 // Emit a CMP with 0, which is the TEST pattern.
11573 //if (Op.getValueType() == MVT::i1)
11574 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11575 // DAG.getConstant(0, MVT::i1));
11576 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11577 DAG.getConstant(0, Op.getValueType()));
11579 unsigned Opcode = 0;
11580 unsigned NumOperands = 0;
11582 // Truncate operations may prevent the merge of the SETCC instruction
11583 // and the arithmetic instruction before it. Attempt to truncate the operands
11584 // of the arithmetic instruction and use a reduced bit-width instruction.
11585 bool NeedTruncation = false;
11586 SDValue ArithOp = Op;
11587 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11588 SDValue Arith = Op->getOperand(0);
11589 // Both the trunc and the arithmetic op need to have one user each.
11590 if (Arith->hasOneUse())
11591 switch (Arith.getOpcode()) {
11598 NeedTruncation = true;
11604 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11605 // which may be the result of a CAST. We use the variable 'Op', which is the
11606 // non-casted variable when we check for possible users.
11607 switch (ArithOp.getOpcode()) {
11609 // Due to an isel shortcoming, be conservative if this add is likely to be
11610 // selected as part of a load-modify-store instruction. When the root node
11611 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11612 // uses of other nodes in the match, such as the ADD in this case. This
11613 // leads to the ADD being left around and reselected, with the result being
11614 // two adds in the output. Alas, even if none our users are stores, that
11615 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11616 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11617 // climbing the DAG back to the root, and it doesn't seem to be worth the
11619 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11620 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11621 if (UI->getOpcode() != ISD::CopyToReg &&
11622 UI->getOpcode() != ISD::SETCC &&
11623 UI->getOpcode() != ISD::STORE)
11626 if (ConstantSDNode *C =
11627 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11628 // An add of one will be selected as an INC.
11629 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11630 Opcode = X86ISD::INC;
11635 // An add of negative one (subtract of one) will be selected as a DEC.
11636 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11637 Opcode = X86ISD::DEC;
11643 // Otherwise use a regular EFLAGS-setting add.
11644 Opcode = X86ISD::ADD;
11649 // If we have a constant logical shift that's only used in a comparison
11650 // against zero turn it into an equivalent AND. This allows turning it into
11651 // a TEST instruction later.
11652 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11653 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11654 EVT VT = Op.getValueType();
11655 unsigned BitWidth = VT.getSizeInBits();
11656 unsigned ShAmt = Op->getConstantOperandVal(1);
11657 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11659 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11660 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11661 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11662 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11664 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11665 DAG.getConstant(Mask, VT));
11666 DAG.ReplaceAllUsesWith(Op, New);
11672 // If the primary and result isn't used, don't bother using X86ISD::AND,
11673 // because a TEST instruction will be better.
11674 if (!hasNonFlagsUse(Op))
11680 // Due to the ISEL shortcoming noted above, be conservative if this op is
11681 // likely to be selected as part of a load-modify-store instruction.
11682 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11683 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11684 if (UI->getOpcode() == ISD::STORE)
11687 // Otherwise use a regular EFLAGS-setting instruction.
11688 switch (ArithOp.getOpcode()) {
11689 default: llvm_unreachable("unexpected operator!");
11690 case ISD::SUB: Opcode = X86ISD::SUB; break;
11691 case ISD::XOR: Opcode = X86ISD::XOR; break;
11692 case ISD::AND: Opcode = X86ISD::AND; break;
11694 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11695 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11696 if (EFLAGS.getNode())
11699 Opcode = X86ISD::OR;
11713 return SDValue(Op.getNode(), 1);
11719 // If we found that truncation is beneficial, perform the truncation and
11721 if (NeedTruncation) {
11722 EVT VT = Op.getValueType();
11723 SDValue WideVal = Op->getOperand(0);
11724 EVT WideVT = WideVal.getValueType();
11725 unsigned ConvertedOp = 0;
11726 // Use a target machine opcode to prevent further DAGCombine
11727 // optimizations that may separate the arithmetic operations
11728 // from the setcc node.
11729 switch (WideVal.getOpcode()) {
11731 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11732 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11733 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11734 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11735 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11739 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11740 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11741 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11742 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11743 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11749 // Emit a CMP with 0, which is the TEST pattern.
11750 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11751 DAG.getConstant(0, Op.getValueType()));
11753 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11754 SmallVector<SDValue, 4> Ops;
11755 for (unsigned i = 0; i != NumOperands; ++i)
11756 Ops.push_back(Op.getOperand(i));
11758 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11759 DAG.ReplaceAllUsesWith(Op, New);
11760 return SDValue(New.getNode(), 1);
11763 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11765 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11766 SDLoc dl, SelectionDAG &DAG) const {
11767 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11768 if (C->getAPIntValue() == 0)
11769 return EmitTest(Op0, X86CC, dl, DAG);
11771 if (Op0.getValueType() == MVT::i1)
11772 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11775 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11776 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11777 // Do the comparison at i32 if it's smaller, besides the Atom case.
11778 // This avoids subregister aliasing issues. Keep the smaller reference
11779 // if we're optimizing for size, however, as that'll allow better folding
11780 // of memory operations.
11781 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11782 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11783 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11784 !Subtarget->isAtom()) {
11785 unsigned ExtendOp =
11786 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11787 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11788 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11790 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11791 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11792 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11794 return SDValue(Sub.getNode(), 1);
11796 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11799 /// Convert a comparison if required by the subtarget.
11800 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11801 SelectionDAG &DAG) const {
11802 // If the subtarget does not support the FUCOMI instruction, floating-point
11803 // comparisons have to be converted.
11804 if (Subtarget->hasCMov() ||
11805 Cmp.getOpcode() != X86ISD::CMP ||
11806 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11807 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11810 // The instruction selector will select an FUCOM instruction instead of
11811 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11812 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11813 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11815 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11816 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11817 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11818 DAG.getConstant(8, MVT::i8));
11819 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11820 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11823 static bool isAllOnes(SDValue V) {
11824 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11825 return C && C->isAllOnesValue();
11828 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11829 /// if it's possible.
11830 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11831 SDLoc dl, SelectionDAG &DAG) const {
11832 SDValue Op0 = And.getOperand(0);
11833 SDValue Op1 = And.getOperand(1);
11834 if (Op0.getOpcode() == ISD::TRUNCATE)
11835 Op0 = Op0.getOperand(0);
11836 if (Op1.getOpcode() == ISD::TRUNCATE)
11837 Op1 = Op1.getOperand(0);
11840 if (Op1.getOpcode() == ISD::SHL)
11841 std::swap(Op0, Op1);
11842 if (Op0.getOpcode() == ISD::SHL) {
11843 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11844 if (And00C->getZExtValue() == 1) {
11845 // If we looked past a truncate, check that it's only truncating away
11847 unsigned BitWidth = Op0.getValueSizeInBits();
11848 unsigned AndBitWidth = And.getValueSizeInBits();
11849 if (BitWidth > AndBitWidth) {
11851 DAG.computeKnownBits(Op0, Zeros, Ones);
11852 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11856 RHS = Op0.getOperand(1);
11858 } else if (Op1.getOpcode() == ISD::Constant) {
11859 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11860 uint64_t AndRHSVal = AndRHS->getZExtValue();
11861 SDValue AndLHS = Op0;
11863 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11864 LHS = AndLHS.getOperand(0);
11865 RHS = AndLHS.getOperand(1);
11868 // Use BT if the immediate can't be encoded in a TEST instruction.
11869 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11871 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11875 if (LHS.getNode()) {
11876 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
11877 // instruction. Since the shift amount is in-range-or-undefined, we know
11878 // that doing a bittest on the i32 value is ok. We extend to i32 because
11879 // the encoding for the i16 version is larger than the i32 version.
11880 // Also promote i16 to i32 for performance / code size reason.
11881 if (LHS.getValueType() == MVT::i8 ||
11882 LHS.getValueType() == MVT::i16)
11883 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11885 // If the operand types disagree, extend the shift amount to match. Since
11886 // BT ignores high bits (like shifts) we can use anyextend.
11887 if (LHS.getValueType() != RHS.getValueType())
11888 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11890 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11891 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11892 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11893 DAG.getConstant(Cond, MVT::i8), BT);
11899 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11901 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11906 // SSE Condition code mapping:
11915 switch (SetCCOpcode) {
11916 default: llvm_unreachable("Unexpected SETCC condition");
11918 case ISD::SETEQ: SSECC = 0; break;
11920 case ISD::SETGT: Swap = true; // Fallthrough
11922 case ISD::SETOLT: SSECC = 1; break;
11924 case ISD::SETGE: Swap = true; // Fallthrough
11926 case ISD::SETOLE: SSECC = 2; break;
11927 case ISD::SETUO: SSECC = 3; break;
11929 case ISD::SETNE: SSECC = 4; break;
11930 case ISD::SETULE: Swap = true; // Fallthrough
11931 case ISD::SETUGE: SSECC = 5; break;
11932 case ISD::SETULT: Swap = true; // Fallthrough
11933 case ISD::SETUGT: SSECC = 6; break;
11934 case ISD::SETO: SSECC = 7; break;
11936 case ISD::SETONE: SSECC = 8; break;
11939 std::swap(Op0, Op1);
11944 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
11945 // ones, and then concatenate the result back.
11946 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
11947 MVT VT = Op.getSimpleValueType();
11949 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
11950 "Unsupported value type for operation");
11952 unsigned NumElems = VT.getVectorNumElements();
11954 SDValue CC = Op.getOperand(2);
11956 // Extract the LHS vectors
11957 SDValue LHS = Op.getOperand(0);
11958 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11959 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11961 // Extract the RHS vectors
11962 SDValue RHS = Op.getOperand(1);
11963 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11964 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11966 // Issue the operation on the smaller types and concatenate the result back
11967 MVT EltVT = VT.getVectorElementType();
11968 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11969 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11970 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
11971 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
11974 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
11975 const X86Subtarget *Subtarget) {
11976 SDValue Op0 = Op.getOperand(0);
11977 SDValue Op1 = Op.getOperand(1);
11978 SDValue CC = Op.getOperand(2);
11979 MVT VT = Op.getSimpleValueType();
11982 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
11983 Op.getValueType().getScalarType() == MVT::i1 &&
11984 "Cannot set masked compare for this operation");
11986 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
11988 bool Unsigned = false;
11991 switch (SetCCOpcode) {
11992 default: llvm_unreachable("Unexpected SETCC condition");
11993 case ISD::SETNE: SSECC = 4; break;
11994 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
11995 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
11996 case ISD::SETLT: Swap = true; //fall-through
11997 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
11998 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
11999 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12000 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12001 case ISD::SETULE: Unsigned = true; //fall-through
12002 case ISD::SETLE: SSECC = 2; break;
12006 std::swap(Op0, Op1);
12008 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12009 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12010 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12011 DAG.getConstant(SSECC, MVT::i8));
12014 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12015 /// operand \p Op1. If non-trivial (for example because it's not constant)
12016 /// return an empty value.
12017 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12019 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12023 MVT VT = Op1.getSimpleValueType();
12024 MVT EVT = VT.getVectorElementType();
12025 unsigned n = VT.getVectorNumElements();
12026 SmallVector<SDValue, 8> ULTOp1;
12028 for (unsigned i = 0; i < n; ++i) {
12029 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12030 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12033 // Avoid underflow.
12034 APInt Val = Elt->getAPIntValue();
12038 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12041 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12044 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12045 SelectionDAG &DAG) {
12046 SDValue Op0 = Op.getOperand(0);
12047 SDValue Op1 = Op.getOperand(1);
12048 SDValue CC = Op.getOperand(2);
12049 MVT VT = Op.getSimpleValueType();
12050 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12051 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12056 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12057 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12060 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12061 unsigned Opc = X86ISD::CMPP;
12062 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12063 assert(VT.getVectorNumElements() <= 16);
12064 Opc = X86ISD::CMPM;
12066 // In the two special cases we can't handle, emit two comparisons.
12069 unsigned CombineOpc;
12070 if (SetCCOpcode == ISD::SETUEQ) {
12071 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12073 assert(SetCCOpcode == ISD::SETONE);
12074 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12077 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12078 DAG.getConstant(CC0, MVT::i8));
12079 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12080 DAG.getConstant(CC1, MVT::i8));
12081 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12083 // Handle all other FP comparisons here.
12084 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12085 DAG.getConstant(SSECC, MVT::i8));
12088 // Break 256-bit integer vector compare into smaller ones.
12089 if (VT.is256BitVector() && !Subtarget->hasInt256())
12090 return Lower256IntVSETCC(Op, DAG);
12092 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12093 EVT OpVT = Op1.getValueType();
12094 if (Subtarget->hasAVX512()) {
12095 if (Op1.getValueType().is512BitVector() ||
12096 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12097 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12099 // In AVX-512 architecture setcc returns mask with i1 elements,
12100 // But there is no compare instruction for i8 and i16 elements.
12101 // We are not talking about 512-bit operands in this case, these
12102 // types are illegal.
12104 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12105 OpVT.getVectorElementType().getSizeInBits() >= 8))
12106 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12107 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12110 // We are handling one of the integer comparisons here. Since SSE only has
12111 // GT and EQ comparisons for integer, swapping operands and multiple
12112 // operations may be required for some comparisons.
12114 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12115 bool Subus = false;
12117 switch (SetCCOpcode) {
12118 default: llvm_unreachable("Unexpected SETCC condition");
12119 case ISD::SETNE: Invert = true;
12120 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12121 case ISD::SETLT: Swap = true;
12122 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12123 case ISD::SETGE: Swap = true;
12124 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12125 Invert = true; break;
12126 case ISD::SETULT: Swap = true;
12127 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12128 FlipSigns = true; break;
12129 case ISD::SETUGE: Swap = true;
12130 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12131 FlipSigns = true; Invert = true; break;
12134 // Special case: Use min/max operations for SETULE/SETUGE
12135 MVT VET = VT.getVectorElementType();
12137 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12138 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12141 switch (SetCCOpcode) {
12143 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12144 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12147 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12150 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12151 if (!MinMax && hasSubus) {
12152 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12154 // t = psubus Op0, Op1
12155 // pcmpeq t, <0..0>
12156 switch (SetCCOpcode) {
12158 case ISD::SETULT: {
12159 // If the comparison is against a constant we can turn this into a
12160 // setule. With psubus, setule does not require a swap. This is
12161 // beneficial because the constant in the register is no longer
12162 // destructed as the destination so it can be hoisted out of a loop.
12163 // Only do this pre-AVX since vpcmp* is no longer destructive.
12164 if (Subtarget->hasAVX())
12166 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12167 if (ULEOp1.getNode()) {
12169 Subus = true; Invert = false; Swap = false;
12173 // Psubus is better than flip-sign because it requires no inversion.
12174 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12175 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12179 Opc = X86ISD::SUBUS;
12185 std::swap(Op0, Op1);
12187 // Check that the operation in question is available (most are plain SSE2,
12188 // but PCMPGTQ and PCMPEQQ have different requirements).
12189 if (VT == MVT::v2i64) {
12190 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12191 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12193 // First cast everything to the right type.
12194 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12195 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12197 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12198 // bits of the inputs before performing those operations. The lower
12199 // compare is always unsigned.
12202 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12204 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12205 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12206 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12207 Sign, Zero, Sign, Zero);
12209 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12210 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12212 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12213 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12214 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12216 // Create masks for only the low parts/high parts of the 64 bit integers.
12217 static const int MaskHi[] = { 1, 1, 3, 3 };
12218 static const int MaskLo[] = { 0, 0, 2, 2 };
12219 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12220 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12221 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12223 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12224 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12227 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12229 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12232 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12233 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12234 // pcmpeqd + pshufd + pand.
12235 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12237 // First cast everything to the right type.
12238 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12239 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12242 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12244 // Make sure the lower and upper halves are both all-ones.
12245 static const int Mask[] = { 1, 0, 3, 2 };
12246 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12247 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12250 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12252 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12256 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12257 // bits of the inputs before performing those operations.
12259 EVT EltVT = VT.getVectorElementType();
12260 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12261 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12262 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12265 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12267 // If the logical-not of the result is required, perform that now.
12269 Result = DAG.getNOT(dl, Result, VT);
12272 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12275 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12276 getZeroVector(VT, Subtarget, DAG, dl));
12281 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12283 MVT VT = Op.getSimpleValueType();
12285 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12287 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12288 && "SetCC type must be 8-bit or 1-bit integer");
12289 SDValue Op0 = Op.getOperand(0);
12290 SDValue Op1 = Op.getOperand(1);
12292 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12294 // Optimize to BT if possible.
12295 // Lower (X & (1 << N)) == 0 to BT(X, N).
12296 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12297 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12298 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12299 Op1.getOpcode() == ISD::Constant &&
12300 cast<ConstantSDNode>(Op1)->isNullValue() &&
12301 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12302 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12303 if (NewSetCC.getNode())
12307 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12309 if (Op1.getOpcode() == ISD::Constant &&
12310 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12311 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12312 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12314 // If the input is a setcc, then reuse the input setcc or use a new one with
12315 // the inverted condition.
12316 if (Op0.getOpcode() == X86ISD::SETCC) {
12317 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12318 bool Invert = (CC == ISD::SETNE) ^
12319 cast<ConstantSDNode>(Op1)->isNullValue();
12323 CCode = X86::GetOppositeBranchCondition(CCode);
12324 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12325 DAG.getConstant(CCode, MVT::i8),
12326 Op0.getOperand(1));
12328 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12332 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12333 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12334 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12336 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12337 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12340 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12341 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12342 if (X86CC == X86::COND_INVALID)
12345 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12346 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12347 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12348 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12350 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12354 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12355 static bool isX86LogicalCmp(SDValue Op) {
12356 unsigned Opc = Op.getNode()->getOpcode();
12357 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12358 Opc == X86ISD::SAHF)
12360 if (Op.getResNo() == 1 &&
12361 (Opc == X86ISD::ADD ||
12362 Opc == X86ISD::SUB ||
12363 Opc == X86ISD::ADC ||
12364 Opc == X86ISD::SBB ||
12365 Opc == X86ISD::SMUL ||
12366 Opc == X86ISD::UMUL ||
12367 Opc == X86ISD::INC ||
12368 Opc == X86ISD::DEC ||
12369 Opc == X86ISD::OR ||
12370 Opc == X86ISD::XOR ||
12371 Opc == X86ISD::AND))
12374 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12380 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12381 if (V.getOpcode() != ISD::TRUNCATE)
12384 SDValue VOp0 = V.getOperand(0);
12385 unsigned InBits = VOp0.getValueSizeInBits();
12386 unsigned Bits = V.getValueSizeInBits();
12387 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12390 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12391 bool addTest = true;
12392 SDValue Cond = Op.getOperand(0);
12393 SDValue Op1 = Op.getOperand(1);
12394 SDValue Op2 = Op.getOperand(2);
12396 EVT VT = Op1.getValueType();
12399 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12400 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12401 // sequence later on.
12402 if (Cond.getOpcode() == ISD::SETCC &&
12403 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12404 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12405 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12406 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12407 int SSECC = translateX86FSETCC(
12408 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12411 if (Subtarget->hasAVX512()) {
12412 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12413 DAG.getConstant(SSECC, MVT::i8));
12414 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12416 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12417 DAG.getConstant(SSECC, MVT::i8));
12418 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12419 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12420 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12424 if (Cond.getOpcode() == ISD::SETCC) {
12425 SDValue NewCond = LowerSETCC(Cond, DAG);
12426 if (NewCond.getNode())
12430 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12431 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12432 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12433 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12434 if (Cond.getOpcode() == X86ISD::SETCC &&
12435 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12436 isZero(Cond.getOperand(1).getOperand(1))) {
12437 SDValue Cmp = Cond.getOperand(1);
12439 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12441 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12442 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12443 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12445 SDValue CmpOp0 = Cmp.getOperand(0);
12446 // Apply further optimizations for special cases
12447 // (select (x != 0), -1, 0) -> neg & sbb
12448 // (select (x == 0), 0, -1) -> neg & sbb
12449 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12450 if (YC->isNullValue() &&
12451 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12452 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12453 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12454 DAG.getConstant(0, CmpOp0.getValueType()),
12456 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12457 DAG.getConstant(X86::COND_B, MVT::i8),
12458 SDValue(Neg.getNode(), 1));
12462 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12463 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12464 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12466 SDValue Res = // Res = 0 or -1.
12467 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12468 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12470 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12471 Res = DAG.getNOT(DL, Res, Res.getValueType());
12473 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12474 if (!N2C || !N2C->isNullValue())
12475 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12480 // Look past (and (setcc_carry (cmp ...)), 1).
12481 if (Cond.getOpcode() == ISD::AND &&
12482 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12483 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12484 if (C && C->getAPIntValue() == 1)
12485 Cond = Cond.getOperand(0);
12488 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12489 // setting operand in place of the X86ISD::SETCC.
12490 unsigned CondOpcode = Cond.getOpcode();
12491 if (CondOpcode == X86ISD::SETCC ||
12492 CondOpcode == X86ISD::SETCC_CARRY) {
12493 CC = Cond.getOperand(0);
12495 SDValue Cmp = Cond.getOperand(1);
12496 unsigned Opc = Cmp.getOpcode();
12497 MVT VT = Op.getSimpleValueType();
12499 bool IllegalFPCMov = false;
12500 if (VT.isFloatingPoint() && !VT.isVector() &&
12501 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12502 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12504 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12505 Opc == X86ISD::BT) { // FIXME
12509 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12510 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12511 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12512 Cond.getOperand(0).getValueType() != MVT::i8)) {
12513 SDValue LHS = Cond.getOperand(0);
12514 SDValue RHS = Cond.getOperand(1);
12515 unsigned X86Opcode;
12518 switch (CondOpcode) {
12519 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12520 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12521 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12522 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12523 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12524 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12525 default: llvm_unreachable("unexpected overflowing operator");
12527 if (CondOpcode == ISD::UMULO)
12528 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12531 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12533 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12535 if (CondOpcode == ISD::UMULO)
12536 Cond = X86Op.getValue(2);
12538 Cond = X86Op.getValue(1);
12540 CC = DAG.getConstant(X86Cond, MVT::i8);
12545 // Look pass the truncate if the high bits are known zero.
12546 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12547 Cond = Cond.getOperand(0);
12549 // We know the result of AND is compared against zero. Try to match
12551 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12552 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12553 if (NewSetCC.getNode()) {
12554 CC = NewSetCC.getOperand(0);
12555 Cond = NewSetCC.getOperand(1);
12562 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12563 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12566 // a < b ? -1 : 0 -> RES = ~setcc_carry
12567 // a < b ? 0 : -1 -> RES = setcc_carry
12568 // a >= b ? -1 : 0 -> RES = setcc_carry
12569 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12570 if (Cond.getOpcode() == X86ISD::SUB) {
12571 Cond = ConvertCmpIfNecessary(Cond, DAG);
12572 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12574 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12575 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12576 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12577 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12578 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12579 return DAG.getNOT(DL, Res, Res.getValueType());
12584 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12585 // widen the cmov and push the truncate through. This avoids introducing a new
12586 // branch during isel and doesn't add any extensions.
12587 if (Op.getValueType() == MVT::i8 &&
12588 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12589 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12590 if (T1.getValueType() == T2.getValueType() &&
12591 // Blacklist CopyFromReg to avoid partial register stalls.
12592 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12593 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12594 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12595 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12599 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12600 // condition is true.
12601 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12602 SDValue Ops[] = { Op2, Op1, CC, Cond };
12603 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12606 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12607 MVT VT = Op->getSimpleValueType(0);
12608 SDValue In = Op->getOperand(0);
12609 MVT InVT = In.getSimpleValueType();
12612 unsigned int NumElts = VT.getVectorNumElements();
12613 if (NumElts != 8 && NumElts != 16)
12616 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12617 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12619 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12620 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12622 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12623 Constant *C = ConstantInt::get(*DAG.getContext(),
12624 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12626 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12627 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12628 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12629 MachinePointerInfo::getConstantPool(),
12630 false, false, false, Alignment);
12631 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12632 if (VT.is512BitVector())
12634 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12637 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12638 SelectionDAG &DAG) {
12639 MVT VT = Op->getSimpleValueType(0);
12640 SDValue In = Op->getOperand(0);
12641 MVT InVT = In.getSimpleValueType();
12644 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12645 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12647 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12648 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12649 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12652 if (Subtarget->hasInt256())
12653 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12655 // Optimize vectors in AVX mode
12656 // Sign extend v8i16 to v8i32 and
12659 // Divide input vector into two parts
12660 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12661 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12662 // concat the vectors to original VT
12664 unsigned NumElems = InVT.getVectorNumElements();
12665 SDValue Undef = DAG.getUNDEF(InVT);
12667 SmallVector<int,8> ShufMask1(NumElems, -1);
12668 for (unsigned i = 0; i != NumElems/2; ++i)
12671 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12673 SmallVector<int,8> ShufMask2(NumElems, -1);
12674 for (unsigned i = 0; i != NumElems/2; ++i)
12675 ShufMask2[i] = i + NumElems/2;
12677 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12679 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12680 VT.getVectorNumElements()/2);
12682 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12683 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12685 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12688 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12689 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12690 // from the AND / OR.
12691 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12692 Opc = Op.getOpcode();
12693 if (Opc != ISD::OR && Opc != ISD::AND)
12695 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12696 Op.getOperand(0).hasOneUse() &&
12697 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12698 Op.getOperand(1).hasOneUse());
12701 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12702 // 1 and that the SETCC node has a single use.
12703 static bool isXor1OfSetCC(SDValue Op) {
12704 if (Op.getOpcode() != ISD::XOR)
12706 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12707 if (N1C && N1C->getAPIntValue() == 1) {
12708 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12709 Op.getOperand(0).hasOneUse();
12714 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12715 bool addTest = true;
12716 SDValue Chain = Op.getOperand(0);
12717 SDValue Cond = Op.getOperand(1);
12718 SDValue Dest = Op.getOperand(2);
12721 bool Inverted = false;
12723 if (Cond.getOpcode() == ISD::SETCC) {
12724 // Check for setcc([su]{add,sub,mul}o == 0).
12725 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12726 isa<ConstantSDNode>(Cond.getOperand(1)) &&
12727 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12728 Cond.getOperand(0).getResNo() == 1 &&
12729 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12730 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12731 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12732 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12733 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12734 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12736 Cond = Cond.getOperand(0);
12738 SDValue NewCond = LowerSETCC(Cond, DAG);
12739 if (NewCond.getNode())
12744 // FIXME: LowerXALUO doesn't handle these!!
12745 else if (Cond.getOpcode() == X86ISD::ADD ||
12746 Cond.getOpcode() == X86ISD::SUB ||
12747 Cond.getOpcode() == X86ISD::SMUL ||
12748 Cond.getOpcode() == X86ISD::UMUL)
12749 Cond = LowerXALUO(Cond, DAG);
12752 // Look pass (and (setcc_carry (cmp ...)), 1).
12753 if (Cond.getOpcode() == ISD::AND &&
12754 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12755 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12756 if (C && C->getAPIntValue() == 1)
12757 Cond = Cond.getOperand(0);
12760 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12761 // setting operand in place of the X86ISD::SETCC.
12762 unsigned CondOpcode = Cond.getOpcode();
12763 if (CondOpcode == X86ISD::SETCC ||
12764 CondOpcode == X86ISD::SETCC_CARRY) {
12765 CC = Cond.getOperand(0);
12767 SDValue Cmp = Cond.getOperand(1);
12768 unsigned Opc = Cmp.getOpcode();
12769 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12770 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12774 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12778 // These can only come from an arithmetic instruction with overflow,
12779 // e.g. SADDO, UADDO.
12780 Cond = Cond.getNode()->getOperand(1);
12786 CondOpcode = Cond.getOpcode();
12787 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12788 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12789 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12790 Cond.getOperand(0).getValueType() != MVT::i8)) {
12791 SDValue LHS = Cond.getOperand(0);
12792 SDValue RHS = Cond.getOperand(1);
12793 unsigned X86Opcode;
12796 // Keep this in sync with LowerXALUO, otherwise we might create redundant
12797 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12799 switch (CondOpcode) {
12800 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12802 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12804 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12807 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12808 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12810 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12812 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12815 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12816 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12817 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12818 default: llvm_unreachable("unexpected overflowing operator");
12821 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12822 if (CondOpcode == ISD::UMULO)
12823 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12826 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12828 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12830 if (CondOpcode == ISD::UMULO)
12831 Cond = X86Op.getValue(2);
12833 Cond = X86Op.getValue(1);
12835 CC = DAG.getConstant(X86Cond, MVT::i8);
12839 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12840 SDValue Cmp = Cond.getOperand(0).getOperand(1);
12841 if (CondOpc == ISD::OR) {
12842 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12843 // two branches instead of an explicit OR instruction with a
12845 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12846 isX86LogicalCmp(Cmp)) {
12847 CC = Cond.getOperand(0).getOperand(0);
12848 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12849 Chain, Dest, CC, Cmp);
12850 CC = Cond.getOperand(1).getOperand(0);
12854 } else { // ISD::AND
12855 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12856 // two branches instead of an explicit AND instruction with a
12857 // separate test. However, we only do this if this block doesn't
12858 // have a fall-through edge, because this requires an explicit
12859 // jmp when the condition is false.
12860 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12861 isX86LogicalCmp(Cmp) &&
12862 Op.getNode()->hasOneUse()) {
12863 X86::CondCode CCode =
12864 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12865 CCode = X86::GetOppositeBranchCondition(CCode);
12866 CC = DAG.getConstant(CCode, MVT::i8);
12867 SDNode *User = *Op.getNode()->use_begin();
12868 // Look for an unconditional branch following this conditional branch.
12869 // We need this because we need to reverse the successors in order
12870 // to implement FCMP_OEQ.
12871 if (User->getOpcode() == ISD::BR) {
12872 SDValue FalseBB = User->getOperand(1);
12874 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12875 assert(NewBR == User);
12879 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12880 Chain, Dest, CC, Cmp);
12881 X86::CondCode CCode =
12882 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12883 CCode = X86::GetOppositeBranchCondition(CCode);
12884 CC = DAG.getConstant(CCode, MVT::i8);
12890 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12891 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12892 // It should be transformed during dag combiner except when the condition
12893 // is set by a arithmetics with overflow node.
12894 X86::CondCode CCode =
12895 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12896 CCode = X86::GetOppositeBranchCondition(CCode);
12897 CC = DAG.getConstant(CCode, MVT::i8);
12898 Cond = Cond.getOperand(0).getOperand(1);
12900 } else if (Cond.getOpcode() == ISD::SETCC &&
12901 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12902 // For FCMP_OEQ, we can emit
12903 // two branches instead of an explicit AND instruction with a
12904 // separate test. However, we only do this if this block doesn't
12905 // have a fall-through edge, because this requires an explicit
12906 // jmp when the condition is false.
12907 if (Op.getNode()->hasOneUse()) {
12908 SDNode *User = *Op.getNode()->use_begin();
12909 // Look for an unconditional branch following this conditional branch.
12910 // We need this because we need to reverse the successors in order
12911 // to implement FCMP_OEQ.
12912 if (User->getOpcode() == ISD::BR) {
12913 SDValue FalseBB = User->getOperand(1);
12915 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12916 assert(NewBR == User);
12920 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12921 Cond.getOperand(0), Cond.getOperand(1));
12922 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12923 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12924 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12925 Chain, Dest, CC, Cmp);
12926 CC = DAG.getConstant(X86::COND_P, MVT::i8);
12931 } else if (Cond.getOpcode() == ISD::SETCC &&
12932 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
12933 // For FCMP_UNE, we can emit
12934 // two branches instead of an explicit AND instruction with a
12935 // separate test. However, we only do this if this block doesn't
12936 // have a fall-through edge, because this requires an explicit
12937 // jmp when the condition is false.
12938 if (Op.getNode()->hasOneUse()) {
12939 SDNode *User = *Op.getNode()->use_begin();
12940 // Look for an unconditional branch following this conditional branch.
12941 // We need this because we need to reverse the successors in order
12942 // to implement FCMP_UNE.
12943 if (User->getOpcode() == ISD::BR) {
12944 SDValue FalseBB = User->getOperand(1);
12946 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12947 assert(NewBR == User);
12950 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12951 Cond.getOperand(0), Cond.getOperand(1));
12952 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12953 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12954 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12955 Chain, Dest, CC, Cmp);
12956 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
12966 // Look pass the truncate if the high bits are known zero.
12967 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12968 Cond = Cond.getOperand(0);
12970 // We know the result of AND is compared against zero. Try to match
12972 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12973 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
12974 if (NewSetCC.getNode()) {
12975 CC = NewSetCC.getOperand(0);
12976 Cond = NewSetCC.getOperand(1);
12983 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
12984 CC = DAG.getConstant(X86Cond, MVT::i8);
12985 Cond = EmitTest(Cond, X86Cond, dl, DAG);
12987 Cond = ConvertCmpIfNecessary(Cond, DAG);
12988 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12989 Chain, Dest, CC, Cond);
12992 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
12993 // Calls to _alloca is needed to probe the stack when allocating more than 4k
12994 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
12995 // that the guard pages used by the OS virtual memory manager are allocated in
12996 // correct sequence.
12998 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
12999 SelectionDAG &DAG) const {
13000 MachineFunction &MF = DAG.getMachineFunction();
13001 bool SplitStack = MF.shouldSplitStack();
13002 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13007 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13008 SDNode* Node = Op.getNode();
13010 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13011 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13012 " not tell us which reg is the stack pointer!");
13013 EVT VT = Node->getValueType(0);
13014 SDValue Tmp1 = SDValue(Node, 0);
13015 SDValue Tmp2 = SDValue(Node, 1);
13016 SDValue Tmp3 = Node->getOperand(2);
13017 SDValue Chain = Tmp1.getOperand(0);
13019 // Chain the dynamic stack allocation so that it doesn't modify the stack
13020 // pointer when other instructions are using the stack.
13021 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13024 SDValue Size = Tmp2.getOperand(1);
13025 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13026 Chain = SP.getValue(1);
13027 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13028 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13029 unsigned StackAlign = TFI.getStackAlignment();
13030 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13031 if (Align > StackAlign)
13032 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13033 DAG.getConstant(-(uint64_t)Align, VT));
13034 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13036 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13037 DAG.getIntPtrConstant(0, true), SDValue(),
13040 SDValue Ops[2] = { Tmp1, Tmp2 };
13041 return DAG.getMergeValues(Ops, dl);
13045 SDValue Chain = Op.getOperand(0);
13046 SDValue Size = Op.getOperand(1);
13047 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13048 EVT VT = Op.getNode()->getValueType(0);
13050 bool Is64Bit = Subtarget->is64Bit();
13051 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13054 MachineRegisterInfo &MRI = MF.getRegInfo();
13057 // The 64 bit implementation of segmented stacks needs to clobber both r10
13058 // r11. This makes it impossible to use it along with nested parameters.
13059 const Function *F = MF.getFunction();
13061 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13063 if (I->hasNestAttr())
13064 report_fatal_error("Cannot use segmented stacks with functions that "
13065 "have nested arguments.");
13068 const TargetRegisterClass *AddrRegClass =
13069 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13070 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13071 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13072 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13073 DAG.getRegister(Vreg, SPTy));
13074 SDValue Ops1[2] = { Value, Chain };
13075 return DAG.getMergeValues(Ops1, dl);
13078 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13080 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13081 Flag = Chain.getValue(1);
13082 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13084 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13086 const X86RegisterInfo *RegInfo =
13087 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13088 unsigned SPReg = RegInfo->getStackRegister();
13089 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13090 Chain = SP.getValue(1);
13093 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13094 DAG.getConstant(-(uint64_t)Align, VT));
13095 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13098 SDValue Ops1[2] = { SP, Chain };
13099 return DAG.getMergeValues(Ops1, dl);
13103 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13104 MachineFunction &MF = DAG.getMachineFunction();
13105 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13107 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13110 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13111 // vastart just stores the address of the VarArgsFrameIndex slot into the
13112 // memory location argument.
13113 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13115 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13116 MachinePointerInfo(SV), false, false, 0);
13120 // gp_offset (0 - 6 * 8)
13121 // fp_offset (48 - 48 + 8 * 16)
13122 // overflow_arg_area (point to parameters coming in memory).
13124 SmallVector<SDValue, 8> MemOps;
13125 SDValue FIN = Op.getOperand(1);
13127 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13128 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13130 FIN, MachinePointerInfo(SV), false, false, 0);
13131 MemOps.push_back(Store);
13134 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13135 FIN, DAG.getIntPtrConstant(4));
13136 Store = DAG.getStore(Op.getOperand(0), DL,
13137 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13139 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13140 MemOps.push_back(Store);
13142 // Store ptr to overflow_arg_area
13143 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13144 FIN, DAG.getIntPtrConstant(4));
13145 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13147 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13148 MachinePointerInfo(SV, 8),
13150 MemOps.push_back(Store);
13152 // Store ptr to reg_save_area.
13153 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13154 FIN, DAG.getIntPtrConstant(8));
13155 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13157 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13158 MachinePointerInfo(SV, 16), false, false, 0);
13159 MemOps.push_back(Store);
13160 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13163 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13164 assert(Subtarget->is64Bit() &&
13165 "LowerVAARG only handles 64-bit va_arg!");
13166 assert((Subtarget->isTargetLinux() ||
13167 Subtarget->isTargetDarwin()) &&
13168 "Unhandled target in LowerVAARG");
13169 assert(Op.getNode()->getNumOperands() == 4);
13170 SDValue Chain = Op.getOperand(0);
13171 SDValue SrcPtr = Op.getOperand(1);
13172 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13173 unsigned Align = Op.getConstantOperandVal(3);
13176 EVT ArgVT = Op.getNode()->getValueType(0);
13177 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13178 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13181 // Decide which area this value should be read from.
13182 // TODO: Implement the AMD64 ABI in its entirety. This simple
13183 // selection mechanism works only for the basic types.
13184 if (ArgVT == MVT::f80) {
13185 llvm_unreachable("va_arg for f80 not yet implemented");
13186 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13187 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13188 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13189 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13191 llvm_unreachable("Unhandled argument type in LowerVAARG");
13194 if (ArgMode == 2) {
13195 // Sanity Check: Make sure using fp_offset makes sense.
13196 assert(!DAG.getTarget().Options.UseSoftFloat &&
13197 !(DAG.getMachineFunction()
13198 .getFunction()->getAttributes()
13199 .hasAttribute(AttributeSet::FunctionIndex,
13200 Attribute::NoImplicitFloat)) &&
13201 Subtarget->hasSSE1());
13204 // Insert VAARG_64 node into the DAG
13205 // VAARG_64 returns two values: Variable Argument Address, Chain
13206 SmallVector<SDValue, 11> InstOps;
13207 InstOps.push_back(Chain);
13208 InstOps.push_back(SrcPtr);
13209 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13210 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13211 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13212 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13213 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13214 VTs, InstOps, MVT::i64,
13215 MachinePointerInfo(SV),
13217 /*Volatile=*/false,
13219 /*WriteMem=*/true);
13220 Chain = VAARG.getValue(1);
13222 // Load the next argument and return it
13223 return DAG.getLoad(ArgVT, dl,
13226 MachinePointerInfo(),
13227 false, false, false, 0);
13230 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13231 SelectionDAG &DAG) {
13232 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13233 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13234 SDValue Chain = Op.getOperand(0);
13235 SDValue DstPtr = Op.getOperand(1);
13236 SDValue SrcPtr = Op.getOperand(2);
13237 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13238 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13241 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13242 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13244 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13247 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13248 // amount is a constant. Takes immediate version of shift as input.
13249 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13250 SDValue SrcOp, uint64_t ShiftAmt,
13251 SelectionDAG &DAG) {
13252 MVT ElementType = VT.getVectorElementType();
13254 // Fold this packed shift into its first operand if ShiftAmt is 0.
13258 // Check for ShiftAmt >= element width
13259 if (ShiftAmt >= ElementType.getSizeInBits()) {
13260 if (Opc == X86ISD::VSRAI)
13261 ShiftAmt = ElementType.getSizeInBits() - 1;
13263 return DAG.getConstant(0, VT);
13266 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13267 && "Unknown target vector shift-by-constant node");
13269 // Fold this packed vector shift into a build vector if SrcOp is a
13270 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13271 if (VT == SrcOp.getSimpleValueType() &&
13272 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13273 SmallVector<SDValue, 8> Elts;
13274 unsigned NumElts = SrcOp->getNumOperands();
13275 ConstantSDNode *ND;
13278 default: llvm_unreachable(nullptr);
13279 case X86ISD::VSHLI:
13280 for (unsigned i=0; i!=NumElts; ++i) {
13281 SDValue CurrentOp = SrcOp->getOperand(i);
13282 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13283 Elts.push_back(CurrentOp);
13286 ND = cast<ConstantSDNode>(CurrentOp);
13287 const APInt &C = ND->getAPIntValue();
13288 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13291 case X86ISD::VSRLI:
13292 for (unsigned i=0; i!=NumElts; ++i) {
13293 SDValue CurrentOp = SrcOp->getOperand(i);
13294 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13295 Elts.push_back(CurrentOp);
13298 ND = cast<ConstantSDNode>(CurrentOp);
13299 const APInt &C = ND->getAPIntValue();
13300 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13303 case X86ISD::VSRAI:
13304 for (unsigned i=0; i!=NumElts; ++i) {
13305 SDValue CurrentOp = SrcOp->getOperand(i);
13306 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13307 Elts.push_back(CurrentOp);
13310 ND = cast<ConstantSDNode>(CurrentOp);
13311 const APInt &C = ND->getAPIntValue();
13312 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13317 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13320 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13323 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13324 // may or may not be a constant. Takes immediate version of shift as input.
13325 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13326 SDValue SrcOp, SDValue ShAmt,
13327 SelectionDAG &DAG) {
13328 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13330 // Catch shift-by-constant.
13331 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13332 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13333 CShAmt->getZExtValue(), DAG);
13335 // Change opcode to non-immediate version
13337 default: llvm_unreachable("Unknown target vector shift node");
13338 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13339 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13340 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13343 // Need to build a vector containing shift amount
13344 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13347 ShOps[1] = DAG.getConstant(0, MVT::i32);
13348 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13349 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13351 // The return type has to be a 128-bit type with the same element
13352 // type as the input type.
13353 MVT EltVT = VT.getVectorElementType();
13354 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13356 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13357 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13360 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13362 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13364 default: return SDValue(); // Don't custom lower most intrinsics.
13365 // Comparison intrinsics.
13366 case Intrinsic::x86_sse_comieq_ss:
13367 case Intrinsic::x86_sse_comilt_ss:
13368 case Intrinsic::x86_sse_comile_ss:
13369 case Intrinsic::x86_sse_comigt_ss:
13370 case Intrinsic::x86_sse_comige_ss:
13371 case Intrinsic::x86_sse_comineq_ss:
13372 case Intrinsic::x86_sse_ucomieq_ss:
13373 case Intrinsic::x86_sse_ucomilt_ss:
13374 case Intrinsic::x86_sse_ucomile_ss:
13375 case Intrinsic::x86_sse_ucomigt_ss:
13376 case Intrinsic::x86_sse_ucomige_ss:
13377 case Intrinsic::x86_sse_ucomineq_ss:
13378 case Intrinsic::x86_sse2_comieq_sd:
13379 case Intrinsic::x86_sse2_comilt_sd:
13380 case Intrinsic::x86_sse2_comile_sd:
13381 case Intrinsic::x86_sse2_comigt_sd:
13382 case Intrinsic::x86_sse2_comige_sd:
13383 case Intrinsic::x86_sse2_comineq_sd:
13384 case Intrinsic::x86_sse2_ucomieq_sd:
13385 case Intrinsic::x86_sse2_ucomilt_sd:
13386 case Intrinsic::x86_sse2_ucomile_sd:
13387 case Intrinsic::x86_sse2_ucomigt_sd:
13388 case Intrinsic::x86_sse2_ucomige_sd:
13389 case Intrinsic::x86_sse2_ucomineq_sd: {
13393 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13394 case Intrinsic::x86_sse_comieq_ss:
13395 case Intrinsic::x86_sse2_comieq_sd:
13396 Opc = X86ISD::COMI;
13399 case Intrinsic::x86_sse_comilt_ss:
13400 case Intrinsic::x86_sse2_comilt_sd:
13401 Opc = X86ISD::COMI;
13404 case Intrinsic::x86_sse_comile_ss:
13405 case Intrinsic::x86_sse2_comile_sd:
13406 Opc = X86ISD::COMI;
13409 case Intrinsic::x86_sse_comigt_ss:
13410 case Intrinsic::x86_sse2_comigt_sd:
13411 Opc = X86ISD::COMI;
13414 case Intrinsic::x86_sse_comige_ss:
13415 case Intrinsic::x86_sse2_comige_sd:
13416 Opc = X86ISD::COMI;
13419 case Intrinsic::x86_sse_comineq_ss:
13420 case Intrinsic::x86_sse2_comineq_sd:
13421 Opc = X86ISD::COMI;
13424 case Intrinsic::x86_sse_ucomieq_ss:
13425 case Intrinsic::x86_sse2_ucomieq_sd:
13426 Opc = X86ISD::UCOMI;
13429 case Intrinsic::x86_sse_ucomilt_ss:
13430 case Intrinsic::x86_sse2_ucomilt_sd:
13431 Opc = X86ISD::UCOMI;
13434 case Intrinsic::x86_sse_ucomile_ss:
13435 case Intrinsic::x86_sse2_ucomile_sd:
13436 Opc = X86ISD::UCOMI;
13439 case Intrinsic::x86_sse_ucomigt_ss:
13440 case Intrinsic::x86_sse2_ucomigt_sd:
13441 Opc = X86ISD::UCOMI;
13444 case Intrinsic::x86_sse_ucomige_ss:
13445 case Intrinsic::x86_sse2_ucomige_sd:
13446 Opc = X86ISD::UCOMI;
13449 case Intrinsic::x86_sse_ucomineq_ss:
13450 case Intrinsic::x86_sse2_ucomineq_sd:
13451 Opc = X86ISD::UCOMI;
13456 SDValue LHS = Op.getOperand(1);
13457 SDValue RHS = Op.getOperand(2);
13458 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13459 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13460 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13461 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13462 DAG.getConstant(X86CC, MVT::i8), Cond);
13463 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13466 // Arithmetic intrinsics.
13467 case Intrinsic::x86_sse2_pmulu_dq:
13468 case Intrinsic::x86_avx2_pmulu_dq:
13469 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13470 Op.getOperand(1), Op.getOperand(2));
13472 case Intrinsic::x86_sse41_pmuldq:
13473 case Intrinsic::x86_avx2_pmul_dq:
13474 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13475 Op.getOperand(1), Op.getOperand(2));
13477 case Intrinsic::x86_sse2_pmulhu_w:
13478 case Intrinsic::x86_avx2_pmulhu_w:
13479 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13480 Op.getOperand(1), Op.getOperand(2));
13482 case Intrinsic::x86_sse2_pmulh_w:
13483 case Intrinsic::x86_avx2_pmulh_w:
13484 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13485 Op.getOperand(1), Op.getOperand(2));
13487 // SSE2/AVX2 sub with unsigned saturation intrinsics
13488 case Intrinsic::x86_sse2_psubus_b:
13489 case Intrinsic::x86_sse2_psubus_w:
13490 case Intrinsic::x86_avx2_psubus_b:
13491 case Intrinsic::x86_avx2_psubus_w:
13492 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13493 Op.getOperand(1), Op.getOperand(2));
13495 // SSE3/AVX horizontal add/sub intrinsics
13496 case Intrinsic::x86_sse3_hadd_ps:
13497 case Intrinsic::x86_sse3_hadd_pd:
13498 case Intrinsic::x86_avx_hadd_ps_256:
13499 case Intrinsic::x86_avx_hadd_pd_256:
13500 case Intrinsic::x86_sse3_hsub_ps:
13501 case Intrinsic::x86_sse3_hsub_pd:
13502 case Intrinsic::x86_avx_hsub_ps_256:
13503 case Intrinsic::x86_avx_hsub_pd_256:
13504 case Intrinsic::x86_ssse3_phadd_w_128:
13505 case Intrinsic::x86_ssse3_phadd_d_128:
13506 case Intrinsic::x86_avx2_phadd_w:
13507 case Intrinsic::x86_avx2_phadd_d:
13508 case Intrinsic::x86_ssse3_phsub_w_128:
13509 case Intrinsic::x86_ssse3_phsub_d_128:
13510 case Intrinsic::x86_avx2_phsub_w:
13511 case Intrinsic::x86_avx2_phsub_d: {
13514 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13515 case Intrinsic::x86_sse3_hadd_ps:
13516 case Intrinsic::x86_sse3_hadd_pd:
13517 case Intrinsic::x86_avx_hadd_ps_256:
13518 case Intrinsic::x86_avx_hadd_pd_256:
13519 Opcode = X86ISD::FHADD;
13521 case Intrinsic::x86_sse3_hsub_ps:
13522 case Intrinsic::x86_sse3_hsub_pd:
13523 case Intrinsic::x86_avx_hsub_ps_256:
13524 case Intrinsic::x86_avx_hsub_pd_256:
13525 Opcode = X86ISD::FHSUB;
13527 case Intrinsic::x86_ssse3_phadd_w_128:
13528 case Intrinsic::x86_ssse3_phadd_d_128:
13529 case Intrinsic::x86_avx2_phadd_w:
13530 case Intrinsic::x86_avx2_phadd_d:
13531 Opcode = X86ISD::HADD;
13533 case Intrinsic::x86_ssse3_phsub_w_128:
13534 case Intrinsic::x86_ssse3_phsub_d_128:
13535 case Intrinsic::x86_avx2_phsub_w:
13536 case Intrinsic::x86_avx2_phsub_d:
13537 Opcode = X86ISD::HSUB;
13540 return DAG.getNode(Opcode, dl, Op.getValueType(),
13541 Op.getOperand(1), Op.getOperand(2));
13544 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13545 case Intrinsic::x86_sse2_pmaxu_b:
13546 case Intrinsic::x86_sse41_pmaxuw:
13547 case Intrinsic::x86_sse41_pmaxud:
13548 case Intrinsic::x86_avx2_pmaxu_b:
13549 case Intrinsic::x86_avx2_pmaxu_w:
13550 case Intrinsic::x86_avx2_pmaxu_d:
13551 case Intrinsic::x86_sse2_pminu_b:
13552 case Intrinsic::x86_sse41_pminuw:
13553 case Intrinsic::x86_sse41_pminud:
13554 case Intrinsic::x86_avx2_pminu_b:
13555 case Intrinsic::x86_avx2_pminu_w:
13556 case Intrinsic::x86_avx2_pminu_d:
13557 case Intrinsic::x86_sse41_pmaxsb:
13558 case Intrinsic::x86_sse2_pmaxs_w:
13559 case Intrinsic::x86_sse41_pmaxsd:
13560 case Intrinsic::x86_avx2_pmaxs_b:
13561 case Intrinsic::x86_avx2_pmaxs_w:
13562 case Intrinsic::x86_avx2_pmaxs_d:
13563 case Intrinsic::x86_sse41_pminsb:
13564 case Intrinsic::x86_sse2_pmins_w:
13565 case Intrinsic::x86_sse41_pminsd:
13566 case Intrinsic::x86_avx2_pmins_b:
13567 case Intrinsic::x86_avx2_pmins_w:
13568 case Intrinsic::x86_avx2_pmins_d: {
13571 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13572 case Intrinsic::x86_sse2_pmaxu_b:
13573 case Intrinsic::x86_sse41_pmaxuw:
13574 case Intrinsic::x86_sse41_pmaxud:
13575 case Intrinsic::x86_avx2_pmaxu_b:
13576 case Intrinsic::x86_avx2_pmaxu_w:
13577 case Intrinsic::x86_avx2_pmaxu_d:
13578 Opcode = X86ISD::UMAX;
13580 case Intrinsic::x86_sse2_pminu_b:
13581 case Intrinsic::x86_sse41_pminuw:
13582 case Intrinsic::x86_sse41_pminud:
13583 case Intrinsic::x86_avx2_pminu_b:
13584 case Intrinsic::x86_avx2_pminu_w:
13585 case Intrinsic::x86_avx2_pminu_d:
13586 Opcode = X86ISD::UMIN;
13588 case Intrinsic::x86_sse41_pmaxsb:
13589 case Intrinsic::x86_sse2_pmaxs_w:
13590 case Intrinsic::x86_sse41_pmaxsd:
13591 case Intrinsic::x86_avx2_pmaxs_b:
13592 case Intrinsic::x86_avx2_pmaxs_w:
13593 case Intrinsic::x86_avx2_pmaxs_d:
13594 Opcode = X86ISD::SMAX;
13596 case Intrinsic::x86_sse41_pminsb:
13597 case Intrinsic::x86_sse2_pmins_w:
13598 case Intrinsic::x86_sse41_pminsd:
13599 case Intrinsic::x86_avx2_pmins_b:
13600 case Intrinsic::x86_avx2_pmins_w:
13601 case Intrinsic::x86_avx2_pmins_d:
13602 Opcode = X86ISD::SMIN;
13605 return DAG.getNode(Opcode, dl, Op.getValueType(),
13606 Op.getOperand(1), Op.getOperand(2));
13609 // SSE/SSE2/AVX floating point max/min intrinsics.
13610 case Intrinsic::x86_sse_max_ps:
13611 case Intrinsic::x86_sse2_max_pd:
13612 case Intrinsic::x86_avx_max_ps_256:
13613 case Intrinsic::x86_avx_max_pd_256:
13614 case Intrinsic::x86_sse_min_ps:
13615 case Intrinsic::x86_sse2_min_pd:
13616 case Intrinsic::x86_avx_min_ps_256:
13617 case Intrinsic::x86_avx_min_pd_256: {
13620 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13621 case Intrinsic::x86_sse_max_ps:
13622 case Intrinsic::x86_sse2_max_pd:
13623 case Intrinsic::x86_avx_max_ps_256:
13624 case Intrinsic::x86_avx_max_pd_256:
13625 Opcode = X86ISD::FMAX;
13627 case Intrinsic::x86_sse_min_ps:
13628 case Intrinsic::x86_sse2_min_pd:
13629 case Intrinsic::x86_avx_min_ps_256:
13630 case Intrinsic::x86_avx_min_pd_256:
13631 Opcode = X86ISD::FMIN;
13634 return DAG.getNode(Opcode, dl, Op.getValueType(),
13635 Op.getOperand(1), Op.getOperand(2));
13638 // AVX2 variable shift intrinsics
13639 case Intrinsic::x86_avx2_psllv_d:
13640 case Intrinsic::x86_avx2_psllv_q:
13641 case Intrinsic::x86_avx2_psllv_d_256:
13642 case Intrinsic::x86_avx2_psllv_q_256:
13643 case Intrinsic::x86_avx2_psrlv_d:
13644 case Intrinsic::x86_avx2_psrlv_q:
13645 case Intrinsic::x86_avx2_psrlv_d_256:
13646 case Intrinsic::x86_avx2_psrlv_q_256:
13647 case Intrinsic::x86_avx2_psrav_d:
13648 case Intrinsic::x86_avx2_psrav_d_256: {
13651 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13652 case Intrinsic::x86_avx2_psllv_d:
13653 case Intrinsic::x86_avx2_psllv_q:
13654 case Intrinsic::x86_avx2_psllv_d_256:
13655 case Intrinsic::x86_avx2_psllv_q_256:
13658 case Intrinsic::x86_avx2_psrlv_d:
13659 case Intrinsic::x86_avx2_psrlv_q:
13660 case Intrinsic::x86_avx2_psrlv_d_256:
13661 case Intrinsic::x86_avx2_psrlv_q_256:
13664 case Intrinsic::x86_avx2_psrav_d:
13665 case Intrinsic::x86_avx2_psrav_d_256:
13669 return DAG.getNode(Opcode, dl, Op.getValueType(),
13670 Op.getOperand(1), Op.getOperand(2));
13673 case Intrinsic::x86_sse2_packssdw_128:
13674 case Intrinsic::x86_sse2_packsswb_128:
13675 case Intrinsic::x86_avx2_packssdw:
13676 case Intrinsic::x86_avx2_packsswb:
13677 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13678 Op.getOperand(1), Op.getOperand(2));
13680 case Intrinsic::x86_sse2_packuswb_128:
13681 case Intrinsic::x86_sse41_packusdw:
13682 case Intrinsic::x86_avx2_packuswb:
13683 case Intrinsic::x86_avx2_packusdw:
13684 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13685 Op.getOperand(1), Op.getOperand(2));
13687 case Intrinsic::x86_ssse3_pshuf_b_128:
13688 case Intrinsic::x86_avx2_pshuf_b:
13689 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13690 Op.getOperand(1), Op.getOperand(2));
13692 case Intrinsic::x86_sse2_pshuf_d:
13693 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13694 Op.getOperand(1), Op.getOperand(2));
13696 case Intrinsic::x86_sse2_pshufl_w:
13697 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13698 Op.getOperand(1), Op.getOperand(2));
13700 case Intrinsic::x86_sse2_pshufh_w:
13701 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13702 Op.getOperand(1), Op.getOperand(2));
13704 case Intrinsic::x86_ssse3_psign_b_128:
13705 case Intrinsic::x86_ssse3_psign_w_128:
13706 case Intrinsic::x86_ssse3_psign_d_128:
13707 case Intrinsic::x86_avx2_psign_b:
13708 case Intrinsic::x86_avx2_psign_w:
13709 case Intrinsic::x86_avx2_psign_d:
13710 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13711 Op.getOperand(1), Op.getOperand(2));
13713 case Intrinsic::x86_sse41_insertps:
13714 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13715 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13717 case Intrinsic::x86_avx_vperm2f128_ps_256:
13718 case Intrinsic::x86_avx_vperm2f128_pd_256:
13719 case Intrinsic::x86_avx_vperm2f128_si_256:
13720 case Intrinsic::x86_avx2_vperm2i128:
13721 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13722 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13724 case Intrinsic::x86_avx2_permd:
13725 case Intrinsic::x86_avx2_permps:
13726 // Operands intentionally swapped. Mask is last operand to intrinsic,
13727 // but second operand for node/instruction.
13728 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13729 Op.getOperand(2), Op.getOperand(1));
13731 case Intrinsic::x86_sse_sqrt_ps:
13732 case Intrinsic::x86_sse2_sqrt_pd:
13733 case Intrinsic::x86_avx_sqrt_ps_256:
13734 case Intrinsic::x86_avx_sqrt_pd_256:
13735 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13737 // ptest and testp intrinsics. The intrinsic these come from are designed to
13738 // return an integer value, not just an instruction so lower it to the ptest
13739 // or testp pattern and a setcc for the result.
13740 case Intrinsic::x86_sse41_ptestz:
13741 case Intrinsic::x86_sse41_ptestc:
13742 case Intrinsic::x86_sse41_ptestnzc:
13743 case Intrinsic::x86_avx_ptestz_256:
13744 case Intrinsic::x86_avx_ptestc_256:
13745 case Intrinsic::x86_avx_ptestnzc_256:
13746 case Intrinsic::x86_avx_vtestz_ps:
13747 case Intrinsic::x86_avx_vtestc_ps:
13748 case Intrinsic::x86_avx_vtestnzc_ps:
13749 case Intrinsic::x86_avx_vtestz_pd:
13750 case Intrinsic::x86_avx_vtestc_pd:
13751 case Intrinsic::x86_avx_vtestnzc_pd:
13752 case Intrinsic::x86_avx_vtestz_ps_256:
13753 case Intrinsic::x86_avx_vtestc_ps_256:
13754 case Intrinsic::x86_avx_vtestnzc_ps_256:
13755 case Intrinsic::x86_avx_vtestz_pd_256:
13756 case Intrinsic::x86_avx_vtestc_pd_256:
13757 case Intrinsic::x86_avx_vtestnzc_pd_256: {
13758 bool IsTestPacked = false;
13761 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13762 case Intrinsic::x86_avx_vtestz_ps:
13763 case Intrinsic::x86_avx_vtestz_pd:
13764 case Intrinsic::x86_avx_vtestz_ps_256:
13765 case Intrinsic::x86_avx_vtestz_pd_256:
13766 IsTestPacked = true; // Fallthrough
13767 case Intrinsic::x86_sse41_ptestz:
13768 case Intrinsic::x86_avx_ptestz_256:
13770 X86CC = X86::COND_E;
13772 case Intrinsic::x86_avx_vtestc_ps:
13773 case Intrinsic::x86_avx_vtestc_pd:
13774 case Intrinsic::x86_avx_vtestc_ps_256:
13775 case Intrinsic::x86_avx_vtestc_pd_256:
13776 IsTestPacked = true; // Fallthrough
13777 case Intrinsic::x86_sse41_ptestc:
13778 case Intrinsic::x86_avx_ptestc_256:
13780 X86CC = X86::COND_B;
13782 case Intrinsic::x86_avx_vtestnzc_ps:
13783 case Intrinsic::x86_avx_vtestnzc_pd:
13784 case Intrinsic::x86_avx_vtestnzc_ps_256:
13785 case Intrinsic::x86_avx_vtestnzc_pd_256:
13786 IsTestPacked = true; // Fallthrough
13787 case Intrinsic::x86_sse41_ptestnzc:
13788 case Intrinsic::x86_avx_ptestnzc_256:
13790 X86CC = X86::COND_A;
13794 SDValue LHS = Op.getOperand(1);
13795 SDValue RHS = Op.getOperand(2);
13796 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13797 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13798 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13799 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13800 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13802 case Intrinsic::x86_avx512_kortestz_w:
13803 case Intrinsic::x86_avx512_kortestc_w: {
13804 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13805 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13806 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13807 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13808 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13809 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13810 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13813 // SSE/AVX shift intrinsics
13814 case Intrinsic::x86_sse2_psll_w:
13815 case Intrinsic::x86_sse2_psll_d:
13816 case Intrinsic::x86_sse2_psll_q:
13817 case Intrinsic::x86_avx2_psll_w:
13818 case Intrinsic::x86_avx2_psll_d:
13819 case Intrinsic::x86_avx2_psll_q:
13820 case Intrinsic::x86_sse2_psrl_w:
13821 case Intrinsic::x86_sse2_psrl_d:
13822 case Intrinsic::x86_sse2_psrl_q:
13823 case Intrinsic::x86_avx2_psrl_w:
13824 case Intrinsic::x86_avx2_psrl_d:
13825 case Intrinsic::x86_avx2_psrl_q:
13826 case Intrinsic::x86_sse2_psra_w:
13827 case Intrinsic::x86_sse2_psra_d:
13828 case Intrinsic::x86_avx2_psra_w:
13829 case Intrinsic::x86_avx2_psra_d: {
13832 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13833 case Intrinsic::x86_sse2_psll_w:
13834 case Intrinsic::x86_sse2_psll_d:
13835 case Intrinsic::x86_sse2_psll_q:
13836 case Intrinsic::x86_avx2_psll_w:
13837 case Intrinsic::x86_avx2_psll_d:
13838 case Intrinsic::x86_avx2_psll_q:
13839 Opcode = X86ISD::VSHL;
13841 case Intrinsic::x86_sse2_psrl_w:
13842 case Intrinsic::x86_sse2_psrl_d:
13843 case Intrinsic::x86_sse2_psrl_q:
13844 case Intrinsic::x86_avx2_psrl_w:
13845 case Intrinsic::x86_avx2_psrl_d:
13846 case Intrinsic::x86_avx2_psrl_q:
13847 Opcode = X86ISD::VSRL;
13849 case Intrinsic::x86_sse2_psra_w:
13850 case Intrinsic::x86_sse2_psra_d:
13851 case Intrinsic::x86_avx2_psra_w:
13852 case Intrinsic::x86_avx2_psra_d:
13853 Opcode = X86ISD::VSRA;
13856 return DAG.getNode(Opcode, dl, Op.getValueType(),
13857 Op.getOperand(1), Op.getOperand(2));
13860 // SSE/AVX immediate shift intrinsics
13861 case Intrinsic::x86_sse2_pslli_w:
13862 case Intrinsic::x86_sse2_pslli_d:
13863 case Intrinsic::x86_sse2_pslli_q:
13864 case Intrinsic::x86_avx2_pslli_w:
13865 case Intrinsic::x86_avx2_pslli_d:
13866 case Intrinsic::x86_avx2_pslli_q:
13867 case Intrinsic::x86_sse2_psrli_w:
13868 case Intrinsic::x86_sse2_psrli_d:
13869 case Intrinsic::x86_sse2_psrli_q:
13870 case Intrinsic::x86_avx2_psrli_w:
13871 case Intrinsic::x86_avx2_psrli_d:
13872 case Intrinsic::x86_avx2_psrli_q:
13873 case Intrinsic::x86_sse2_psrai_w:
13874 case Intrinsic::x86_sse2_psrai_d:
13875 case Intrinsic::x86_avx2_psrai_w:
13876 case Intrinsic::x86_avx2_psrai_d: {
13879 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13880 case Intrinsic::x86_sse2_pslli_w:
13881 case Intrinsic::x86_sse2_pslli_d:
13882 case Intrinsic::x86_sse2_pslli_q:
13883 case Intrinsic::x86_avx2_pslli_w:
13884 case Intrinsic::x86_avx2_pslli_d:
13885 case Intrinsic::x86_avx2_pslli_q:
13886 Opcode = X86ISD::VSHLI;
13888 case Intrinsic::x86_sse2_psrli_w:
13889 case Intrinsic::x86_sse2_psrli_d:
13890 case Intrinsic::x86_sse2_psrli_q:
13891 case Intrinsic::x86_avx2_psrli_w:
13892 case Intrinsic::x86_avx2_psrli_d:
13893 case Intrinsic::x86_avx2_psrli_q:
13894 Opcode = X86ISD::VSRLI;
13896 case Intrinsic::x86_sse2_psrai_w:
13897 case Intrinsic::x86_sse2_psrai_d:
13898 case Intrinsic::x86_avx2_psrai_w:
13899 case Intrinsic::x86_avx2_psrai_d:
13900 Opcode = X86ISD::VSRAI;
13903 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13904 Op.getOperand(1), Op.getOperand(2), DAG);
13907 case Intrinsic::x86_sse42_pcmpistria128:
13908 case Intrinsic::x86_sse42_pcmpestria128:
13909 case Intrinsic::x86_sse42_pcmpistric128:
13910 case Intrinsic::x86_sse42_pcmpestric128:
13911 case Intrinsic::x86_sse42_pcmpistrio128:
13912 case Intrinsic::x86_sse42_pcmpestrio128:
13913 case Intrinsic::x86_sse42_pcmpistris128:
13914 case Intrinsic::x86_sse42_pcmpestris128:
13915 case Intrinsic::x86_sse42_pcmpistriz128:
13916 case Intrinsic::x86_sse42_pcmpestriz128: {
13920 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13921 case Intrinsic::x86_sse42_pcmpistria128:
13922 Opcode = X86ISD::PCMPISTRI;
13923 X86CC = X86::COND_A;
13925 case Intrinsic::x86_sse42_pcmpestria128:
13926 Opcode = X86ISD::PCMPESTRI;
13927 X86CC = X86::COND_A;
13929 case Intrinsic::x86_sse42_pcmpistric128:
13930 Opcode = X86ISD::PCMPISTRI;
13931 X86CC = X86::COND_B;
13933 case Intrinsic::x86_sse42_pcmpestric128:
13934 Opcode = X86ISD::PCMPESTRI;
13935 X86CC = X86::COND_B;
13937 case Intrinsic::x86_sse42_pcmpistrio128:
13938 Opcode = X86ISD::PCMPISTRI;
13939 X86CC = X86::COND_O;
13941 case Intrinsic::x86_sse42_pcmpestrio128:
13942 Opcode = X86ISD::PCMPESTRI;
13943 X86CC = X86::COND_O;
13945 case Intrinsic::x86_sse42_pcmpistris128:
13946 Opcode = X86ISD::PCMPISTRI;
13947 X86CC = X86::COND_S;
13949 case Intrinsic::x86_sse42_pcmpestris128:
13950 Opcode = X86ISD::PCMPESTRI;
13951 X86CC = X86::COND_S;
13953 case Intrinsic::x86_sse42_pcmpistriz128:
13954 Opcode = X86ISD::PCMPISTRI;
13955 X86CC = X86::COND_E;
13957 case Intrinsic::x86_sse42_pcmpestriz128:
13958 Opcode = X86ISD::PCMPESTRI;
13959 X86CC = X86::COND_E;
13962 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
13963 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13964 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
13965 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13966 DAG.getConstant(X86CC, MVT::i8),
13967 SDValue(PCMP.getNode(), 1));
13968 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13971 case Intrinsic::x86_sse42_pcmpistri128:
13972 case Intrinsic::x86_sse42_pcmpestri128: {
13974 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
13975 Opcode = X86ISD::PCMPISTRI;
13977 Opcode = X86ISD::PCMPESTRI;
13979 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
13980 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13981 return DAG.getNode(Opcode, dl, VTs, NewOps);
13983 case Intrinsic::x86_fma_vfmadd_ps:
13984 case Intrinsic::x86_fma_vfmadd_pd:
13985 case Intrinsic::x86_fma_vfmsub_ps:
13986 case Intrinsic::x86_fma_vfmsub_pd:
13987 case Intrinsic::x86_fma_vfnmadd_ps:
13988 case Intrinsic::x86_fma_vfnmadd_pd:
13989 case Intrinsic::x86_fma_vfnmsub_ps:
13990 case Intrinsic::x86_fma_vfnmsub_pd:
13991 case Intrinsic::x86_fma_vfmaddsub_ps:
13992 case Intrinsic::x86_fma_vfmaddsub_pd:
13993 case Intrinsic::x86_fma_vfmsubadd_ps:
13994 case Intrinsic::x86_fma_vfmsubadd_pd:
13995 case Intrinsic::x86_fma_vfmadd_ps_256:
13996 case Intrinsic::x86_fma_vfmadd_pd_256:
13997 case Intrinsic::x86_fma_vfmsub_ps_256:
13998 case Intrinsic::x86_fma_vfmsub_pd_256:
13999 case Intrinsic::x86_fma_vfnmadd_ps_256:
14000 case Intrinsic::x86_fma_vfnmadd_pd_256:
14001 case Intrinsic::x86_fma_vfnmsub_ps_256:
14002 case Intrinsic::x86_fma_vfnmsub_pd_256:
14003 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14004 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14005 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14006 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14007 case Intrinsic::x86_fma_vfmadd_ps_512:
14008 case Intrinsic::x86_fma_vfmadd_pd_512:
14009 case Intrinsic::x86_fma_vfmsub_ps_512:
14010 case Intrinsic::x86_fma_vfmsub_pd_512:
14011 case Intrinsic::x86_fma_vfnmadd_ps_512:
14012 case Intrinsic::x86_fma_vfnmadd_pd_512:
14013 case Intrinsic::x86_fma_vfnmsub_ps_512:
14014 case Intrinsic::x86_fma_vfnmsub_pd_512:
14015 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14016 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14017 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14018 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14021 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14022 case Intrinsic::x86_fma_vfmadd_ps:
14023 case Intrinsic::x86_fma_vfmadd_pd:
14024 case Intrinsic::x86_fma_vfmadd_ps_256:
14025 case Intrinsic::x86_fma_vfmadd_pd_256:
14026 case Intrinsic::x86_fma_vfmadd_ps_512:
14027 case Intrinsic::x86_fma_vfmadd_pd_512:
14028 Opc = X86ISD::FMADD;
14030 case Intrinsic::x86_fma_vfmsub_ps:
14031 case Intrinsic::x86_fma_vfmsub_pd:
14032 case Intrinsic::x86_fma_vfmsub_ps_256:
14033 case Intrinsic::x86_fma_vfmsub_pd_256:
14034 case Intrinsic::x86_fma_vfmsub_ps_512:
14035 case Intrinsic::x86_fma_vfmsub_pd_512:
14036 Opc = X86ISD::FMSUB;
14038 case Intrinsic::x86_fma_vfnmadd_ps:
14039 case Intrinsic::x86_fma_vfnmadd_pd:
14040 case Intrinsic::x86_fma_vfnmadd_ps_256:
14041 case Intrinsic::x86_fma_vfnmadd_pd_256:
14042 case Intrinsic::x86_fma_vfnmadd_ps_512:
14043 case Intrinsic::x86_fma_vfnmadd_pd_512:
14044 Opc = X86ISD::FNMADD;
14046 case Intrinsic::x86_fma_vfnmsub_ps:
14047 case Intrinsic::x86_fma_vfnmsub_pd:
14048 case Intrinsic::x86_fma_vfnmsub_ps_256:
14049 case Intrinsic::x86_fma_vfnmsub_pd_256:
14050 case Intrinsic::x86_fma_vfnmsub_ps_512:
14051 case Intrinsic::x86_fma_vfnmsub_pd_512:
14052 Opc = X86ISD::FNMSUB;
14054 case Intrinsic::x86_fma_vfmaddsub_ps:
14055 case Intrinsic::x86_fma_vfmaddsub_pd:
14056 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14057 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14058 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14059 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14060 Opc = X86ISD::FMADDSUB;
14062 case Intrinsic::x86_fma_vfmsubadd_ps:
14063 case Intrinsic::x86_fma_vfmsubadd_pd:
14064 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14065 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14066 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14067 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14068 Opc = X86ISD::FMSUBADD;
14072 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14073 Op.getOperand(2), Op.getOperand(3));
14078 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14079 SDValue Src, SDValue Mask, SDValue Base,
14080 SDValue Index, SDValue ScaleOp, SDValue Chain,
14081 const X86Subtarget * Subtarget) {
14083 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14084 assert(C && "Invalid scale type");
14085 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14086 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14087 Index.getSimpleValueType().getVectorNumElements());
14089 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14091 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14093 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14094 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14095 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14096 SDValue Segment = DAG.getRegister(0, MVT::i32);
14097 if (Src.getOpcode() == ISD::UNDEF)
14098 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14099 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14100 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14101 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14102 return DAG.getMergeValues(RetOps, dl);
14105 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14106 SDValue Src, SDValue Mask, SDValue Base,
14107 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14109 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14110 assert(C && "Invalid scale type");
14111 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14112 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14113 SDValue Segment = DAG.getRegister(0, MVT::i32);
14114 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14115 Index.getSimpleValueType().getVectorNumElements());
14117 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14119 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14121 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14122 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14123 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14124 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14125 return SDValue(Res, 1);
14128 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14129 SDValue Mask, SDValue Base, SDValue Index,
14130 SDValue ScaleOp, SDValue Chain) {
14132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14133 assert(C && "Invalid scale type");
14134 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14135 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14136 SDValue Segment = DAG.getRegister(0, MVT::i32);
14138 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14140 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14142 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14144 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14145 //SDVTList VTs = DAG.getVTList(MVT::Other);
14146 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14147 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14148 return SDValue(Res, 0);
14151 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14152 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14153 // also used to custom lower READCYCLECOUNTER nodes.
14154 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14155 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14156 SmallVectorImpl<SDValue> &Results) {
14157 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14158 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14161 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14162 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14163 // and the EAX register is loaded with the low-order 32 bits.
14164 if (Subtarget->is64Bit()) {
14165 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14166 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14169 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14170 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14173 SDValue Chain = HI.getValue(1);
14175 if (Opcode == X86ISD::RDTSCP_DAG) {
14176 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14178 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14179 // the ECX register. Add 'ecx' explicitly to the chain.
14180 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14182 // Explicitly store the content of ECX at the location passed in input
14183 // to the 'rdtscp' intrinsic.
14184 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14185 MachinePointerInfo(), false, false, 0);
14188 if (Subtarget->is64Bit()) {
14189 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14190 // the EAX register is loaded with the low-order 32 bits.
14191 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14192 DAG.getConstant(32, MVT::i8));
14193 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14194 Results.push_back(Chain);
14198 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14199 SDValue Ops[] = { LO, HI };
14200 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14201 Results.push_back(Pair);
14202 Results.push_back(Chain);
14205 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14206 SelectionDAG &DAG) {
14207 SmallVector<SDValue, 2> Results;
14209 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14211 return DAG.getMergeValues(Results, DL);
14214 enum IntrinsicType {
14215 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
14218 struct IntrinsicData {
14219 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14220 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14221 IntrinsicType Type;
14226 std::map < unsigned, IntrinsicData> IntrMap;
14227 static void InitIntinsicsMap() {
14228 static bool Initialized = false;
14231 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14232 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14233 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14234 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14235 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14236 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14237 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14238 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14239 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14240 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14241 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14242 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14243 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14244 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14245 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14246 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14247 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14248 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14250 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14251 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14252 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14253 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14254 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14255 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14256 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14257 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14258 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14259 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14260 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14261 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14262 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14263 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14264 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14265 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14267 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14268 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14269 X86::VGATHERPF1QPSm)));
14270 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14271 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14272 X86::VGATHERPF1QPDm)));
14273 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14274 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14275 X86::VGATHERPF1DPDm)));
14276 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14277 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14278 X86::VGATHERPF1DPSm)));
14279 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14280 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14281 X86::VSCATTERPF1QPSm)));
14282 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14283 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14284 X86::VSCATTERPF1QPDm)));
14285 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14286 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14287 X86::VSCATTERPF1DPDm)));
14288 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14289 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14290 X86::VSCATTERPF1DPSm)));
14291 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14292 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14293 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14294 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14295 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14296 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14297 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14298 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14299 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14300 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14301 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14302 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14303 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14304 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14305 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14306 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14307 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14308 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14309 Initialized = true;
14312 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14313 SelectionDAG &DAG) {
14314 InitIntinsicsMap();
14315 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14316 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14317 if (itr == IntrMap.end())
14321 IntrinsicData Intr = itr->second;
14322 switch(Intr.Type) {
14325 // Emit the node with the right value type.
14326 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14327 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14329 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14330 // Otherwise return the value from Rand, which is always 0, casted to i32.
14331 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14332 DAG.getConstant(1, Op->getValueType(1)),
14333 DAG.getConstant(X86::COND_B, MVT::i32),
14334 SDValue(Result.getNode(), 1) };
14335 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14336 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14339 // Return { result, isValid, chain }.
14340 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14341 SDValue(Result.getNode(), 2));
14344 //gather(v1, mask, index, base, scale);
14345 SDValue Chain = Op.getOperand(0);
14346 SDValue Src = Op.getOperand(2);
14347 SDValue Base = Op.getOperand(3);
14348 SDValue Index = Op.getOperand(4);
14349 SDValue Mask = Op.getOperand(5);
14350 SDValue Scale = Op.getOperand(6);
14351 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14355 //scatter(base, mask, index, v1, scale);
14356 SDValue Chain = Op.getOperand(0);
14357 SDValue Base = Op.getOperand(2);
14358 SDValue Mask = Op.getOperand(3);
14359 SDValue Index = Op.getOperand(4);
14360 SDValue Src = Op.getOperand(5);
14361 SDValue Scale = Op.getOperand(6);
14362 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14365 SDValue Hint = Op.getOperand(6);
14367 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14368 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14369 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14370 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14371 SDValue Chain = Op.getOperand(0);
14372 SDValue Mask = Op.getOperand(2);
14373 SDValue Index = Op.getOperand(3);
14374 SDValue Base = Op.getOperand(4);
14375 SDValue Scale = Op.getOperand(5);
14376 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14378 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14380 SmallVector<SDValue, 2> Results;
14381 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14382 return DAG.getMergeValues(Results, dl);
14384 // XTEST intrinsics.
14386 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14387 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14388 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14389 DAG.getConstant(X86::COND_NE, MVT::i8),
14391 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14392 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14393 Ret, SDValue(InTrans.getNode(), 1));
14396 llvm_unreachable("Unknown Intrinsic Type");
14399 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14400 SelectionDAG &DAG) const {
14401 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14402 MFI->setReturnAddressIsTaken(true);
14404 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14407 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14409 EVT PtrVT = getPointerTy();
14412 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14413 const X86RegisterInfo *RegInfo =
14414 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14415 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14416 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14417 DAG.getNode(ISD::ADD, dl, PtrVT,
14418 FrameAddr, Offset),
14419 MachinePointerInfo(), false, false, false, 0);
14422 // Just load the return address.
14423 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14424 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14425 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14428 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14429 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14430 MFI->setFrameAddressIsTaken(true);
14432 EVT VT = Op.getValueType();
14433 SDLoc dl(Op); // FIXME probably not meaningful
14434 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14435 const X86RegisterInfo *RegInfo =
14436 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14437 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14438 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14439 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14440 "Invalid Frame Register!");
14441 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14443 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14444 MachinePointerInfo(),
14445 false, false, false, 0);
14449 // FIXME? Maybe this could be a TableGen attribute on some registers and
14450 // this table could be generated automatically from RegInfo.
14451 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14453 unsigned Reg = StringSwitch<unsigned>(RegName)
14454 .Case("esp", X86::ESP)
14455 .Case("rsp", X86::RSP)
14459 report_fatal_error("Invalid register name global variable");
14462 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14463 SelectionDAG &DAG) const {
14464 const X86RegisterInfo *RegInfo =
14465 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14466 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14469 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14470 SDValue Chain = Op.getOperand(0);
14471 SDValue Offset = Op.getOperand(1);
14472 SDValue Handler = Op.getOperand(2);
14475 EVT PtrVT = getPointerTy();
14476 const X86RegisterInfo *RegInfo =
14477 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14478 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14479 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14480 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14481 "Invalid Frame Register!");
14482 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14483 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14485 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14486 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14487 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14488 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14490 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14492 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14493 DAG.getRegister(StoreAddrReg, PtrVT));
14496 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14497 SelectionDAG &DAG) const {
14499 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14500 DAG.getVTList(MVT::i32, MVT::Other),
14501 Op.getOperand(0), Op.getOperand(1));
14504 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14505 SelectionDAG &DAG) const {
14507 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14508 Op.getOperand(0), Op.getOperand(1));
14511 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14512 return Op.getOperand(0);
14515 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14516 SelectionDAG &DAG) const {
14517 SDValue Root = Op.getOperand(0);
14518 SDValue Trmp = Op.getOperand(1); // trampoline
14519 SDValue FPtr = Op.getOperand(2); // nested function
14520 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14523 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14524 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14526 if (Subtarget->is64Bit()) {
14527 SDValue OutChains[6];
14529 // Large code-model.
14530 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14531 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14533 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14534 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14536 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14538 // Load the pointer to the nested function into R11.
14539 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14540 SDValue Addr = Trmp;
14541 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14542 Addr, MachinePointerInfo(TrmpAddr),
14545 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14546 DAG.getConstant(2, MVT::i64));
14547 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14548 MachinePointerInfo(TrmpAddr, 2),
14551 // Load the 'nest' parameter value into R10.
14552 // R10 is specified in X86CallingConv.td
14553 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14554 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14555 DAG.getConstant(10, MVT::i64));
14556 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14557 Addr, MachinePointerInfo(TrmpAddr, 10),
14560 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14561 DAG.getConstant(12, MVT::i64));
14562 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14563 MachinePointerInfo(TrmpAddr, 12),
14566 // Jump to the nested function.
14567 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14568 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14569 DAG.getConstant(20, MVT::i64));
14570 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14571 Addr, MachinePointerInfo(TrmpAddr, 20),
14574 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14575 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14576 DAG.getConstant(22, MVT::i64));
14577 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14578 MachinePointerInfo(TrmpAddr, 22),
14581 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14583 const Function *Func =
14584 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14585 CallingConv::ID CC = Func->getCallingConv();
14590 llvm_unreachable("Unsupported calling convention");
14591 case CallingConv::C:
14592 case CallingConv::X86_StdCall: {
14593 // Pass 'nest' parameter in ECX.
14594 // Must be kept in sync with X86CallingConv.td
14595 NestReg = X86::ECX;
14597 // Check that ECX wasn't needed by an 'inreg' parameter.
14598 FunctionType *FTy = Func->getFunctionType();
14599 const AttributeSet &Attrs = Func->getAttributes();
14601 if (!Attrs.isEmpty() && !Func->isVarArg()) {
14602 unsigned InRegCount = 0;
14605 for (FunctionType::param_iterator I = FTy->param_begin(),
14606 E = FTy->param_end(); I != E; ++I, ++Idx)
14607 if (Attrs.hasAttribute(Idx, Attribute::InReg))
14608 // FIXME: should only count parameters that are lowered to integers.
14609 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14611 if (InRegCount > 2) {
14612 report_fatal_error("Nest register in use - reduce number of inreg"
14618 case CallingConv::X86_FastCall:
14619 case CallingConv::X86_ThisCall:
14620 case CallingConv::Fast:
14621 // Pass 'nest' parameter in EAX.
14622 // Must be kept in sync with X86CallingConv.td
14623 NestReg = X86::EAX;
14627 SDValue OutChains[4];
14628 SDValue Addr, Disp;
14630 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14631 DAG.getConstant(10, MVT::i32));
14632 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14634 // This is storing the opcode for MOV32ri.
14635 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14636 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14637 OutChains[0] = DAG.getStore(Root, dl,
14638 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14639 Trmp, MachinePointerInfo(TrmpAddr),
14642 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14643 DAG.getConstant(1, MVT::i32));
14644 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14645 MachinePointerInfo(TrmpAddr, 1),
14648 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14649 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14650 DAG.getConstant(5, MVT::i32));
14651 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14652 MachinePointerInfo(TrmpAddr, 5),
14655 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14656 DAG.getConstant(6, MVT::i32));
14657 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14658 MachinePointerInfo(TrmpAddr, 6),
14661 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14665 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14666 SelectionDAG &DAG) const {
14668 The rounding mode is in bits 11:10 of FPSR, and has the following
14670 00 Round to nearest
14675 FLT_ROUNDS, on the other hand, expects the following:
14682 To perform the conversion, we do:
14683 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14686 MachineFunction &MF = DAG.getMachineFunction();
14687 const TargetMachine &TM = MF.getTarget();
14688 const TargetFrameLowering &TFI = *TM.getFrameLowering();
14689 unsigned StackAlignment = TFI.getStackAlignment();
14690 MVT VT = Op.getSimpleValueType();
14693 // Save FP Control Word to stack slot
14694 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14695 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14697 MachineMemOperand *MMO =
14698 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14699 MachineMemOperand::MOStore, 2, 2);
14701 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14702 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14703 DAG.getVTList(MVT::Other),
14704 Ops, MVT::i16, MMO);
14706 // Load FP Control Word from stack slot
14707 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14708 MachinePointerInfo(), false, false, false, 0);
14710 // Transform as necessary
14712 DAG.getNode(ISD::SRL, DL, MVT::i16,
14713 DAG.getNode(ISD::AND, DL, MVT::i16,
14714 CWD, DAG.getConstant(0x800, MVT::i16)),
14715 DAG.getConstant(11, MVT::i8));
14717 DAG.getNode(ISD::SRL, DL, MVT::i16,
14718 DAG.getNode(ISD::AND, DL, MVT::i16,
14719 CWD, DAG.getConstant(0x400, MVT::i16)),
14720 DAG.getConstant(9, MVT::i8));
14723 DAG.getNode(ISD::AND, DL, MVT::i16,
14724 DAG.getNode(ISD::ADD, DL, MVT::i16,
14725 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14726 DAG.getConstant(1, MVT::i16)),
14727 DAG.getConstant(3, MVT::i16));
14729 return DAG.getNode((VT.getSizeInBits() < 16 ?
14730 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14733 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14734 MVT VT = Op.getSimpleValueType();
14736 unsigned NumBits = VT.getSizeInBits();
14739 Op = Op.getOperand(0);
14740 if (VT == MVT::i8) {
14741 // Zero extend to i32 since there is not an i8 bsr.
14743 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14746 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14747 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14748 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14750 // If src is zero (i.e. bsr sets ZF), returns NumBits.
14753 DAG.getConstant(NumBits+NumBits-1, OpVT),
14754 DAG.getConstant(X86::COND_E, MVT::i8),
14757 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14759 // Finally xor with NumBits-1.
14760 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14763 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14767 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14768 MVT VT = Op.getSimpleValueType();
14770 unsigned NumBits = VT.getSizeInBits();
14773 Op = Op.getOperand(0);
14774 if (VT == MVT::i8) {
14775 // Zero extend to i32 since there is not an i8 bsr.
14777 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14780 // Issue a bsr (scan bits in reverse).
14781 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14782 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14784 // And xor with NumBits-1.
14785 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14788 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14792 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14793 MVT VT = Op.getSimpleValueType();
14794 unsigned NumBits = VT.getSizeInBits();
14796 Op = Op.getOperand(0);
14798 // Issue a bsf (scan bits forward) which also sets EFLAGS.
14799 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14800 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14802 // If src is zero (i.e. bsf sets ZF), returns NumBits.
14805 DAG.getConstant(NumBits, VT),
14806 DAG.getConstant(X86::COND_E, MVT::i8),
14809 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14812 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14813 // ones, and then concatenate the result back.
14814 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14815 MVT VT = Op.getSimpleValueType();
14817 assert(VT.is256BitVector() && VT.isInteger() &&
14818 "Unsupported value type for operation");
14820 unsigned NumElems = VT.getVectorNumElements();
14823 // Extract the LHS vectors
14824 SDValue LHS = Op.getOperand(0);
14825 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14826 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14828 // Extract the RHS vectors
14829 SDValue RHS = Op.getOperand(1);
14830 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14831 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14833 MVT EltVT = VT.getVectorElementType();
14834 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14836 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14837 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14838 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14841 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14842 assert(Op.getSimpleValueType().is256BitVector() &&
14843 Op.getSimpleValueType().isInteger() &&
14844 "Only handle AVX 256-bit vector integer operation");
14845 return Lower256IntArith(Op, DAG);
14848 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14849 assert(Op.getSimpleValueType().is256BitVector() &&
14850 Op.getSimpleValueType().isInteger() &&
14851 "Only handle AVX 256-bit vector integer operation");
14852 return Lower256IntArith(Op, DAG);
14855 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14856 SelectionDAG &DAG) {
14858 MVT VT = Op.getSimpleValueType();
14860 // Decompose 256-bit ops into smaller 128-bit ops.
14861 if (VT.is256BitVector() && !Subtarget->hasInt256())
14862 return Lower256IntArith(Op, DAG);
14864 SDValue A = Op.getOperand(0);
14865 SDValue B = Op.getOperand(1);
14867 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
14868 if (VT == MVT::v4i32) {
14869 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
14870 "Should not custom lower when pmuldq is available!");
14872 // Extract the odd parts.
14873 static const int UnpackMask[] = { 1, -1, 3, -1 };
14874 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
14875 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
14877 // Multiply the even parts.
14878 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
14879 // Now multiply odd parts.
14880 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
14882 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
14883 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
14885 // Merge the two vectors back together with a shuffle. This expands into 2
14887 static const int ShufMask[] = { 0, 4, 2, 6 };
14888 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
14891 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
14892 "Only know how to lower V2I64/V4I64/V8I64 multiply");
14894 // Ahi = psrlqi(a, 32);
14895 // Bhi = psrlqi(b, 32);
14897 // AloBlo = pmuludq(a, b);
14898 // AloBhi = pmuludq(a, Bhi);
14899 // AhiBlo = pmuludq(Ahi, b);
14901 // AloBhi = psllqi(AloBhi, 32);
14902 // AhiBlo = psllqi(AhiBlo, 32);
14903 // return AloBlo + AloBhi + AhiBlo;
14905 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
14906 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
14908 // Bit cast to 32-bit vectors for MULUDQ
14909 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
14910 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
14911 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
14912 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
14913 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
14914 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
14916 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
14917 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
14918 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
14920 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
14921 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
14923 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
14924 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
14927 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
14928 assert(Subtarget->isTargetWin64() && "Unexpected target");
14929 EVT VT = Op.getValueType();
14930 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
14931 "Unexpected return type for lowering");
14935 switch (Op->getOpcode()) {
14936 default: llvm_unreachable("Unexpected request for libcall!");
14937 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
14938 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
14939 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
14940 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
14941 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
14942 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
14946 SDValue InChain = DAG.getEntryNode();
14948 TargetLowering::ArgListTy Args;
14949 TargetLowering::ArgListEntry Entry;
14950 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
14951 EVT ArgVT = Op->getOperand(i).getValueType();
14952 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
14953 "Unexpected argument type for lowering");
14954 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
14955 Entry.Node = StackPtr;
14956 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
14958 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14959 Entry.Ty = PointerType::get(ArgTy,0);
14960 Entry.isSExt = false;
14961 Entry.isZExt = false;
14962 Args.push_back(Entry);
14965 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14968 TargetLowering::CallLoweringInfo CLI(DAG);
14969 CLI.setDebugLoc(dl).setChain(InChain)
14970 .setCallee(getLibcallCallingConv(LC),
14971 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
14973 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14975 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14976 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
14979 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
14980 SelectionDAG &DAG) {
14981 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
14982 EVT VT = Op0.getValueType();
14985 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
14986 (VT == MVT::v8i32 && Subtarget->hasInt256()));
14988 // Get the high parts.
14989 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
14990 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
14991 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
14993 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
14995 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
14996 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
14998 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
14999 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15000 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15001 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15002 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15004 // Shuffle it back into the right order.
15005 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15006 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15007 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15008 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15010 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15011 // unsigned multiply.
15012 if (IsSigned && !Subtarget->hasSSE41()) {
15014 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15015 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15016 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15017 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15018 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15020 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15021 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15024 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15027 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15028 const X86Subtarget *Subtarget) {
15029 MVT VT = Op.getSimpleValueType();
15031 SDValue R = Op.getOperand(0);
15032 SDValue Amt = Op.getOperand(1);
15034 // Optimize shl/srl/sra with constant shift amount.
15035 if (isSplatVector(Amt.getNode())) {
15036 SDValue SclrAmt = Amt->getOperand(0);
15037 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15038 uint64_t ShiftAmt = C->getZExtValue();
15040 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15041 (Subtarget->hasInt256() &&
15042 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15043 (Subtarget->hasAVX512() &&
15044 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15045 if (Op.getOpcode() == ISD::SHL)
15046 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15048 if (Op.getOpcode() == ISD::SRL)
15049 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15051 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15052 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15056 if (VT == MVT::v16i8) {
15057 if (Op.getOpcode() == ISD::SHL) {
15058 // Make a large shift.
15059 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15060 MVT::v8i16, R, ShiftAmt,
15062 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15063 // Zero out the rightmost bits.
15064 SmallVector<SDValue, 16> V(16,
15065 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15067 return DAG.getNode(ISD::AND, dl, VT, SHL,
15068 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15070 if (Op.getOpcode() == ISD::SRL) {
15071 // Make a large shift.
15072 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15073 MVT::v8i16, R, ShiftAmt,
15075 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15076 // Zero out the leftmost bits.
15077 SmallVector<SDValue, 16> V(16,
15078 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15080 return DAG.getNode(ISD::AND, dl, VT, SRL,
15081 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15083 if (Op.getOpcode() == ISD::SRA) {
15084 if (ShiftAmt == 7) {
15085 // R s>> 7 === R s< 0
15086 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15087 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15090 // R s>> a === ((R u>> a) ^ m) - m
15091 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15092 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15094 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15095 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15096 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15099 llvm_unreachable("Unknown shift opcode.");
15102 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15103 if (Op.getOpcode() == ISD::SHL) {
15104 // Make a large shift.
15105 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15106 MVT::v16i16, R, ShiftAmt,
15108 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15109 // Zero out the rightmost bits.
15110 SmallVector<SDValue, 32> V(32,
15111 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15113 return DAG.getNode(ISD::AND, dl, VT, SHL,
15114 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15116 if (Op.getOpcode() == ISD::SRL) {
15117 // Make a large shift.
15118 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15119 MVT::v16i16, R, ShiftAmt,
15121 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15122 // Zero out the leftmost bits.
15123 SmallVector<SDValue, 32> V(32,
15124 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15126 return DAG.getNode(ISD::AND, dl, VT, SRL,
15127 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15129 if (Op.getOpcode() == ISD::SRA) {
15130 if (ShiftAmt == 7) {
15131 // R s>> 7 === R s< 0
15132 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15133 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15136 // R s>> a === ((R u>> a) ^ m) - m
15137 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15138 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15140 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15141 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15142 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15145 llvm_unreachable("Unknown shift opcode.");
15150 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15151 if (!Subtarget->is64Bit() &&
15152 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15153 Amt.getOpcode() == ISD::BITCAST &&
15154 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15155 Amt = Amt.getOperand(0);
15156 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15157 VT.getVectorNumElements();
15158 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15159 uint64_t ShiftAmt = 0;
15160 for (unsigned i = 0; i != Ratio; ++i) {
15161 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15165 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15167 // Check remaining shift amounts.
15168 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15169 uint64_t ShAmt = 0;
15170 for (unsigned j = 0; j != Ratio; ++j) {
15171 ConstantSDNode *C =
15172 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15176 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15178 if (ShAmt != ShiftAmt)
15181 switch (Op.getOpcode()) {
15183 llvm_unreachable("Unknown shift opcode!");
15185 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15188 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15191 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15199 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15200 const X86Subtarget* Subtarget) {
15201 MVT VT = Op.getSimpleValueType();
15203 SDValue R = Op.getOperand(0);
15204 SDValue Amt = Op.getOperand(1);
15206 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15207 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15208 (Subtarget->hasInt256() &&
15209 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15210 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15211 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15213 EVT EltVT = VT.getVectorElementType();
15215 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15216 unsigned NumElts = VT.getVectorNumElements();
15218 for (i = 0; i != NumElts; ++i) {
15219 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15223 for (j = i; j != NumElts; ++j) {
15224 SDValue Arg = Amt.getOperand(j);
15225 if (Arg.getOpcode() == ISD::UNDEF) continue;
15226 if (Arg != Amt.getOperand(i))
15229 if (i != NumElts && j == NumElts)
15230 BaseShAmt = Amt.getOperand(i);
15232 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15233 Amt = Amt.getOperand(0);
15234 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15235 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15236 SDValue InVec = Amt.getOperand(0);
15237 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15238 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15240 for (; i != NumElts; ++i) {
15241 SDValue Arg = InVec.getOperand(i);
15242 if (Arg.getOpcode() == ISD::UNDEF) continue;
15246 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15247 if (ConstantSDNode *C =
15248 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15249 unsigned SplatIdx =
15250 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15251 if (C->getZExtValue() == SplatIdx)
15252 BaseShAmt = InVec.getOperand(1);
15255 if (!BaseShAmt.getNode())
15256 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15257 DAG.getIntPtrConstant(0));
15261 if (BaseShAmt.getNode()) {
15262 if (EltVT.bitsGT(MVT::i32))
15263 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15264 else if (EltVT.bitsLT(MVT::i32))
15265 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15267 switch (Op.getOpcode()) {
15269 llvm_unreachable("Unknown shift opcode!");
15271 switch (VT.SimpleTy) {
15272 default: return SDValue();
15281 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15284 switch (VT.SimpleTy) {
15285 default: return SDValue();
15292 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15295 switch (VT.SimpleTy) {
15296 default: return SDValue();
15305 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15311 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15312 if (!Subtarget->is64Bit() &&
15313 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15314 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15315 Amt.getOpcode() == ISD::BITCAST &&
15316 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15317 Amt = Amt.getOperand(0);
15318 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15319 VT.getVectorNumElements();
15320 std::vector<SDValue> Vals(Ratio);
15321 for (unsigned i = 0; i != Ratio; ++i)
15322 Vals[i] = Amt.getOperand(i);
15323 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15324 for (unsigned j = 0; j != Ratio; ++j)
15325 if (Vals[j] != Amt.getOperand(i + j))
15328 switch (Op.getOpcode()) {
15330 llvm_unreachable("Unknown shift opcode!");
15332 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15334 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15336 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15343 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15344 SelectionDAG &DAG) {
15346 MVT VT = Op.getSimpleValueType();
15348 SDValue R = Op.getOperand(0);
15349 SDValue Amt = Op.getOperand(1);
15352 if (!Subtarget->hasSSE2())
15355 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15359 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15363 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15365 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15366 if (Subtarget->hasInt256()) {
15367 if (Op.getOpcode() == ISD::SRL &&
15368 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15369 VT == MVT::v4i64 || VT == MVT::v8i32))
15371 if (Op.getOpcode() == ISD::SHL &&
15372 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15373 VT == MVT::v4i64 || VT == MVT::v8i32))
15375 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15379 // If possible, lower this packed shift into a vector multiply instead of
15380 // expanding it into a sequence of scalar shifts.
15381 // Do this only if the vector shift count is a constant build_vector.
15382 if (Op.getOpcode() == ISD::SHL &&
15383 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15384 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15385 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15386 SmallVector<SDValue, 8> Elts;
15387 EVT SVT = VT.getScalarType();
15388 unsigned SVTBits = SVT.getSizeInBits();
15389 const APInt &One = APInt(SVTBits, 1);
15390 unsigned NumElems = VT.getVectorNumElements();
15392 for (unsigned i=0; i !=NumElems; ++i) {
15393 SDValue Op = Amt->getOperand(i);
15394 if (Op->getOpcode() == ISD::UNDEF) {
15395 Elts.push_back(Op);
15399 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15400 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15401 uint64_t ShAmt = C.getZExtValue();
15402 if (ShAmt >= SVTBits) {
15403 Elts.push_back(DAG.getUNDEF(SVT));
15406 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15408 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15409 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15412 // Lower SHL with variable shift amount.
15413 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15414 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15416 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15417 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15418 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15419 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15422 // If possible, lower this shift as a sequence of two shifts by
15423 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15425 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15427 // Could be rewritten as:
15428 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15430 // The advantage is that the two shifts from the example would be
15431 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15432 // the vector shift into four scalar shifts plus four pairs of vector
15434 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15435 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15436 unsigned TargetOpcode = X86ISD::MOVSS;
15437 bool CanBeSimplified;
15438 // The splat value for the first packed shift (the 'X' from the example).
15439 SDValue Amt1 = Amt->getOperand(0);
15440 // The splat value for the second packed shift (the 'Y' from the example).
15441 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15442 Amt->getOperand(2);
15444 // See if it is possible to replace this node with a sequence of
15445 // two shifts followed by a MOVSS/MOVSD
15446 if (VT == MVT::v4i32) {
15447 // Check if it is legal to use a MOVSS.
15448 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15449 Amt2 == Amt->getOperand(3);
15450 if (!CanBeSimplified) {
15451 // Otherwise, check if we can still simplify this node using a MOVSD.
15452 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15453 Amt->getOperand(2) == Amt->getOperand(3);
15454 TargetOpcode = X86ISD::MOVSD;
15455 Amt2 = Amt->getOperand(2);
15458 // Do similar checks for the case where the machine value type
15460 CanBeSimplified = Amt1 == Amt->getOperand(1);
15461 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15462 CanBeSimplified = Amt2 == Amt->getOperand(i);
15464 if (!CanBeSimplified) {
15465 TargetOpcode = X86ISD::MOVSD;
15466 CanBeSimplified = true;
15467 Amt2 = Amt->getOperand(4);
15468 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15469 CanBeSimplified = Amt1 == Amt->getOperand(i);
15470 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15471 CanBeSimplified = Amt2 == Amt->getOperand(j);
15475 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15476 isa<ConstantSDNode>(Amt2)) {
15477 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15478 EVT CastVT = MVT::v4i32;
15480 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15481 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15483 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15484 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15485 if (TargetOpcode == X86ISD::MOVSD)
15486 CastVT = MVT::v2i64;
15487 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15488 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15489 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15491 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15495 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15496 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15499 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15500 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15502 // Turn 'a' into a mask suitable for VSELECT
15503 SDValue VSelM = DAG.getConstant(0x80, VT);
15504 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15505 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15507 SDValue CM1 = DAG.getConstant(0x0f, VT);
15508 SDValue CM2 = DAG.getConstant(0x3f, VT);
15510 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15511 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15512 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15513 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15514 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15517 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15518 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15519 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15521 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15522 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15523 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15524 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15525 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15528 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15529 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15530 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15532 // return VSELECT(r, r+r, a);
15533 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15534 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15538 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15539 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15540 // solution better.
15541 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15542 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15544 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15545 R = DAG.getNode(ExtOpc, dl, NewVT, R);
15546 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15547 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15548 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15551 // Decompose 256-bit shifts into smaller 128-bit shifts.
15552 if (VT.is256BitVector()) {
15553 unsigned NumElems = VT.getVectorNumElements();
15554 MVT EltVT = VT.getVectorElementType();
15555 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15557 // Extract the two vectors
15558 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15559 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15561 // Recreate the shift amount vectors
15562 SDValue Amt1, Amt2;
15563 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15564 // Constant shift amount
15565 SmallVector<SDValue, 4> Amt1Csts;
15566 SmallVector<SDValue, 4> Amt2Csts;
15567 for (unsigned i = 0; i != NumElems/2; ++i)
15568 Amt1Csts.push_back(Amt->getOperand(i));
15569 for (unsigned i = NumElems/2; i != NumElems; ++i)
15570 Amt2Csts.push_back(Amt->getOperand(i));
15572 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15573 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15575 // Variable shift amount
15576 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15577 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15580 // Issue new vector shifts for the smaller types
15581 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15582 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15584 // Concatenate the result back
15585 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15591 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15592 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15593 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15594 // looks for this combo and may remove the "setcc" instruction if the "setcc"
15595 // has only one use.
15596 SDNode *N = Op.getNode();
15597 SDValue LHS = N->getOperand(0);
15598 SDValue RHS = N->getOperand(1);
15599 unsigned BaseOp = 0;
15602 switch (Op.getOpcode()) {
15603 default: llvm_unreachable("Unknown ovf instruction!");
15605 // A subtract of one will be selected as a INC. Note that INC doesn't
15606 // set CF, so we can't do this for UADDO.
15607 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15609 BaseOp = X86ISD::INC;
15610 Cond = X86::COND_O;
15613 BaseOp = X86ISD::ADD;
15614 Cond = X86::COND_O;
15617 BaseOp = X86ISD::ADD;
15618 Cond = X86::COND_B;
15621 // A subtract of one will be selected as a DEC. Note that DEC doesn't
15622 // set CF, so we can't do this for USUBO.
15623 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15625 BaseOp = X86ISD::DEC;
15626 Cond = X86::COND_O;
15629 BaseOp = X86ISD::SUB;
15630 Cond = X86::COND_O;
15633 BaseOp = X86ISD::SUB;
15634 Cond = X86::COND_B;
15637 BaseOp = X86ISD::SMUL;
15638 Cond = X86::COND_O;
15640 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15641 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15643 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15646 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15647 DAG.getConstant(X86::COND_O, MVT::i32),
15648 SDValue(Sum.getNode(), 2));
15650 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15654 // Also sets EFLAGS.
15655 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15656 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15659 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15660 DAG.getConstant(Cond, MVT::i32),
15661 SDValue(Sum.getNode(), 1));
15663 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15666 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15667 SelectionDAG &DAG) const {
15669 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15670 MVT VT = Op.getSimpleValueType();
15672 if (!Subtarget->hasSSE2() || !VT.isVector())
15675 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15676 ExtraVT.getScalarType().getSizeInBits();
15678 switch (VT.SimpleTy) {
15679 default: return SDValue();
15682 if (!Subtarget->hasFp256())
15684 if (!Subtarget->hasInt256()) {
15685 // needs to be split
15686 unsigned NumElems = VT.getVectorNumElements();
15688 // Extract the LHS vectors
15689 SDValue LHS = Op.getOperand(0);
15690 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15691 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15693 MVT EltVT = VT.getVectorElementType();
15694 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15696 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15697 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15698 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15700 SDValue Extra = DAG.getValueType(ExtraVT);
15702 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15703 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15705 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15710 SDValue Op0 = Op.getOperand(0);
15711 SDValue Op00 = Op0.getOperand(0);
15713 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15714 if (Op0.getOpcode() == ISD::BITCAST &&
15715 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15716 // (sext (vzext x)) -> (vsext x)
15717 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15718 if (Tmp1.getNode()) {
15719 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15720 // This folding is only valid when the in-reg type is a vector of i8,
15722 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15723 ExtraEltVT == MVT::i32) {
15724 SDValue Tmp1Op0 = Tmp1.getOperand(0);
15725 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15726 "This optimization is invalid without a VZEXT.");
15727 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15733 // If the above didn't work, then just use Shift-Left + Shift-Right.
15734 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15736 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15742 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15743 SelectionDAG &DAG) {
15745 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15746 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15747 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15748 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15750 // The only fence that needs an instruction is a sequentially-consistent
15751 // cross-thread fence.
15752 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15753 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15754 // no-sse2). There isn't any reason to disable it if the target processor
15756 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15757 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15759 SDValue Chain = Op.getOperand(0);
15760 SDValue Zero = DAG.getConstant(0, MVT::i32);
15762 DAG.getRegister(X86::ESP, MVT::i32), // Base
15763 DAG.getTargetConstant(1, MVT::i8), // Scale
15764 DAG.getRegister(0, MVT::i32), // Index
15765 DAG.getTargetConstant(0, MVT::i32), // Disp
15766 DAG.getRegister(0, MVT::i32), // Segment.
15770 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15771 return SDValue(Res, 0);
15774 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15775 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15778 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15779 SelectionDAG &DAG) {
15780 MVT T = Op.getSimpleValueType();
15784 switch(T.SimpleTy) {
15785 default: llvm_unreachable("Invalid value type!");
15786 case MVT::i8: Reg = X86::AL; size = 1; break;
15787 case MVT::i16: Reg = X86::AX; size = 2; break;
15788 case MVT::i32: Reg = X86::EAX; size = 4; break;
15790 assert(Subtarget->is64Bit() && "Node not type legal!");
15791 Reg = X86::RAX; size = 8;
15794 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15795 Op.getOperand(2), SDValue());
15796 SDValue Ops[] = { cpIn.getValue(0),
15799 DAG.getTargetConstant(size, MVT::i8),
15800 cpIn.getValue(1) };
15801 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15802 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15803 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15807 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15808 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15809 MVT::i32, cpOut.getValue(2));
15810 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15811 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15813 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15814 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15815 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15819 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15820 SelectionDAG &DAG) {
15821 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15822 MVT DstVT = Op.getSimpleValueType();
15824 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15825 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15826 if (DstVT != MVT::f64)
15827 // This conversion needs to be expanded.
15830 SDValue InVec = Op->getOperand(0);
15832 unsigned NumElts = SrcVT.getVectorNumElements();
15833 EVT SVT = SrcVT.getVectorElementType();
15835 // Widen the vector in input in the case of MVT::v2i32.
15836 // Example: from MVT::v2i32 to MVT::v4i32.
15837 SmallVector<SDValue, 16> Elts;
15838 for (unsigned i = 0, e = NumElts; i != e; ++i)
15839 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15840 DAG.getIntPtrConstant(i)));
15842 // Explicitly mark the extra elements as Undef.
15843 SDValue Undef = DAG.getUNDEF(SVT);
15844 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15845 Elts.push_back(Undef);
15847 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15848 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15849 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15850 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15851 DAG.getIntPtrConstant(0));
15854 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15855 Subtarget->hasMMX() && "Unexpected custom BITCAST");
15856 assert((DstVT == MVT::i64 ||
15857 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
15858 "Unexpected custom BITCAST");
15859 // i64 <=> MMX conversions are Legal.
15860 if (SrcVT==MVT::i64 && DstVT.isVector())
15862 if (DstVT==MVT::i64 && SrcVT.isVector())
15864 // MMX <=> MMX conversions are Legal.
15865 if (SrcVT.isVector() && DstVT.isVector())
15867 // All other conversions need to be expanded.
15871 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
15872 SDNode *Node = Op.getNode();
15874 EVT T = Node->getValueType(0);
15875 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
15876 DAG.getConstant(0, T), Node->getOperand(2));
15877 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
15878 cast<AtomicSDNode>(Node)->getMemoryVT(),
15879 Node->getOperand(0),
15880 Node->getOperand(1), negOp,
15881 cast<AtomicSDNode>(Node)->getMemOperand(),
15882 cast<AtomicSDNode>(Node)->getOrdering(),
15883 cast<AtomicSDNode>(Node)->getSynchScope());
15886 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
15887 SDNode *Node = Op.getNode();
15889 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
15891 // Convert seq_cst store -> xchg
15892 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
15893 // FIXME: On 32-bit, store -> fist or movq would be more efficient
15894 // (The only way to get a 16-byte store is cmpxchg16b)
15895 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
15896 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
15897 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15898 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
15899 cast<AtomicSDNode>(Node)->getMemoryVT(),
15900 Node->getOperand(0),
15901 Node->getOperand(1), Node->getOperand(2),
15902 cast<AtomicSDNode>(Node)->getMemOperand(),
15903 cast<AtomicSDNode>(Node)->getOrdering(),
15904 cast<AtomicSDNode>(Node)->getSynchScope());
15905 return Swap.getValue(1);
15907 // Other atomic stores have a simple pattern.
15911 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
15912 EVT VT = Op.getNode()->getSimpleValueType(0);
15914 // Let legalize expand this if it isn't a legal type yet.
15915 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15918 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15921 bool ExtraOp = false;
15922 switch (Op.getOpcode()) {
15923 default: llvm_unreachable("Invalid code");
15924 case ISD::ADDC: Opc = X86ISD::ADD; break;
15925 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
15926 case ISD::SUBC: Opc = X86ISD::SUB; break;
15927 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
15931 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
15933 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
15934 Op.getOperand(1), Op.getOperand(2));
15937 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
15938 SelectionDAG &DAG) {
15939 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
15941 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
15942 // which returns the values as { float, float } (in XMM0) or
15943 // { double, double } (which is returned in XMM0, XMM1).
15945 SDValue Arg = Op.getOperand(0);
15946 EVT ArgVT = Arg.getValueType();
15947 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15949 TargetLowering::ArgListTy Args;
15950 TargetLowering::ArgListEntry Entry;
15954 Entry.isSExt = false;
15955 Entry.isZExt = false;
15956 Args.push_back(Entry);
15958 bool isF64 = ArgVT == MVT::f64;
15959 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
15960 // the small struct {f32, f32} is returned in (eax, edx). For f64,
15961 // the results are returned via SRet in memory.
15962 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
15963 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15964 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
15966 Type *RetTy = isF64
15967 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
15968 : (Type*)VectorType::get(ArgTy, 4);
15970 TargetLowering::CallLoweringInfo CLI(DAG);
15971 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
15972 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
15974 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
15977 // Returned in xmm0 and xmm1.
15978 return CallResult.first;
15980 // Returned in bits 0:31 and 32:64 xmm0.
15981 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
15982 CallResult.first, DAG.getIntPtrConstant(0));
15983 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
15984 CallResult.first, DAG.getIntPtrConstant(1));
15985 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
15986 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
15989 /// LowerOperation - Provide custom lowering hooks for some operations.
15991 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
15992 switch (Op.getOpcode()) {
15993 default: llvm_unreachable("Should not custom lower this!");
15994 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
15995 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
15996 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
15997 return LowerCMP_SWAP(Op, Subtarget, DAG);
15998 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
15999 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16000 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16001 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16002 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16003 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16004 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16005 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16006 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16007 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16008 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16009 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16010 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16011 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16012 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16013 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16014 case ISD::SHL_PARTS:
16015 case ISD::SRA_PARTS:
16016 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16017 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16018 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16019 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16020 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16021 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16022 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16023 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16024 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16025 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16026 case ISD::FABS: return LowerFABS(Op, DAG);
16027 case ISD::FNEG: return LowerFNEG(Op, DAG);
16028 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16029 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16030 case ISD::SETCC: return LowerSETCC(Op, DAG);
16031 case ISD::SELECT: return LowerSELECT(Op, DAG);
16032 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16033 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16034 case ISD::VASTART: return LowerVASTART(Op, DAG);
16035 case ISD::VAARG: return LowerVAARG(Op, DAG);
16036 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16037 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16038 case ISD::INTRINSIC_VOID:
16039 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16040 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16041 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16042 case ISD::FRAME_TO_ARGS_OFFSET:
16043 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16044 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16045 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16046 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16047 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16048 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16049 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16050 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16051 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16052 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16053 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16054 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16055 case ISD::UMUL_LOHI:
16056 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16059 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16065 case ISD::UMULO: return LowerXALUO(Op, DAG);
16066 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16067 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16071 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16072 case ISD::ADD: return LowerADD(Op, DAG);
16073 case ISD::SUB: return LowerSUB(Op, DAG);
16074 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16078 static void ReplaceATOMIC_LOAD(SDNode *Node,
16079 SmallVectorImpl<SDValue> &Results,
16080 SelectionDAG &DAG) {
16082 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16084 // Convert wide load -> cmpxchg8b/cmpxchg16b
16085 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16086 // (The only way to get a 16-byte load is cmpxchg16b)
16087 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16088 SDValue Zero = DAG.getConstant(0, VT);
16089 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16091 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16092 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16093 cast<AtomicSDNode>(Node)->getMemOperand(),
16094 cast<AtomicSDNode>(Node)->getOrdering(),
16095 cast<AtomicSDNode>(Node)->getOrdering(),
16096 cast<AtomicSDNode>(Node)->getSynchScope());
16097 Results.push_back(Swap.getValue(0));
16098 Results.push_back(Swap.getValue(2));
16102 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
16103 SelectionDAG &DAG, unsigned NewOp) {
16105 assert (Node->getValueType(0) == MVT::i64 &&
16106 "Only know how to expand i64 atomics");
16108 SDValue Chain = Node->getOperand(0);
16109 SDValue In1 = Node->getOperand(1);
16110 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16111 Node->getOperand(2), DAG.getIntPtrConstant(0));
16112 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16113 Node->getOperand(2), DAG.getIntPtrConstant(1));
16114 SDValue Ops[] = { Chain, In1, In2L, In2H };
16115 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
16117 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
16118 cast<MemSDNode>(Node)->getMemOperand());
16119 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
16120 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
16121 Results.push_back(Result.getValue(2));
16124 /// ReplaceNodeResults - Replace a node with an illegal result type
16125 /// with a new node built out of custom code.
16126 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16127 SmallVectorImpl<SDValue>&Results,
16128 SelectionDAG &DAG) const {
16130 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16131 switch (N->getOpcode()) {
16133 llvm_unreachable("Do not know how to custom type legalize this operation!");
16134 case ISD::SIGN_EXTEND_INREG:
16139 // We don't want to expand or promote these.
16146 case ISD::UDIVREM: {
16147 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16148 Results.push_back(V);
16151 case ISD::FP_TO_SINT:
16152 case ISD::FP_TO_UINT: {
16153 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16155 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16158 std::pair<SDValue,SDValue> Vals =
16159 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16160 SDValue FIST = Vals.first, StackSlot = Vals.second;
16161 if (FIST.getNode()) {
16162 EVT VT = N->getValueType(0);
16163 // Return a load from the stack slot.
16164 if (StackSlot.getNode())
16165 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16166 MachinePointerInfo(),
16167 false, false, false, 0));
16169 Results.push_back(FIST);
16173 case ISD::UINT_TO_FP: {
16174 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16175 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16176 N->getValueType(0) != MVT::v2f32)
16178 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16180 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16182 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16183 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16184 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16185 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16186 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16187 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16190 case ISD::FP_ROUND: {
16191 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16193 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16194 Results.push_back(V);
16197 case ISD::INTRINSIC_W_CHAIN: {
16198 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16200 default : llvm_unreachable("Do not know how to custom type "
16201 "legalize this intrinsic operation!");
16202 case Intrinsic::x86_rdtsc:
16203 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16205 case Intrinsic::x86_rdtscp:
16206 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16210 case ISD::READCYCLECOUNTER: {
16211 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16214 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16215 EVT T = N->getValueType(0);
16216 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16217 bool Regs64bit = T == MVT::i128;
16218 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16219 SDValue cpInL, cpInH;
16220 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16221 DAG.getConstant(0, HalfT));
16222 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16223 DAG.getConstant(1, HalfT));
16224 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16225 Regs64bit ? X86::RAX : X86::EAX,
16227 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16228 Regs64bit ? X86::RDX : X86::EDX,
16229 cpInH, cpInL.getValue(1));
16230 SDValue swapInL, swapInH;
16231 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16232 DAG.getConstant(0, HalfT));
16233 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16234 DAG.getConstant(1, HalfT));
16235 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16236 Regs64bit ? X86::RBX : X86::EBX,
16237 swapInL, cpInH.getValue(1));
16238 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16239 Regs64bit ? X86::RCX : X86::ECX,
16240 swapInH, swapInL.getValue(1));
16241 SDValue Ops[] = { swapInH.getValue(0),
16243 swapInH.getValue(1) };
16244 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16245 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16246 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16247 X86ISD::LCMPXCHG8_DAG;
16248 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16249 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16250 Regs64bit ? X86::RAX : X86::EAX,
16251 HalfT, Result.getValue(1));
16252 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16253 Regs64bit ? X86::RDX : X86::EDX,
16254 HalfT, cpOutL.getValue(2));
16255 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16257 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16258 MVT::i32, cpOutH.getValue(2));
16260 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16261 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16262 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16264 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16265 Results.push_back(Success);
16266 Results.push_back(EFLAGS.getValue(1));
16269 case ISD::ATOMIC_LOAD_ADD:
16270 case ISD::ATOMIC_LOAD_AND:
16271 case ISD::ATOMIC_LOAD_NAND:
16272 case ISD::ATOMIC_LOAD_OR:
16273 case ISD::ATOMIC_LOAD_SUB:
16274 case ISD::ATOMIC_LOAD_XOR:
16275 case ISD::ATOMIC_LOAD_MAX:
16276 case ISD::ATOMIC_LOAD_MIN:
16277 case ISD::ATOMIC_LOAD_UMAX:
16278 case ISD::ATOMIC_LOAD_UMIN:
16279 case ISD::ATOMIC_SWAP: {
16281 switch (N->getOpcode()) {
16282 default: llvm_unreachable("Unexpected opcode");
16283 case ISD::ATOMIC_LOAD_ADD:
16284 Opc = X86ISD::ATOMADD64_DAG;
16286 case ISD::ATOMIC_LOAD_AND:
16287 Opc = X86ISD::ATOMAND64_DAG;
16289 case ISD::ATOMIC_LOAD_NAND:
16290 Opc = X86ISD::ATOMNAND64_DAG;
16292 case ISD::ATOMIC_LOAD_OR:
16293 Opc = X86ISD::ATOMOR64_DAG;
16295 case ISD::ATOMIC_LOAD_SUB:
16296 Opc = X86ISD::ATOMSUB64_DAG;
16298 case ISD::ATOMIC_LOAD_XOR:
16299 Opc = X86ISD::ATOMXOR64_DAG;
16301 case ISD::ATOMIC_LOAD_MAX:
16302 Opc = X86ISD::ATOMMAX64_DAG;
16304 case ISD::ATOMIC_LOAD_MIN:
16305 Opc = X86ISD::ATOMMIN64_DAG;
16307 case ISD::ATOMIC_LOAD_UMAX:
16308 Opc = X86ISD::ATOMUMAX64_DAG;
16310 case ISD::ATOMIC_LOAD_UMIN:
16311 Opc = X86ISD::ATOMUMIN64_DAG;
16313 case ISD::ATOMIC_SWAP:
16314 Opc = X86ISD::ATOMSWAP64_DAG;
16317 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
16320 case ISD::ATOMIC_LOAD: {
16321 ReplaceATOMIC_LOAD(N, Results, DAG);
16324 case ISD::BITCAST: {
16325 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16326 EVT DstVT = N->getValueType(0);
16327 EVT SrcVT = N->getOperand(0)->getValueType(0);
16329 if (SrcVT != MVT::f64 ||
16330 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16333 unsigned NumElts = DstVT.getVectorNumElements();
16334 EVT SVT = DstVT.getVectorElementType();
16335 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16336 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16337 MVT::v2f64, N->getOperand(0));
16338 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16340 SmallVector<SDValue, 8> Elts;
16341 for (unsigned i = 0, e = NumElts; i != e; ++i)
16342 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16343 ToVecInt, DAG.getIntPtrConstant(i)));
16345 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16350 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16352 default: return nullptr;
16353 case X86ISD::BSF: return "X86ISD::BSF";
16354 case X86ISD::BSR: return "X86ISD::BSR";
16355 case X86ISD::SHLD: return "X86ISD::SHLD";
16356 case X86ISD::SHRD: return "X86ISD::SHRD";
16357 case X86ISD::FAND: return "X86ISD::FAND";
16358 case X86ISD::FANDN: return "X86ISD::FANDN";
16359 case X86ISD::FOR: return "X86ISD::FOR";
16360 case X86ISD::FXOR: return "X86ISD::FXOR";
16361 case X86ISD::FSRL: return "X86ISD::FSRL";
16362 case X86ISD::FILD: return "X86ISD::FILD";
16363 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16364 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16365 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16366 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16367 case X86ISD::FLD: return "X86ISD::FLD";
16368 case X86ISD::FST: return "X86ISD::FST";
16369 case X86ISD::CALL: return "X86ISD::CALL";
16370 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16371 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16372 case X86ISD::BT: return "X86ISD::BT";
16373 case X86ISD::CMP: return "X86ISD::CMP";
16374 case X86ISD::COMI: return "X86ISD::COMI";
16375 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16376 case X86ISD::CMPM: return "X86ISD::CMPM";
16377 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16378 case X86ISD::SETCC: return "X86ISD::SETCC";
16379 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16380 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16381 case X86ISD::CMOV: return "X86ISD::CMOV";
16382 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16383 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16384 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16385 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16386 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16387 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16388 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16389 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16390 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16391 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16392 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16393 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16394 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16395 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16396 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16397 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16398 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16399 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16400 case X86ISD::HADD: return "X86ISD::HADD";
16401 case X86ISD::HSUB: return "X86ISD::HSUB";
16402 case X86ISD::FHADD: return "X86ISD::FHADD";
16403 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16404 case X86ISD::UMAX: return "X86ISD::UMAX";
16405 case X86ISD::UMIN: return "X86ISD::UMIN";
16406 case X86ISD::SMAX: return "X86ISD::SMAX";
16407 case X86ISD::SMIN: return "X86ISD::SMIN";
16408 case X86ISD::FMAX: return "X86ISD::FMAX";
16409 case X86ISD::FMIN: return "X86ISD::FMIN";
16410 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16411 case X86ISD::FMINC: return "X86ISD::FMINC";
16412 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16413 case X86ISD::FRCP: return "X86ISD::FRCP";
16414 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16415 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16416 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16417 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16418 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16419 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16420 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16421 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16422 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16423 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16424 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16425 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16426 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
16427 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
16428 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
16429 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
16430 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
16431 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
16432 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16433 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16434 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16435 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16436 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16437 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16438 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16439 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16440 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16441 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16442 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16443 case X86ISD::VSHL: return "X86ISD::VSHL";
16444 case X86ISD::VSRL: return "X86ISD::VSRL";
16445 case X86ISD::VSRA: return "X86ISD::VSRA";
16446 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16447 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16448 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16449 case X86ISD::CMPP: return "X86ISD::CMPP";
16450 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16451 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16452 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16453 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16454 case X86ISD::ADD: return "X86ISD::ADD";
16455 case X86ISD::SUB: return "X86ISD::SUB";
16456 case X86ISD::ADC: return "X86ISD::ADC";
16457 case X86ISD::SBB: return "X86ISD::SBB";
16458 case X86ISD::SMUL: return "X86ISD::SMUL";
16459 case X86ISD::UMUL: return "X86ISD::UMUL";
16460 case X86ISD::INC: return "X86ISD::INC";
16461 case X86ISD::DEC: return "X86ISD::DEC";
16462 case X86ISD::OR: return "X86ISD::OR";
16463 case X86ISD::XOR: return "X86ISD::XOR";
16464 case X86ISD::AND: return "X86ISD::AND";
16465 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16466 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16467 case X86ISD::PTEST: return "X86ISD::PTEST";
16468 case X86ISD::TESTP: return "X86ISD::TESTP";
16469 case X86ISD::TESTM: return "X86ISD::TESTM";
16470 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16471 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16472 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16473 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16474 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16475 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16476 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16477 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16478 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16479 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16480 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16481 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16482 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16483 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16484 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16485 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16486 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16487 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16488 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16489 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16490 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16491 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16492 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16493 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16494 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16495 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16496 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16497 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16498 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16499 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16500 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16501 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16502 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16503 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16504 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16505 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16506 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16507 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16508 case X86ISD::SAHF: return "X86ISD::SAHF";
16509 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16510 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16511 case X86ISD::FMADD: return "X86ISD::FMADD";
16512 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16513 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16514 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16515 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16516 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16517 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16518 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16519 case X86ISD::XTEST: return "X86ISD::XTEST";
16523 // isLegalAddressingMode - Return true if the addressing mode represented
16524 // by AM is legal for this target, for a load/store of the specified type.
16525 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16527 // X86 supports extremely general addressing modes.
16528 CodeModel::Model M = getTargetMachine().getCodeModel();
16529 Reloc::Model R = getTargetMachine().getRelocationModel();
16531 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16532 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16537 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16539 // If a reference to this global requires an extra load, we can't fold it.
16540 if (isGlobalStubReference(GVFlags))
16543 // If BaseGV requires a register for the PIC base, we cannot also have a
16544 // BaseReg specified.
16545 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16548 // If lower 4G is not available, then we must use rip-relative addressing.
16549 if ((M != CodeModel::Small || R != Reloc::Static) &&
16550 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16554 switch (AM.Scale) {
16560 // These scales always work.
16565 // These scales are formed with basereg+scalereg. Only accept if there is
16570 default: // Other stuff never works.
16577 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16578 unsigned Bits = Ty->getScalarSizeInBits();
16580 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16581 // particularly cheaper than those without.
16585 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16586 // variable shifts just as cheap as scalar ones.
16587 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16590 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16591 // fully general vector.
16595 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16596 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16598 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16599 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16600 return NumBits1 > NumBits2;
16603 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16604 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16607 if (!isTypeLegal(EVT::getEVT(Ty1)))
16610 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16612 // Assuming the caller doesn't have a zeroext or signext return parameter,
16613 // truncation all the way down to i1 is valid.
16617 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16618 return isInt<32>(Imm);
16621 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16622 // Can also use sub to handle negated immediates.
16623 return isInt<32>(Imm);
16626 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16627 if (!VT1.isInteger() || !VT2.isInteger())
16629 unsigned NumBits1 = VT1.getSizeInBits();
16630 unsigned NumBits2 = VT2.getSizeInBits();
16631 return NumBits1 > NumBits2;
16634 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16635 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16636 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16639 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16640 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16641 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16644 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16645 EVT VT1 = Val.getValueType();
16646 if (isZExtFree(VT1, VT2))
16649 if (Val.getOpcode() != ISD::LOAD)
16652 if (!VT1.isSimple() || !VT1.isInteger() ||
16653 !VT2.isSimple() || !VT2.isInteger())
16656 switch (VT1.getSimpleVT().SimpleTy) {
16661 // X86 has 8, 16, and 32-bit zero-extending loads.
16669 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16670 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16673 VT = VT.getScalarType();
16675 if (!VT.isSimple())
16678 switch (VT.getSimpleVT().SimpleTy) {
16689 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16690 // i16 instructions are longer (0x66 prefix) and potentially slower.
16691 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16694 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16695 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16696 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16697 /// are assumed to be legal.
16699 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16701 if (!VT.isSimple())
16704 MVT SVT = VT.getSimpleVT();
16706 // Very little shuffling can be done for 64-bit vectors right now.
16707 if (VT.getSizeInBits() == 64)
16710 // If this is a single-input shuffle with no 128 bit lane crossings we can
16711 // lower it into pshufb.
16712 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16713 (SVT.is256BitVector() && Subtarget->hasInt256())) {
16714 bool isLegal = true;
16715 for (unsigned I = 0, E = M.size(); I != E; ++I) {
16716 if (M[I] >= (int)SVT.getVectorNumElements() ||
16717 ShuffleCrosses128bitLane(SVT, I, M[I])) {
16726 // FIXME: blends, shifts.
16727 return (SVT.getVectorNumElements() == 2 ||
16728 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16729 isMOVLMask(M, SVT) ||
16730 isSHUFPMask(M, SVT) ||
16731 isPSHUFDMask(M, SVT) ||
16732 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16733 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16734 isPALIGNRMask(M, SVT, Subtarget) ||
16735 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16736 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16737 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16738 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16739 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16743 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16745 if (!VT.isSimple())
16748 MVT SVT = VT.getSimpleVT();
16749 unsigned NumElts = SVT.getVectorNumElements();
16750 // FIXME: This collection of masks seems suspect.
16753 if (NumElts == 4 && SVT.is128BitVector()) {
16754 return (isMOVLMask(Mask, SVT) ||
16755 isCommutedMOVLMask(Mask, SVT, true) ||
16756 isSHUFPMask(Mask, SVT) ||
16757 isSHUFPMask(Mask, SVT, /* Commuted */ true));
16762 //===----------------------------------------------------------------------===//
16763 // X86 Scheduler Hooks
16764 //===----------------------------------------------------------------------===//
16766 /// Utility function to emit xbegin specifying the start of an RTM region.
16767 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16768 const TargetInstrInfo *TII) {
16769 DebugLoc DL = MI->getDebugLoc();
16771 const BasicBlock *BB = MBB->getBasicBlock();
16772 MachineFunction::iterator I = MBB;
16775 // For the v = xbegin(), we generate
16786 MachineBasicBlock *thisMBB = MBB;
16787 MachineFunction *MF = MBB->getParent();
16788 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16789 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16790 MF->insert(I, mainMBB);
16791 MF->insert(I, sinkMBB);
16793 // Transfer the remainder of BB and its successor edges to sinkMBB.
16794 sinkMBB->splice(sinkMBB->begin(), MBB,
16795 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16796 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16800 // # fallthrough to mainMBB
16801 // # abortion to sinkMBB
16802 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16803 thisMBB->addSuccessor(mainMBB);
16804 thisMBB->addSuccessor(sinkMBB);
16808 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16809 mainMBB->addSuccessor(sinkMBB);
16812 // EAX is live into the sinkMBB
16813 sinkMBB->addLiveIn(X86::EAX);
16814 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16815 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16818 MI->eraseFromParent();
16822 // Get CMPXCHG opcode for the specified data type.
16823 static unsigned getCmpXChgOpcode(EVT VT) {
16824 switch (VT.getSimpleVT().SimpleTy) {
16825 case MVT::i8: return X86::LCMPXCHG8;
16826 case MVT::i16: return X86::LCMPXCHG16;
16827 case MVT::i32: return X86::LCMPXCHG32;
16828 case MVT::i64: return X86::LCMPXCHG64;
16832 llvm_unreachable("Invalid operand size!");
16835 // Get LOAD opcode for the specified data type.
16836 static unsigned getLoadOpcode(EVT VT) {
16837 switch (VT.getSimpleVT().SimpleTy) {
16838 case MVT::i8: return X86::MOV8rm;
16839 case MVT::i16: return X86::MOV16rm;
16840 case MVT::i32: return X86::MOV32rm;
16841 case MVT::i64: return X86::MOV64rm;
16845 llvm_unreachable("Invalid operand size!");
16848 // Get opcode of the non-atomic one from the specified atomic instruction.
16849 static unsigned getNonAtomicOpcode(unsigned Opc) {
16851 case X86::ATOMAND8: return X86::AND8rr;
16852 case X86::ATOMAND16: return X86::AND16rr;
16853 case X86::ATOMAND32: return X86::AND32rr;
16854 case X86::ATOMAND64: return X86::AND64rr;
16855 case X86::ATOMOR8: return X86::OR8rr;
16856 case X86::ATOMOR16: return X86::OR16rr;
16857 case X86::ATOMOR32: return X86::OR32rr;
16858 case X86::ATOMOR64: return X86::OR64rr;
16859 case X86::ATOMXOR8: return X86::XOR8rr;
16860 case X86::ATOMXOR16: return X86::XOR16rr;
16861 case X86::ATOMXOR32: return X86::XOR32rr;
16862 case X86::ATOMXOR64: return X86::XOR64rr;
16864 llvm_unreachable("Unhandled atomic-load-op opcode!");
16867 // Get opcode of the non-atomic one from the specified atomic instruction with
16869 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
16870 unsigned &ExtraOpc) {
16872 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
16873 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
16874 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
16875 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
16876 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
16877 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
16878 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
16879 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
16880 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
16881 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
16882 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
16883 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
16884 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
16885 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
16886 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
16887 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
16888 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
16889 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
16890 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
16891 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
16893 llvm_unreachable("Unhandled atomic-load-op opcode!");
16896 // Get opcode of the non-atomic one from the specified atomic instruction for
16897 // 64-bit data type on 32-bit target.
16898 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
16900 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
16901 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
16902 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
16903 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
16904 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
16905 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
16906 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
16907 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
16908 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
16909 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
16911 llvm_unreachable("Unhandled atomic-load-op opcode!");
16914 // Get opcode of the non-atomic one from the specified atomic instruction for
16915 // 64-bit data type on 32-bit target with extra opcode.
16916 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
16918 unsigned &ExtraOpc) {
16920 case X86::ATOMNAND6432:
16921 ExtraOpc = X86::NOT32r;
16922 HiOpc = X86::AND32rr;
16923 return X86::AND32rr;
16925 llvm_unreachable("Unhandled atomic-load-op opcode!");
16928 // Get pseudo CMOV opcode from the specified data type.
16929 static unsigned getPseudoCMOVOpc(EVT VT) {
16930 switch (VT.getSimpleVT().SimpleTy) {
16931 case MVT::i8: return X86::CMOV_GR8;
16932 case MVT::i16: return X86::CMOV_GR16;
16933 case MVT::i32: return X86::CMOV_GR32;
16937 llvm_unreachable("Unknown CMOV opcode!");
16940 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
16941 // They will be translated into a spin-loop or compare-exchange loop from
16944 // dst = atomic-fetch-op MI.addr, MI.val
16950 // t1 = LOAD MI.addr
16952 // t4 = phi(t1, t3 / loop)
16953 // t2 = OP MI.val, t4
16955 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
16961 MachineBasicBlock *
16962 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
16963 MachineBasicBlock *MBB) const {
16964 MachineFunction *MF = MBB->getParent();
16965 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16966 DebugLoc DL = MI->getDebugLoc();
16968 MachineRegisterInfo &MRI = MF->getRegInfo();
16970 const BasicBlock *BB = MBB->getBasicBlock();
16971 MachineFunction::iterator I = MBB;
16974 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
16975 "Unexpected number of operands");
16977 assert(MI->hasOneMemOperand() &&
16978 "Expected atomic-load-op to have one memoperand");
16980 // Memory Reference
16981 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16982 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16984 unsigned DstReg, SrcReg;
16985 unsigned MemOpndSlot;
16987 unsigned CurOp = 0;
16989 DstReg = MI->getOperand(CurOp++).getReg();
16990 MemOpndSlot = CurOp;
16991 CurOp += X86::AddrNumOperands;
16992 SrcReg = MI->getOperand(CurOp++).getReg();
16994 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16995 MVT::SimpleValueType VT = *RC->vt_begin();
16996 unsigned t1 = MRI.createVirtualRegister(RC);
16997 unsigned t2 = MRI.createVirtualRegister(RC);
16998 unsigned t3 = MRI.createVirtualRegister(RC);
16999 unsigned t4 = MRI.createVirtualRegister(RC);
17000 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
17002 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
17003 unsigned LOADOpc = getLoadOpcode(VT);
17005 // For the atomic load-arith operator, we generate
17008 // t1 = LOAD [MI.addr]
17010 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
17011 // t1 = OP MI.val, EAX
17013 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
17019 MachineBasicBlock *thisMBB = MBB;
17020 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17021 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17022 MF->insert(I, mainMBB);
17023 MF->insert(I, sinkMBB);
17025 MachineInstrBuilder MIB;
17027 // Transfer the remainder of BB and its successor edges to sinkMBB.
17028 sinkMBB->splice(sinkMBB->begin(), MBB,
17029 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17030 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17033 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
17034 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17035 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17037 NewMO.setIsKill(false);
17038 MIB.addOperand(NewMO);
17040 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17041 unsigned flags = (*MMOI)->getFlags();
17042 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17043 MachineMemOperand *MMO =
17044 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17045 (*MMOI)->getSize(),
17046 (*MMOI)->getBaseAlignment(),
17047 (*MMOI)->getTBAAInfo(),
17048 (*MMOI)->getRanges());
17049 MIB.addMemOperand(MMO);
17052 thisMBB->addSuccessor(mainMBB);
17055 MachineBasicBlock *origMainMBB = mainMBB;
17058 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
17059 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17061 unsigned Opc = MI->getOpcode();
17064 llvm_unreachable("Unhandled atomic-load-op opcode!");
17065 case X86::ATOMAND8:
17066 case X86::ATOMAND16:
17067 case X86::ATOMAND32:
17068 case X86::ATOMAND64:
17070 case X86::ATOMOR16:
17071 case X86::ATOMOR32:
17072 case X86::ATOMOR64:
17073 case X86::ATOMXOR8:
17074 case X86::ATOMXOR16:
17075 case X86::ATOMXOR32:
17076 case X86::ATOMXOR64: {
17077 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
17078 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
17082 case X86::ATOMNAND8:
17083 case X86::ATOMNAND16:
17084 case X86::ATOMNAND32:
17085 case X86::ATOMNAND64: {
17086 unsigned Tmp = MRI.createVirtualRegister(RC);
17088 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
17089 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
17091 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
17094 case X86::ATOMMAX8:
17095 case X86::ATOMMAX16:
17096 case X86::ATOMMAX32:
17097 case X86::ATOMMAX64:
17098 case X86::ATOMMIN8:
17099 case X86::ATOMMIN16:
17100 case X86::ATOMMIN32:
17101 case X86::ATOMMIN64:
17102 case X86::ATOMUMAX8:
17103 case X86::ATOMUMAX16:
17104 case X86::ATOMUMAX32:
17105 case X86::ATOMUMAX64:
17106 case X86::ATOMUMIN8:
17107 case X86::ATOMUMIN16:
17108 case X86::ATOMUMIN32:
17109 case X86::ATOMUMIN64: {
17111 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
17113 BuildMI(mainMBB, DL, TII->get(CMPOpc))
17117 if (Subtarget->hasCMov()) {
17118 if (VT != MVT::i8) {
17120 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
17124 // Promote i8 to i32 to use CMOV32
17125 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
17126 const TargetRegisterClass *RC32 =
17127 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
17128 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
17129 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
17130 unsigned Tmp = MRI.createVirtualRegister(RC32);
17132 unsigned Undef = MRI.createVirtualRegister(RC32);
17133 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
17135 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
17138 .addImm(X86::sub_8bit);
17139 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
17142 .addImm(X86::sub_8bit);
17144 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
17148 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
17149 .addReg(Tmp, 0, X86::sub_8bit);
17152 // Use pseudo select and lower them.
17153 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
17154 "Invalid atomic-load-op transformation!");
17155 unsigned SelOpc = getPseudoCMOVOpc(VT);
17156 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
17157 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
17158 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
17159 .addReg(SrcReg).addReg(t4)
17161 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17162 // Replace the original PHI node as mainMBB is changed after CMOV
17164 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
17165 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17166 Phi->eraseFromParent();
17172 // Copy PhyReg back from virtual register.
17173 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
17176 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17177 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17178 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17180 NewMO.setIsKill(false);
17181 MIB.addOperand(NewMO);
17184 MIB.setMemRefs(MMOBegin, MMOEnd);
17186 // Copy PhyReg back to virtual register.
17187 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
17190 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17192 mainMBB->addSuccessor(origMainMBB);
17193 mainMBB->addSuccessor(sinkMBB);
17196 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17197 TII->get(TargetOpcode::COPY), DstReg)
17200 MI->eraseFromParent();
17204 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
17205 // instructions. They will be translated into a spin-loop or compare-exchange
17209 // dst = atomic-fetch-op MI.addr, MI.val
17215 // t1L = LOAD [MI.addr + 0]
17216 // t1H = LOAD [MI.addr + 4]
17218 // t4L = phi(t1L, t3L / loop)
17219 // t4H = phi(t1H, t3H / loop)
17220 // t2L = OP MI.val.lo, t4L
17221 // t2H = OP MI.val.hi, t4H
17226 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17234 MachineBasicBlock *
17235 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
17236 MachineBasicBlock *MBB) const {
17237 MachineFunction *MF = MBB->getParent();
17238 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17239 DebugLoc DL = MI->getDebugLoc();
17241 MachineRegisterInfo &MRI = MF->getRegInfo();
17243 const BasicBlock *BB = MBB->getBasicBlock();
17244 MachineFunction::iterator I = MBB;
17247 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
17248 "Unexpected number of operands");
17250 assert(MI->hasOneMemOperand() &&
17251 "Expected atomic-load-op32 to have one memoperand");
17253 // Memory Reference
17254 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17255 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17257 unsigned DstLoReg, DstHiReg;
17258 unsigned SrcLoReg, SrcHiReg;
17259 unsigned MemOpndSlot;
17261 unsigned CurOp = 0;
17263 DstLoReg = MI->getOperand(CurOp++).getReg();
17264 DstHiReg = MI->getOperand(CurOp++).getReg();
17265 MemOpndSlot = CurOp;
17266 CurOp += X86::AddrNumOperands;
17267 SrcLoReg = MI->getOperand(CurOp++).getReg();
17268 SrcHiReg = MI->getOperand(CurOp++).getReg();
17270 const TargetRegisterClass *RC = &X86::GR32RegClass;
17271 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
17273 unsigned t1L = MRI.createVirtualRegister(RC);
17274 unsigned t1H = MRI.createVirtualRegister(RC);
17275 unsigned t2L = MRI.createVirtualRegister(RC);
17276 unsigned t2H = MRI.createVirtualRegister(RC);
17277 unsigned t3L = MRI.createVirtualRegister(RC);
17278 unsigned t3H = MRI.createVirtualRegister(RC);
17279 unsigned t4L = MRI.createVirtualRegister(RC);
17280 unsigned t4H = MRI.createVirtualRegister(RC);
17282 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
17283 unsigned LOADOpc = X86::MOV32rm;
17285 // For the atomic load-arith operator, we generate
17288 // t1L = LOAD [MI.addr + 0]
17289 // t1H = LOAD [MI.addr + 4]
17291 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
17292 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
17293 // t2L = OP MI.val.lo, t4L
17294 // t2H = OP MI.val.hi, t4H
17297 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17305 MachineBasicBlock *thisMBB = MBB;
17306 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17307 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17308 MF->insert(I, mainMBB);
17309 MF->insert(I, sinkMBB);
17311 MachineInstrBuilder MIB;
17313 // Transfer the remainder of BB and its successor edges to sinkMBB.
17314 sinkMBB->splice(sinkMBB->begin(), MBB,
17315 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17316 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17320 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
17321 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17322 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17324 NewMO.setIsKill(false);
17325 MIB.addOperand(NewMO);
17327 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17328 unsigned flags = (*MMOI)->getFlags();
17329 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17330 MachineMemOperand *MMO =
17331 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17332 (*MMOI)->getSize(),
17333 (*MMOI)->getBaseAlignment(),
17334 (*MMOI)->getTBAAInfo(),
17335 (*MMOI)->getRanges());
17336 MIB.addMemOperand(MMO);
17338 MachineInstr *LowMI = MIB;
17341 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
17342 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17343 if (i == X86::AddrDisp) {
17344 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
17346 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17348 NewMO.setIsKill(false);
17349 MIB.addOperand(NewMO);
17352 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
17354 thisMBB->addSuccessor(mainMBB);
17357 MachineBasicBlock *origMainMBB = mainMBB;
17360 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
17361 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17362 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
17363 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17365 unsigned Opc = MI->getOpcode();
17368 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
17369 case X86::ATOMAND6432:
17370 case X86::ATOMOR6432:
17371 case X86::ATOMXOR6432:
17372 case X86::ATOMADD6432:
17373 case X86::ATOMSUB6432: {
17375 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17376 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
17378 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
17382 case X86::ATOMNAND6432: {
17383 unsigned HiOpc, NOTOpc;
17384 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
17385 unsigned TmpL = MRI.createVirtualRegister(RC);
17386 unsigned TmpH = MRI.createVirtualRegister(RC);
17387 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
17389 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
17391 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
17392 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
17395 case X86::ATOMMAX6432:
17396 case X86::ATOMMIN6432:
17397 case X86::ATOMUMAX6432:
17398 case X86::ATOMUMIN6432: {
17400 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17401 unsigned cL = MRI.createVirtualRegister(RC8);
17402 unsigned cH = MRI.createVirtualRegister(RC8);
17403 unsigned cL32 = MRI.createVirtualRegister(RC);
17404 unsigned cH32 = MRI.createVirtualRegister(RC);
17405 unsigned cc = MRI.createVirtualRegister(RC);
17406 // cl := cmp src_lo, lo
17407 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17408 .addReg(SrcLoReg).addReg(t4L);
17409 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
17410 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
17411 // ch := cmp src_hi, hi
17412 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17413 .addReg(SrcHiReg).addReg(t4H);
17414 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
17415 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
17416 // cc := if (src_hi == hi) ? cl : ch;
17417 if (Subtarget->hasCMov()) {
17418 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
17419 .addReg(cH32).addReg(cL32);
17421 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
17422 .addReg(cH32).addReg(cL32)
17423 .addImm(X86::COND_E);
17424 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17426 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
17427 if (Subtarget->hasCMov()) {
17428 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
17429 .addReg(SrcLoReg).addReg(t4L);
17430 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
17431 .addReg(SrcHiReg).addReg(t4H);
17433 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
17434 .addReg(SrcLoReg).addReg(t4L)
17435 .addImm(X86::COND_NE);
17436 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17437 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
17438 // 2nd CMOV lowering.
17439 mainMBB->addLiveIn(X86::EFLAGS);
17440 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
17441 .addReg(SrcHiReg).addReg(t4H)
17442 .addImm(X86::COND_NE);
17443 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17444 // Replace the original PHI node as mainMBB is changed after CMOV
17446 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
17447 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17448 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
17449 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17450 PhiL->eraseFromParent();
17451 PhiH->eraseFromParent();
17455 case X86::ATOMSWAP6432: {
17457 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17458 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
17459 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
17464 // Copy EDX:EAX back from HiReg:LoReg
17465 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
17466 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
17467 // Copy ECX:EBX from t1H:t1L
17468 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
17469 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
17471 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17472 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17473 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17475 NewMO.setIsKill(false);
17476 MIB.addOperand(NewMO);
17478 MIB.setMemRefs(MMOBegin, MMOEnd);
17480 // Copy EDX:EAX back to t3H:t3L
17481 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
17482 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
17484 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17486 mainMBB->addSuccessor(origMainMBB);
17487 mainMBB->addSuccessor(sinkMBB);
17490 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17491 TII->get(TargetOpcode::COPY), DstLoReg)
17493 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17494 TII->get(TargetOpcode::COPY), DstHiReg)
17497 MI->eraseFromParent();
17501 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17502 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17503 // in the .td file.
17504 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17505 const TargetInstrInfo *TII) {
17507 switch (MI->getOpcode()) {
17508 default: llvm_unreachable("illegal opcode!");
17509 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17510 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17511 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17512 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17513 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17514 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17515 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17516 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17519 DebugLoc dl = MI->getDebugLoc();
17520 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17522 unsigned NumArgs = MI->getNumOperands();
17523 for (unsigned i = 1; i < NumArgs; ++i) {
17524 MachineOperand &Op = MI->getOperand(i);
17525 if (!(Op.isReg() && Op.isImplicit()))
17526 MIB.addOperand(Op);
17528 if (MI->hasOneMemOperand())
17529 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17531 BuildMI(*BB, MI, dl,
17532 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17533 .addReg(X86::XMM0);
17535 MI->eraseFromParent();
17539 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17540 // defs in an instruction pattern
17541 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17542 const TargetInstrInfo *TII) {
17544 switch (MI->getOpcode()) {
17545 default: llvm_unreachable("illegal opcode!");
17546 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17547 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17548 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17549 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17550 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17551 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17552 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17553 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17556 DebugLoc dl = MI->getDebugLoc();
17557 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17559 unsigned NumArgs = MI->getNumOperands(); // remove the results
17560 for (unsigned i = 1; i < NumArgs; ++i) {
17561 MachineOperand &Op = MI->getOperand(i);
17562 if (!(Op.isReg() && Op.isImplicit()))
17563 MIB.addOperand(Op);
17565 if (MI->hasOneMemOperand())
17566 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17568 BuildMI(*BB, MI, dl,
17569 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17572 MI->eraseFromParent();
17576 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17577 const TargetInstrInfo *TII,
17578 const X86Subtarget* Subtarget) {
17579 DebugLoc dl = MI->getDebugLoc();
17581 // Address into RAX/EAX, other two args into ECX, EDX.
17582 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17583 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17584 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17585 for (int i = 0; i < X86::AddrNumOperands; ++i)
17586 MIB.addOperand(MI->getOperand(i));
17588 unsigned ValOps = X86::AddrNumOperands;
17589 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17590 .addReg(MI->getOperand(ValOps).getReg());
17591 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17592 .addReg(MI->getOperand(ValOps+1).getReg());
17594 // The instruction doesn't actually take any operands though.
17595 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17597 MI->eraseFromParent(); // The pseudo is gone now.
17601 MachineBasicBlock *
17602 X86TargetLowering::EmitVAARG64WithCustomInserter(
17604 MachineBasicBlock *MBB) const {
17605 // Emit va_arg instruction on X86-64.
17607 // Operands to this pseudo-instruction:
17608 // 0 ) Output : destination address (reg)
17609 // 1-5) Input : va_list address (addr, i64mem)
17610 // 6 ) ArgSize : Size (in bytes) of vararg type
17611 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17612 // 8 ) Align : Alignment of type
17613 // 9 ) EFLAGS (implicit-def)
17615 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17616 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17618 unsigned DestReg = MI->getOperand(0).getReg();
17619 MachineOperand &Base = MI->getOperand(1);
17620 MachineOperand &Scale = MI->getOperand(2);
17621 MachineOperand &Index = MI->getOperand(3);
17622 MachineOperand &Disp = MI->getOperand(4);
17623 MachineOperand &Segment = MI->getOperand(5);
17624 unsigned ArgSize = MI->getOperand(6).getImm();
17625 unsigned ArgMode = MI->getOperand(7).getImm();
17626 unsigned Align = MI->getOperand(8).getImm();
17628 // Memory Reference
17629 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17630 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17631 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17633 // Machine Information
17634 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17635 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17636 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17637 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17638 DebugLoc DL = MI->getDebugLoc();
17640 // struct va_list {
17643 // i64 overflow_area (address)
17644 // i64 reg_save_area (address)
17646 // sizeof(va_list) = 24
17647 // alignment(va_list) = 8
17649 unsigned TotalNumIntRegs = 6;
17650 unsigned TotalNumXMMRegs = 8;
17651 bool UseGPOffset = (ArgMode == 1);
17652 bool UseFPOffset = (ArgMode == 2);
17653 unsigned MaxOffset = TotalNumIntRegs * 8 +
17654 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17656 /* Align ArgSize to a multiple of 8 */
17657 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17658 bool NeedsAlign = (Align > 8);
17660 MachineBasicBlock *thisMBB = MBB;
17661 MachineBasicBlock *overflowMBB;
17662 MachineBasicBlock *offsetMBB;
17663 MachineBasicBlock *endMBB;
17665 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17666 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17667 unsigned OffsetReg = 0;
17669 if (!UseGPOffset && !UseFPOffset) {
17670 // If we only pull from the overflow region, we don't create a branch.
17671 // We don't need to alter control flow.
17672 OffsetDestReg = 0; // unused
17673 OverflowDestReg = DestReg;
17675 offsetMBB = nullptr;
17676 overflowMBB = thisMBB;
17679 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17680 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17681 // If not, pull from overflow_area. (branch to overflowMBB)
17686 // offsetMBB overflowMBB
17691 // Registers for the PHI in endMBB
17692 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17693 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17695 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17696 MachineFunction *MF = MBB->getParent();
17697 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17698 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17699 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17701 MachineFunction::iterator MBBIter = MBB;
17704 // Insert the new basic blocks
17705 MF->insert(MBBIter, offsetMBB);
17706 MF->insert(MBBIter, overflowMBB);
17707 MF->insert(MBBIter, endMBB);
17709 // Transfer the remainder of MBB and its successor edges to endMBB.
17710 endMBB->splice(endMBB->begin(), thisMBB,
17711 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17712 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17714 // Make offsetMBB and overflowMBB successors of thisMBB
17715 thisMBB->addSuccessor(offsetMBB);
17716 thisMBB->addSuccessor(overflowMBB);
17718 // endMBB is a successor of both offsetMBB and overflowMBB
17719 offsetMBB->addSuccessor(endMBB);
17720 overflowMBB->addSuccessor(endMBB);
17722 // Load the offset value into a register
17723 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17724 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17728 .addDisp(Disp, UseFPOffset ? 4 : 0)
17729 .addOperand(Segment)
17730 .setMemRefs(MMOBegin, MMOEnd);
17732 // Check if there is enough room left to pull this argument.
17733 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17735 .addImm(MaxOffset + 8 - ArgSizeA8);
17737 // Branch to "overflowMBB" if offset >= max
17738 // Fall through to "offsetMBB" otherwise
17739 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17740 .addMBB(overflowMBB);
17743 // In offsetMBB, emit code to use the reg_save_area.
17745 assert(OffsetReg != 0);
17747 // Read the reg_save_area address.
17748 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17749 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17754 .addOperand(Segment)
17755 .setMemRefs(MMOBegin, MMOEnd);
17757 // Zero-extend the offset
17758 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17759 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17762 .addImm(X86::sub_32bit);
17764 // Add the offset to the reg_save_area to get the final address.
17765 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17766 .addReg(OffsetReg64)
17767 .addReg(RegSaveReg);
17769 // Compute the offset for the next argument
17770 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17771 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17773 .addImm(UseFPOffset ? 16 : 8);
17775 // Store it back into the va_list.
17776 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17780 .addDisp(Disp, UseFPOffset ? 4 : 0)
17781 .addOperand(Segment)
17782 .addReg(NextOffsetReg)
17783 .setMemRefs(MMOBegin, MMOEnd);
17786 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17791 // Emit code to use overflow area
17794 // Load the overflow_area address into a register.
17795 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17796 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17801 .addOperand(Segment)
17802 .setMemRefs(MMOBegin, MMOEnd);
17804 // If we need to align it, do so. Otherwise, just copy the address
17805 // to OverflowDestReg.
17807 // Align the overflow address
17808 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17809 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17811 // aligned_addr = (addr + (align-1)) & ~(align-1)
17812 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17813 .addReg(OverflowAddrReg)
17816 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17818 .addImm(~(uint64_t)(Align-1));
17820 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17821 .addReg(OverflowAddrReg);
17824 // Compute the next overflow address after this argument.
17825 // (the overflow address should be kept 8-byte aligned)
17826 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17827 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17828 .addReg(OverflowDestReg)
17829 .addImm(ArgSizeA8);
17831 // Store the new overflow address.
17832 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17837 .addOperand(Segment)
17838 .addReg(NextAddrReg)
17839 .setMemRefs(MMOBegin, MMOEnd);
17841 // If we branched, emit the PHI to the front of endMBB.
17843 BuildMI(*endMBB, endMBB->begin(), DL,
17844 TII->get(X86::PHI), DestReg)
17845 .addReg(OffsetDestReg).addMBB(offsetMBB)
17846 .addReg(OverflowDestReg).addMBB(overflowMBB);
17849 // Erase the pseudo instruction
17850 MI->eraseFromParent();
17855 MachineBasicBlock *
17856 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17858 MachineBasicBlock *MBB) const {
17859 // Emit code to save XMM registers to the stack. The ABI says that the
17860 // number of registers to save is given in %al, so it's theoretically
17861 // possible to do an indirect jump trick to avoid saving all of them,
17862 // however this code takes a simpler approach and just executes all
17863 // of the stores if %al is non-zero. It's less code, and it's probably
17864 // easier on the hardware branch predictor, and stores aren't all that
17865 // expensive anyway.
17867 // Create the new basic blocks. One block contains all the XMM stores,
17868 // and one block is the final destination regardless of whether any
17869 // stores were performed.
17870 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17871 MachineFunction *F = MBB->getParent();
17872 MachineFunction::iterator MBBIter = MBB;
17874 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17875 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17876 F->insert(MBBIter, XMMSaveMBB);
17877 F->insert(MBBIter, EndMBB);
17879 // Transfer the remainder of MBB and its successor edges to EndMBB.
17880 EndMBB->splice(EndMBB->begin(), MBB,
17881 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17882 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17884 // The original block will now fall through to the XMM save block.
17885 MBB->addSuccessor(XMMSaveMBB);
17886 // The XMMSaveMBB will fall through to the end block.
17887 XMMSaveMBB->addSuccessor(EndMBB);
17889 // Now add the instructions.
17890 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17891 DebugLoc DL = MI->getDebugLoc();
17893 unsigned CountReg = MI->getOperand(0).getReg();
17894 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17895 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17897 if (!Subtarget->isTargetWin64()) {
17898 // If %al is 0, branch around the XMM save block.
17899 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17900 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17901 MBB->addSuccessor(EndMBB);
17904 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17905 // that was just emitted, but clearly shouldn't be "saved".
17906 assert((MI->getNumOperands() <= 3 ||
17907 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17908 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17909 && "Expected last argument to be EFLAGS");
17910 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17911 // In the XMM save block, save all the XMM argument registers.
17912 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17913 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17914 MachineMemOperand *MMO =
17915 F->getMachineMemOperand(
17916 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17917 MachineMemOperand::MOStore,
17918 /*Size=*/16, /*Align=*/16);
17919 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17920 .addFrameIndex(RegSaveFrameIndex)
17921 .addImm(/*Scale=*/1)
17922 .addReg(/*IndexReg=*/0)
17923 .addImm(/*Disp=*/Offset)
17924 .addReg(/*Segment=*/0)
17925 .addReg(MI->getOperand(i).getReg())
17926 .addMemOperand(MMO);
17929 MI->eraseFromParent(); // The pseudo instruction is gone now.
17934 // The EFLAGS operand of SelectItr might be missing a kill marker
17935 // because there were multiple uses of EFLAGS, and ISel didn't know
17936 // which to mark. Figure out whether SelectItr should have had a
17937 // kill marker, and set it if it should. Returns the correct kill
17939 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17940 MachineBasicBlock* BB,
17941 const TargetRegisterInfo* TRI) {
17942 // Scan forward through BB for a use/def of EFLAGS.
17943 MachineBasicBlock::iterator miI(std::next(SelectItr));
17944 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17945 const MachineInstr& mi = *miI;
17946 if (mi.readsRegister(X86::EFLAGS))
17948 if (mi.definesRegister(X86::EFLAGS))
17949 break; // Should have kill-flag - update below.
17952 // If we hit the end of the block, check whether EFLAGS is live into a
17954 if (miI == BB->end()) {
17955 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17956 sEnd = BB->succ_end();
17957 sItr != sEnd; ++sItr) {
17958 MachineBasicBlock* succ = *sItr;
17959 if (succ->isLiveIn(X86::EFLAGS))
17964 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17965 // out. SelectMI should have a kill flag on EFLAGS.
17966 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17970 MachineBasicBlock *
17971 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17972 MachineBasicBlock *BB) const {
17973 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17974 DebugLoc DL = MI->getDebugLoc();
17976 // To "insert" a SELECT_CC instruction, we actually have to insert the
17977 // diamond control-flow pattern. The incoming instruction knows the
17978 // destination vreg to set, the condition code register to branch on, the
17979 // true/false values to select between, and a branch opcode to use.
17980 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17981 MachineFunction::iterator It = BB;
17987 // cmpTY ccX, r1, r2
17989 // fallthrough --> copy0MBB
17990 MachineBasicBlock *thisMBB = BB;
17991 MachineFunction *F = BB->getParent();
17992 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17993 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17994 F->insert(It, copy0MBB);
17995 F->insert(It, sinkMBB);
17997 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17998 // live into the sink and copy blocks.
17999 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
18000 if (!MI->killsRegister(X86::EFLAGS) &&
18001 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18002 copy0MBB->addLiveIn(X86::EFLAGS);
18003 sinkMBB->addLiveIn(X86::EFLAGS);
18006 // Transfer the remainder of BB and its successor edges to sinkMBB.
18007 sinkMBB->splice(sinkMBB->begin(), BB,
18008 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18009 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18011 // Add the true and fallthrough blocks as its successors.
18012 BB->addSuccessor(copy0MBB);
18013 BB->addSuccessor(sinkMBB);
18015 // Create the conditional branch instruction.
18017 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18018 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18021 // %FalseValue = ...
18022 // # fallthrough to sinkMBB
18023 copy0MBB->addSuccessor(sinkMBB);
18026 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18028 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18029 TII->get(X86::PHI), MI->getOperand(0).getReg())
18030 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18031 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18033 MI->eraseFromParent(); // The pseudo instruction is gone now.
18037 MachineBasicBlock *
18038 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18039 bool Is64Bit) const {
18040 MachineFunction *MF = BB->getParent();
18041 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18042 DebugLoc DL = MI->getDebugLoc();
18043 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18045 assert(MF->shouldSplitStack());
18047 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18048 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18051 // ... [Till the alloca]
18052 // If stacklet is not large enough, jump to mallocMBB
18055 // Allocate by subtracting from RSP
18056 // Jump to continueMBB
18059 // Allocate by call to runtime
18063 // [rest of original BB]
18066 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18067 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18068 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18070 MachineRegisterInfo &MRI = MF->getRegInfo();
18071 const TargetRegisterClass *AddrRegClass =
18072 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18074 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18075 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18076 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18077 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18078 sizeVReg = MI->getOperand(1).getReg(),
18079 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18081 MachineFunction::iterator MBBIter = BB;
18084 MF->insert(MBBIter, bumpMBB);
18085 MF->insert(MBBIter, mallocMBB);
18086 MF->insert(MBBIter, continueMBB);
18088 continueMBB->splice(continueMBB->begin(), BB,
18089 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18090 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18092 // Add code to the main basic block to check if the stack limit has been hit,
18093 // and if so, jump to mallocMBB otherwise to bumpMBB.
18094 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18095 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18096 .addReg(tmpSPVReg).addReg(sizeVReg);
18097 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18098 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18099 .addReg(SPLimitVReg);
18100 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18102 // bumpMBB simply decreases the stack pointer, since we know the current
18103 // stacklet has enough space.
18104 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18105 .addReg(SPLimitVReg);
18106 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18107 .addReg(SPLimitVReg);
18108 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18110 // Calls into a routine in libgcc to allocate more space from the heap.
18111 const uint32_t *RegMask =
18112 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18114 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18116 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18117 .addExternalSymbol("__morestack_allocate_stack_space")
18118 .addRegMask(RegMask)
18119 .addReg(X86::RDI, RegState::Implicit)
18120 .addReg(X86::RAX, RegState::ImplicitDefine);
18122 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18124 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18125 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18126 .addExternalSymbol("__morestack_allocate_stack_space")
18127 .addRegMask(RegMask)
18128 .addReg(X86::EAX, RegState::ImplicitDefine);
18132 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18135 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18136 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18137 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18139 // Set up the CFG correctly.
18140 BB->addSuccessor(bumpMBB);
18141 BB->addSuccessor(mallocMBB);
18142 mallocMBB->addSuccessor(continueMBB);
18143 bumpMBB->addSuccessor(continueMBB);
18145 // Take care of the PHI nodes.
18146 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18147 MI->getOperand(0).getReg())
18148 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18149 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18151 // Delete the original pseudo instruction.
18152 MI->eraseFromParent();
18155 return continueMBB;
18158 MachineBasicBlock *
18159 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18160 MachineBasicBlock *BB) const {
18161 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
18162 DebugLoc DL = MI->getDebugLoc();
18164 assert(!Subtarget->isTargetMacho());
18166 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18167 // non-trivial part is impdef of ESP.
18169 if (Subtarget->isTargetWin64()) {
18170 if (Subtarget->isTargetCygMing()) {
18171 // ___chkstk(Mingw64):
18172 // Clobbers R10, R11, RAX and EFLAGS.
18174 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18175 .addExternalSymbol("___chkstk")
18176 .addReg(X86::RAX, RegState::Implicit)
18177 .addReg(X86::RSP, RegState::Implicit)
18178 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18179 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18180 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18182 // __chkstk(MSVCRT): does not update stack pointer.
18183 // Clobbers R10, R11 and EFLAGS.
18184 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18185 .addExternalSymbol("__chkstk")
18186 .addReg(X86::RAX, RegState::Implicit)
18187 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18188 // RAX has the offset to be subtracted from RSP.
18189 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18194 const char *StackProbeSymbol =
18195 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18197 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18198 .addExternalSymbol(StackProbeSymbol)
18199 .addReg(X86::EAX, RegState::Implicit)
18200 .addReg(X86::ESP, RegState::Implicit)
18201 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18202 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18203 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18206 MI->eraseFromParent(); // The pseudo instruction is gone now.
18210 MachineBasicBlock *
18211 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18212 MachineBasicBlock *BB) const {
18213 // This is pretty easy. We're taking the value that we received from
18214 // our load from the relocation, sticking it in either RDI (x86-64)
18215 // or EAX and doing an indirect call. The return value will then
18216 // be in the normal return register.
18217 MachineFunction *F = BB->getParent();
18218 const X86InstrInfo *TII
18219 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
18220 DebugLoc DL = MI->getDebugLoc();
18222 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18223 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18225 // Get a register mask for the lowered call.
18226 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18227 // proper register mask.
18228 const uint32_t *RegMask =
18229 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18230 if (Subtarget->is64Bit()) {
18231 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18232 TII->get(X86::MOV64rm), X86::RDI)
18234 .addImm(0).addReg(0)
18235 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18236 MI->getOperand(3).getTargetFlags())
18238 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18239 addDirectMem(MIB, X86::RDI);
18240 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18241 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18242 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18243 TII->get(X86::MOV32rm), X86::EAX)
18245 .addImm(0).addReg(0)
18246 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18247 MI->getOperand(3).getTargetFlags())
18249 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18250 addDirectMem(MIB, X86::EAX);
18251 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18253 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18254 TII->get(X86::MOV32rm), X86::EAX)
18255 .addReg(TII->getGlobalBaseReg(F))
18256 .addImm(0).addReg(0)
18257 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18258 MI->getOperand(3).getTargetFlags())
18260 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18261 addDirectMem(MIB, X86::EAX);
18262 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18265 MI->eraseFromParent(); // The pseudo instruction is gone now.
18269 MachineBasicBlock *
18270 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18271 MachineBasicBlock *MBB) const {
18272 DebugLoc DL = MI->getDebugLoc();
18273 MachineFunction *MF = MBB->getParent();
18274 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18275 MachineRegisterInfo &MRI = MF->getRegInfo();
18277 const BasicBlock *BB = MBB->getBasicBlock();
18278 MachineFunction::iterator I = MBB;
18281 // Memory Reference
18282 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18283 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18286 unsigned MemOpndSlot = 0;
18288 unsigned CurOp = 0;
18290 DstReg = MI->getOperand(CurOp++).getReg();
18291 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18292 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18293 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18294 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18296 MemOpndSlot = CurOp;
18298 MVT PVT = getPointerTy();
18299 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18300 "Invalid Pointer Size!");
18302 // For v = setjmp(buf), we generate
18305 // buf[LabelOffset] = restoreMBB
18306 // SjLjSetup restoreMBB
18312 // v = phi(main, restore)
18317 MachineBasicBlock *thisMBB = MBB;
18318 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18319 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18320 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18321 MF->insert(I, mainMBB);
18322 MF->insert(I, sinkMBB);
18323 MF->push_back(restoreMBB);
18325 MachineInstrBuilder MIB;
18327 // Transfer the remainder of BB and its successor edges to sinkMBB.
18328 sinkMBB->splice(sinkMBB->begin(), MBB,
18329 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18330 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18333 unsigned PtrStoreOpc = 0;
18334 unsigned LabelReg = 0;
18335 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18336 Reloc::Model RM = MF->getTarget().getRelocationModel();
18337 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18338 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18340 // Prepare IP either in reg or imm.
18341 if (!UseImmLabel) {
18342 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18343 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18344 LabelReg = MRI.createVirtualRegister(PtrRC);
18345 if (Subtarget->is64Bit()) {
18346 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18350 .addMBB(restoreMBB)
18353 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18354 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18355 .addReg(XII->getGlobalBaseReg(MF))
18358 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18362 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18364 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18365 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18366 if (i == X86::AddrDisp)
18367 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18369 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18372 MIB.addReg(LabelReg);
18374 MIB.addMBB(restoreMBB);
18375 MIB.setMemRefs(MMOBegin, MMOEnd);
18377 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18378 .addMBB(restoreMBB);
18380 const X86RegisterInfo *RegInfo =
18381 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18382 MIB.addRegMask(RegInfo->getNoPreservedMask());
18383 thisMBB->addSuccessor(mainMBB);
18384 thisMBB->addSuccessor(restoreMBB);
18388 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18389 mainMBB->addSuccessor(sinkMBB);
18392 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18393 TII->get(X86::PHI), DstReg)
18394 .addReg(mainDstReg).addMBB(mainMBB)
18395 .addReg(restoreDstReg).addMBB(restoreMBB);
18398 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18399 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18400 restoreMBB->addSuccessor(sinkMBB);
18402 MI->eraseFromParent();
18406 MachineBasicBlock *
18407 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18408 MachineBasicBlock *MBB) const {
18409 DebugLoc DL = MI->getDebugLoc();
18410 MachineFunction *MF = MBB->getParent();
18411 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18412 MachineRegisterInfo &MRI = MF->getRegInfo();
18414 // Memory Reference
18415 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18416 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18418 MVT PVT = getPointerTy();
18419 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18420 "Invalid Pointer Size!");
18422 const TargetRegisterClass *RC =
18423 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18424 unsigned Tmp = MRI.createVirtualRegister(RC);
18425 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18426 const X86RegisterInfo *RegInfo =
18427 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18428 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18429 unsigned SP = RegInfo->getStackRegister();
18431 MachineInstrBuilder MIB;
18433 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18434 const int64_t SPOffset = 2 * PVT.getStoreSize();
18436 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18437 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18440 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18441 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18442 MIB.addOperand(MI->getOperand(i));
18443 MIB.setMemRefs(MMOBegin, MMOEnd);
18445 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18446 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18447 if (i == X86::AddrDisp)
18448 MIB.addDisp(MI->getOperand(i), LabelOffset);
18450 MIB.addOperand(MI->getOperand(i));
18452 MIB.setMemRefs(MMOBegin, MMOEnd);
18454 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18455 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18456 if (i == X86::AddrDisp)
18457 MIB.addDisp(MI->getOperand(i), SPOffset);
18459 MIB.addOperand(MI->getOperand(i));
18461 MIB.setMemRefs(MMOBegin, MMOEnd);
18463 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18465 MI->eraseFromParent();
18469 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18470 // accumulator loops. Writing back to the accumulator allows the coalescer
18471 // to remove extra copies in the loop.
18472 MachineBasicBlock *
18473 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18474 MachineBasicBlock *MBB) const {
18475 MachineOperand &AddendOp = MI->getOperand(3);
18477 // Bail out early if the addend isn't a register - we can't switch these.
18478 if (!AddendOp.isReg())
18481 MachineFunction &MF = *MBB->getParent();
18482 MachineRegisterInfo &MRI = MF.getRegInfo();
18484 // Check whether the addend is defined by a PHI:
18485 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18486 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18487 if (!AddendDef.isPHI())
18490 // Look for the following pattern:
18492 // %addend = phi [%entry, 0], [%loop, %result]
18494 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18498 // %addend = phi [%entry, 0], [%loop, %result]
18500 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18502 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18503 assert(AddendDef.getOperand(i).isReg());
18504 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18505 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18506 if (&PHISrcInst == MI) {
18507 // Found a matching instruction.
18508 unsigned NewFMAOpc = 0;
18509 switch (MI->getOpcode()) {
18510 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18511 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18512 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18513 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18514 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18515 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18516 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18517 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18518 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18519 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18520 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18521 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18522 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18523 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18524 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18525 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18526 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18527 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18528 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18529 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18530 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18531 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18532 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18533 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18534 default: llvm_unreachable("Unrecognized FMA variant.");
18537 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18538 MachineInstrBuilder MIB =
18539 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18540 .addOperand(MI->getOperand(0))
18541 .addOperand(MI->getOperand(3))
18542 .addOperand(MI->getOperand(2))
18543 .addOperand(MI->getOperand(1));
18544 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18545 MI->eraseFromParent();
18552 MachineBasicBlock *
18553 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18554 MachineBasicBlock *BB) const {
18555 switch (MI->getOpcode()) {
18556 default: llvm_unreachable("Unexpected instr type to insert");
18557 case X86::TAILJMPd64:
18558 case X86::TAILJMPr64:
18559 case X86::TAILJMPm64:
18560 llvm_unreachable("TAILJMP64 would not be touched here.");
18561 case X86::TCRETURNdi64:
18562 case X86::TCRETURNri64:
18563 case X86::TCRETURNmi64:
18565 case X86::WIN_ALLOCA:
18566 return EmitLoweredWinAlloca(MI, BB);
18567 case X86::SEG_ALLOCA_32:
18568 return EmitLoweredSegAlloca(MI, BB, false);
18569 case X86::SEG_ALLOCA_64:
18570 return EmitLoweredSegAlloca(MI, BB, true);
18571 case X86::TLSCall_32:
18572 case X86::TLSCall_64:
18573 return EmitLoweredTLSCall(MI, BB);
18574 case X86::CMOV_GR8:
18575 case X86::CMOV_FR32:
18576 case X86::CMOV_FR64:
18577 case X86::CMOV_V4F32:
18578 case X86::CMOV_V2F64:
18579 case X86::CMOV_V2I64:
18580 case X86::CMOV_V8F32:
18581 case X86::CMOV_V4F64:
18582 case X86::CMOV_V4I64:
18583 case X86::CMOV_V16F32:
18584 case X86::CMOV_V8F64:
18585 case X86::CMOV_V8I64:
18586 case X86::CMOV_GR16:
18587 case X86::CMOV_GR32:
18588 case X86::CMOV_RFP32:
18589 case X86::CMOV_RFP64:
18590 case X86::CMOV_RFP80:
18591 return EmitLoweredSelect(MI, BB);
18593 case X86::FP32_TO_INT16_IN_MEM:
18594 case X86::FP32_TO_INT32_IN_MEM:
18595 case X86::FP32_TO_INT64_IN_MEM:
18596 case X86::FP64_TO_INT16_IN_MEM:
18597 case X86::FP64_TO_INT32_IN_MEM:
18598 case X86::FP64_TO_INT64_IN_MEM:
18599 case X86::FP80_TO_INT16_IN_MEM:
18600 case X86::FP80_TO_INT32_IN_MEM:
18601 case X86::FP80_TO_INT64_IN_MEM: {
18602 MachineFunction *F = BB->getParent();
18603 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18604 DebugLoc DL = MI->getDebugLoc();
18606 // Change the floating point control register to use "round towards zero"
18607 // mode when truncating to an integer value.
18608 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18609 addFrameReference(BuildMI(*BB, MI, DL,
18610 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18612 // Load the old value of the high byte of the control word...
18614 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18615 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18618 // Set the high part to be round to zero...
18619 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18622 // Reload the modified control word now...
18623 addFrameReference(BuildMI(*BB, MI, DL,
18624 TII->get(X86::FLDCW16m)), CWFrameIdx);
18626 // Restore the memory image of control word to original value
18627 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18630 // Get the X86 opcode to use.
18632 switch (MI->getOpcode()) {
18633 default: llvm_unreachable("illegal opcode!");
18634 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18635 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18636 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18637 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18638 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18639 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18640 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18641 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18642 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18646 MachineOperand &Op = MI->getOperand(0);
18648 AM.BaseType = X86AddressMode::RegBase;
18649 AM.Base.Reg = Op.getReg();
18651 AM.BaseType = X86AddressMode::FrameIndexBase;
18652 AM.Base.FrameIndex = Op.getIndex();
18654 Op = MI->getOperand(1);
18656 AM.Scale = Op.getImm();
18657 Op = MI->getOperand(2);
18659 AM.IndexReg = Op.getImm();
18660 Op = MI->getOperand(3);
18661 if (Op.isGlobal()) {
18662 AM.GV = Op.getGlobal();
18664 AM.Disp = Op.getImm();
18666 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18667 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18669 // Reload the original control word now.
18670 addFrameReference(BuildMI(*BB, MI, DL,
18671 TII->get(X86::FLDCW16m)), CWFrameIdx);
18673 MI->eraseFromParent(); // The pseudo instruction is gone now.
18676 // String/text processing lowering.
18677 case X86::PCMPISTRM128REG:
18678 case X86::VPCMPISTRM128REG:
18679 case X86::PCMPISTRM128MEM:
18680 case X86::VPCMPISTRM128MEM:
18681 case X86::PCMPESTRM128REG:
18682 case X86::VPCMPESTRM128REG:
18683 case X86::PCMPESTRM128MEM:
18684 case X86::VPCMPESTRM128MEM:
18685 assert(Subtarget->hasSSE42() &&
18686 "Target must have SSE4.2 or AVX features enabled");
18687 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18689 // String/text processing lowering.
18690 case X86::PCMPISTRIREG:
18691 case X86::VPCMPISTRIREG:
18692 case X86::PCMPISTRIMEM:
18693 case X86::VPCMPISTRIMEM:
18694 case X86::PCMPESTRIREG:
18695 case X86::VPCMPESTRIREG:
18696 case X86::PCMPESTRIMEM:
18697 case X86::VPCMPESTRIMEM:
18698 assert(Subtarget->hasSSE42() &&
18699 "Target must have SSE4.2 or AVX features enabled");
18700 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18702 // Thread synchronization.
18704 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18708 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18710 // Atomic Lowering.
18711 case X86::ATOMAND8:
18712 case X86::ATOMAND16:
18713 case X86::ATOMAND32:
18714 case X86::ATOMAND64:
18717 case X86::ATOMOR16:
18718 case X86::ATOMOR32:
18719 case X86::ATOMOR64:
18721 case X86::ATOMXOR16:
18722 case X86::ATOMXOR8:
18723 case X86::ATOMXOR32:
18724 case X86::ATOMXOR64:
18726 case X86::ATOMNAND8:
18727 case X86::ATOMNAND16:
18728 case X86::ATOMNAND32:
18729 case X86::ATOMNAND64:
18731 case X86::ATOMMAX8:
18732 case X86::ATOMMAX16:
18733 case X86::ATOMMAX32:
18734 case X86::ATOMMAX64:
18736 case X86::ATOMMIN8:
18737 case X86::ATOMMIN16:
18738 case X86::ATOMMIN32:
18739 case X86::ATOMMIN64:
18741 case X86::ATOMUMAX8:
18742 case X86::ATOMUMAX16:
18743 case X86::ATOMUMAX32:
18744 case X86::ATOMUMAX64:
18746 case X86::ATOMUMIN8:
18747 case X86::ATOMUMIN16:
18748 case X86::ATOMUMIN32:
18749 case X86::ATOMUMIN64:
18750 return EmitAtomicLoadArith(MI, BB);
18752 // This group does 64-bit operations on a 32-bit host.
18753 case X86::ATOMAND6432:
18754 case X86::ATOMOR6432:
18755 case X86::ATOMXOR6432:
18756 case X86::ATOMNAND6432:
18757 case X86::ATOMADD6432:
18758 case X86::ATOMSUB6432:
18759 case X86::ATOMMAX6432:
18760 case X86::ATOMMIN6432:
18761 case X86::ATOMUMAX6432:
18762 case X86::ATOMUMIN6432:
18763 case X86::ATOMSWAP6432:
18764 return EmitAtomicLoadArith6432(MI, BB);
18766 case X86::VASTART_SAVE_XMM_REGS:
18767 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18769 case X86::VAARG_64:
18770 return EmitVAARG64WithCustomInserter(MI, BB);
18772 case X86::EH_SjLj_SetJmp32:
18773 case X86::EH_SjLj_SetJmp64:
18774 return emitEHSjLjSetJmp(MI, BB);
18776 case X86::EH_SjLj_LongJmp32:
18777 case X86::EH_SjLj_LongJmp64:
18778 return emitEHSjLjLongJmp(MI, BB);
18780 case TargetOpcode::STACKMAP:
18781 case TargetOpcode::PATCHPOINT:
18782 return emitPatchPoint(MI, BB);
18784 case X86::VFMADDPDr213r:
18785 case X86::VFMADDPSr213r:
18786 case X86::VFMADDSDr213r:
18787 case X86::VFMADDSSr213r:
18788 case X86::VFMSUBPDr213r:
18789 case X86::VFMSUBPSr213r:
18790 case X86::VFMSUBSDr213r:
18791 case X86::VFMSUBSSr213r:
18792 case X86::VFNMADDPDr213r:
18793 case X86::VFNMADDPSr213r:
18794 case X86::VFNMADDSDr213r:
18795 case X86::VFNMADDSSr213r:
18796 case X86::VFNMSUBPDr213r:
18797 case X86::VFNMSUBPSr213r:
18798 case X86::VFNMSUBSDr213r:
18799 case X86::VFNMSUBSSr213r:
18800 case X86::VFMADDPDr213rY:
18801 case X86::VFMADDPSr213rY:
18802 case X86::VFMSUBPDr213rY:
18803 case X86::VFMSUBPSr213rY:
18804 case X86::VFNMADDPDr213rY:
18805 case X86::VFNMADDPSr213rY:
18806 case X86::VFNMSUBPDr213rY:
18807 case X86::VFNMSUBPSr213rY:
18808 return emitFMA3Instr(MI, BB);
18812 //===----------------------------------------------------------------------===//
18813 // X86 Optimization Hooks
18814 //===----------------------------------------------------------------------===//
18816 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18819 const SelectionDAG &DAG,
18820 unsigned Depth) const {
18821 unsigned BitWidth = KnownZero.getBitWidth();
18822 unsigned Opc = Op.getOpcode();
18823 assert((Opc >= ISD::BUILTIN_OP_END ||
18824 Opc == ISD::INTRINSIC_WO_CHAIN ||
18825 Opc == ISD::INTRINSIC_W_CHAIN ||
18826 Opc == ISD::INTRINSIC_VOID) &&
18827 "Should use MaskedValueIsZero if you don't know whether Op"
18828 " is a target node!");
18830 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18844 // These nodes' second result is a boolean.
18845 if (Op.getResNo() == 0)
18848 case X86ISD::SETCC:
18849 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18851 case ISD::INTRINSIC_WO_CHAIN: {
18852 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18853 unsigned NumLoBits = 0;
18856 case Intrinsic::x86_sse_movmsk_ps:
18857 case Intrinsic::x86_avx_movmsk_ps_256:
18858 case Intrinsic::x86_sse2_movmsk_pd:
18859 case Intrinsic::x86_avx_movmsk_pd_256:
18860 case Intrinsic::x86_mmx_pmovmskb:
18861 case Intrinsic::x86_sse2_pmovmskb_128:
18862 case Intrinsic::x86_avx2_pmovmskb: {
18863 // High bits of movmskp{s|d}, pmovmskb are known zero.
18865 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18866 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18867 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18868 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18869 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18870 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18871 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18872 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18874 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18883 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18885 const SelectionDAG &,
18886 unsigned Depth) const {
18887 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18888 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18889 return Op.getValueType().getScalarType().getSizeInBits();
18895 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18896 /// node is a GlobalAddress + offset.
18897 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18898 const GlobalValue* &GA,
18899 int64_t &Offset) const {
18900 if (N->getOpcode() == X86ISD::Wrapper) {
18901 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18902 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18903 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18907 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18910 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18911 /// same as extracting the high 128-bit part of 256-bit vector and then
18912 /// inserting the result into the low part of a new 256-bit vector
18913 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18914 EVT VT = SVOp->getValueType(0);
18915 unsigned NumElems = VT.getVectorNumElements();
18917 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18918 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18919 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18920 SVOp->getMaskElt(j) >= 0)
18926 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18927 /// same as extracting the low 128-bit part of 256-bit vector and then
18928 /// inserting the result into the high part of a new 256-bit vector
18929 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18930 EVT VT = SVOp->getValueType(0);
18931 unsigned NumElems = VT.getVectorNumElements();
18933 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18934 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18935 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18936 SVOp->getMaskElt(j) >= 0)
18942 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18943 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18944 TargetLowering::DAGCombinerInfo &DCI,
18945 const X86Subtarget* Subtarget) {
18947 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18948 SDValue V1 = SVOp->getOperand(0);
18949 SDValue V2 = SVOp->getOperand(1);
18950 EVT VT = SVOp->getValueType(0);
18951 unsigned NumElems = VT.getVectorNumElements();
18953 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18954 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18958 // V UNDEF BUILD_VECTOR UNDEF
18960 // CONCAT_VECTOR CONCAT_VECTOR
18963 // RESULT: V + zero extended
18965 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18966 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18967 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18970 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18973 // To match the shuffle mask, the first half of the mask should
18974 // be exactly the first vector, and all the rest a splat with the
18975 // first element of the second one.
18976 for (unsigned i = 0; i != NumElems/2; ++i)
18977 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18978 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18981 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18982 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18983 if (Ld->hasNUsesOfValue(1, 0)) {
18984 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18985 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18987 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18989 Ld->getPointerInfo(),
18990 Ld->getAlignment(),
18991 false/*isVolatile*/, true/*ReadMem*/,
18992 false/*WriteMem*/);
18994 // Make sure the newly-created LOAD is in the same position as Ld in
18995 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18996 // and update uses of Ld's output chain to use the TokenFactor.
18997 if (Ld->hasAnyUseOfValue(1)) {
18998 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18999 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19000 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19001 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19002 SDValue(ResNode.getNode(), 1));
19005 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19009 // Emit a zeroed vector and insert the desired subvector on its
19011 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19012 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19013 return DCI.CombineTo(N, InsV);
19016 //===--------------------------------------------------------------------===//
19017 // Combine some shuffles into subvector extracts and inserts:
19020 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19021 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19022 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19023 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19024 return DCI.CombineTo(N, InsV);
19027 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19028 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19029 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19030 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19031 return DCI.CombineTo(N, InsV);
19037 /// \brief Get the PSHUF-style mask from PSHUF node.
19039 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19040 /// PSHUF-style masks that can be reused with such instructions.
19041 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19042 SmallVector<int, 4> Mask;
19044 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19048 switch (N.getOpcode()) {
19049 case X86ISD::PSHUFD:
19051 case X86ISD::PSHUFLW:
19054 case X86ISD::PSHUFHW:
19055 Mask.erase(Mask.begin(), Mask.begin() + 4);
19056 for (int &M : Mask)
19060 llvm_unreachable("No valid shuffle instruction found!");
19064 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19066 /// We walk up the chain and look for a combinable shuffle, skipping over
19067 /// shuffles that we could hoist this shuffle's transformation past without
19068 /// altering anything.
19069 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19071 TargetLowering::DAGCombinerInfo &DCI) {
19072 assert(N.getOpcode() == X86ISD::PSHUFD &&
19073 "Called with something other than an x86 128-bit half shuffle!");
19076 // Walk up a single-use chain looking for a combinable shuffle.
19077 SDValue V = N.getOperand(0);
19078 for (; V.hasOneUse(); V = V.getOperand(0)) {
19079 switch (V.getOpcode()) {
19081 return false; // Nothing combined!
19084 // Skip bitcasts as we always know the type for the target specific
19088 case X86ISD::PSHUFD:
19089 // Found another dword shuffle.
19092 case X86ISD::PSHUFLW:
19093 // Check that the low words (being shuffled) are the identity in the
19094 // dword shuffle, and the high words are self-contained.
19095 if (Mask[0] != 0 || Mask[1] != 1 ||
19096 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19101 case X86ISD::PSHUFHW:
19102 // Check that the high words (being shuffled) are the identity in the
19103 // dword shuffle, and the low words are self-contained.
19104 if (Mask[2] != 2 || Mask[3] != 3 ||
19105 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19110 // Break out of the loop if we break out of the switch.
19114 if (!V.hasOneUse())
19115 // We fell out of the loop without finding a viable combining instruction.
19118 // Record the old value to use in RAUW-ing.
19121 // Merge this node's mask and our incoming mask.
19122 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19123 for (int &M : Mask)
19125 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
19126 getV4X86ShuffleImm8ForMask(Mask, DAG));
19128 // Replace N with its operand as we're going to combine that shuffle away.
19129 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19131 // Replace the combinable shuffle with the combined one, updating all users
19132 // so that we re-evaluate the chain here.
19133 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19137 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19139 /// We walk up the chain, skipping shuffles of the other half and looking
19140 /// through shuffles which switch halves trying to find a shuffle of the same
19141 /// pair of dwords.
19142 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19144 TargetLowering::DAGCombinerInfo &DCI) {
19146 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19147 "Called with something other than an x86 128-bit half shuffle!");
19149 unsigned CombineOpcode = N.getOpcode();
19151 // Walk up a single-use chain looking for a combinable shuffle.
19152 SDValue V = N.getOperand(0);
19153 for (; V.hasOneUse(); V = V.getOperand(0)) {
19154 switch (V.getOpcode()) {
19156 return false; // Nothing combined!
19159 // Skip bitcasts as we always know the type for the target specific
19163 case X86ISD::PSHUFLW:
19164 case X86ISD::PSHUFHW:
19165 if (V.getOpcode() == CombineOpcode)
19168 // Other-half shuffles are no-ops.
19171 case X86ISD::PSHUFD: {
19172 // We can only handle pshufd if the half we are combining either stays in
19173 // its half, or switches to the other half. Bail if one of these isn't
19175 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19176 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19177 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19178 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19181 // Map the mask through the pshufd and keep walking up the chain.
19182 for (int i = 0; i < 4; ++i)
19183 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19185 // Switch halves if the pshufd does.
19187 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19191 // Break out of the loop if we break out of the switch.
19195 if (!V.hasOneUse())
19196 // We fell out of the loop without finding a viable combining instruction.
19199 // Record the old value to use in RAUW-ing.
19202 // Merge this node's mask and our incoming mask (adjusted to account for all
19203 // the pshufd instructions encountered).
19204 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19205 for (int &M : Mask)
19207 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19208 getV4X86ShuffleImm8ForMask(Mask, DAG));
19210 // Replace N with its operand as we're going to combine that shuffle away.
19211 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19213 // Replace the combinable shuffle with the combined one, updating all users
19214 // so that we re-evaluate the chain here.
19215 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19219 /// \brief Try to combine x86 target specific shuffles.
19220 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19221 TargetLowering::DAGCombinerInfo &DCI,
19222 const X86Subtarget *Subtarget) {
19224 MVT VT = N.getSimpleValueType();
19225 SmallVector<int, 4> Mask;
19227 switch (N.getOpcode()) {
19228 case X86ISD::PSHUFD:
19229 case X86ISD::PSHUFLW:
19230 case X86ISD::PSHUFHW:
19231 Mask = getPSHUFShuffleMask(N);
19232 assert(Mask.size() == 4);
19238 // Nuke no-op shuffles that show up after combining.
19239 if (isNoopShuffleMask(Mask))
19240 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19242 // Look for simplifications involving one or two shuffle instructions.
19243 SDValue V = N.getOperand(0);
19244 switch (N.getOpcode()) {
19247 case X86ISD::PSHUFLW:
19248 case X86ISD::PSHUFHW:
19249 assert(VT == MVT::v8i16);
19251 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19252 return SDValue(); // We combined away this shuffle, so we're done.
19254 // See if this reduces to a PSHUFD which is no more expensive and can
19255 // combine with more operations.
19256 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19257 areAdjacentMasksSequential(Mask)) {
19258 int DMask[] = {-1, -1, -1, -1};
19259 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19260 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19261 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19262 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19263 DCI.AddToWorklist(V.getNode());
19264 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19265 getV4X86ShuffleImm8ForMask(DMask, DAG));
19266 DCI.AddToWorklist(V.getNode());
19267 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19272 case X86ISD::PSHUFD:
19273 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19274 return SDValue(); // We combined away this shuffle.
19282 /// PerformShuffleCombine - Performs several different shuffle combines.
19283 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19284 TargetLowering::DAGCombinerInfo &DCI,
19285 const X86Subtarget *Subtarget) {
19287 SDValue N0 = N->getOperand(0);
19288 SDValue N1 = N->getOperand(1);
19289 EVT VT = N->getValueType(0);
19291 // Canonicalize shuffles that perform 'addsub' on packed float vectors
19292 // according to the rule:
19293 // (shuffle (FADD A, B), (FSUB A, B), Mask) ->
19294 // (shuffle (FSUB A, -B), (FADD A, -B), Mask)
19296 // Where 'Mask' is:
19297 // <0,5,2,7> -- for v4f32 and v4f64 shuffles;
19298 // <0,3> -- for v2f64 shuffles;
19299 // <0,9,2,11,4,13,6,15> -- for v8f32 shuffles.
19301 // This helps pattern-matching more SSE3/AVX ADDSUB instructions
19302 // during ISel stage.
19303 if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
19304 ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19305 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19306 N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
19307 // Operands to the FADD and FSUB must be the same.
19308 ((N0->getOperand(0) == N1->getOperand(0) &&
19309 N0->getOperand(1) == N1->getOperand(1)) ||
19310 // FADD is commutable. See if by commuting the operands of the FADD
19311 // we would still be able to match the operands of the FSUB dag node.
19312 (N0->getOperand(1) == N1->getOperand(0) &&
19313 N0->getOperand(0) == N1->getOperand(1))) &&
19314 N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
19315 N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
19317 ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
19318 unsigned NumElts = VT.getVectorNumElements();
19319 ArrayRef<int> Mask = SV->getMask();
19320 bool CanFold = true;
19322 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
19323 CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
19326 SDValue Op0 = N1->getOperand(0);
19327 SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
19328 SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
19329 SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
19330 return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
19334 // Don't create instructions with illegal types after legalize types has run.
19335 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19336 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19339 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19340 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19341 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19342 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19344 // During Type Legalization, when promoting illegal vector types,
19345 // the backend might introduce new shuffle dag nodes and bitcasts.
19347 // This code performs the following transformation:
19348 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19349 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19351 // We do this only if both the bitcast and the BINOP dag nodes have
19352 // one use. Also, perform this transformation only if the new binary
19353 // operation is legal. This is to avoid introducing dag nodes that
19354 // potentially need to be further expanded (or custom lowered) into a
19355 // less optimal sequence of dag nodes.
19356 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19357 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19358 N0.getOpcode() == ISD::BITCAST) {
19359 SDValue BC0 = N0.getOperand(0);
19360 EVT SVT = BC0.getValueType();
19361 unsigned Opcode = BC0.getOpcode();
19362 unsigned NumElts = VT.getVectorNumElements();
19364 if (BC0.hasOneUse() && SVT.isVector() &&
19365 SVT.getVectorNumElements() * 2 == NumElts &&
19366 TLI.isOperationLegal(Opcode, VT)) {
19367 bool CanFold = false;
19379 unsigned SVTNumElts = SVT.getVectorNumElements();
19380 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19381 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19382 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19383 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19384 CanFold = SVOp->getMaskElt(i) < 0;
19387 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19388 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19389 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19390 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19395 // Only handle 128 wide vector from here on.
19396 if (!VT.is128BitVector())
19399 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19400 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19401 // consecutive, non-overlapping, and in the right order.
19402 SmallVector<SDValue, 16> Elts;
19403 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19404 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19406 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19410 if (isTargetShuffle(N->getOpcode())) {
19412 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19413 if (Shuffle.getNode())
19420 /// PerformTruncateCombine - Converts truncate operation to
19421 /// a sequence of vector shuffle operations.
19422 /// It is possible when we truncate 256-bit vector to 128-bit vector
19423 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19424 TargetLowering::DAGCombinerInfo &DCI,
19425 const X86Subtarget *Subtarget) {
19429 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19430 /// specific shuffle of a load can be folded into a single element load.
19431 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19432 /// shuffles have been customed lowered so we need to handle those here.
19433 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19434 TargetLowering::DAGCombinerInfo &DCI) {
19435 if (DCI.isBeforeLegalizeOps())
19438 SDValue InVec = N->getOperand(0);
19439 SDValue EltNo = N->getOperand(1);
19441 if (!isa<ConstantSDNode>(EltNo))
19444 EVT VT = InVec.getValueType();
19446 bool HasShuffleIntoBitcast = false;
19447 if (InVec.getOpcode() == ISD::BITCAST) {
19448 // Don't duplicate a load with other uses.
19449 if (!InVec.hasOneUse())
19451 EVT BCVT = InVec.getOperand(0).getValueType();
19452 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19454 InVec = InVec.getOperand(0);
19455 HasShuffleIntoBitcast = true;
19458 if (!isTargetShuffle(InVec.getOpcode()))
19461 // Don't duplicate a load with other uses.
19462 if (!InVec.hasOneUse())
19465 SmallVector<int, 16> ShuffleMask;
19467 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19471 // Select the input vector, guarding against out of range extract vector.
19472 unsigned NumElems = VT.getVectorNumElements();
19473 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19474 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19475 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19476 : InVec.getOperand(1);
19478 // If inputs to shuffle are the same for both ops, then allow 2 uses
19479 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19481 if (LdNode.getOpcode() == ISD::BITCAST) {
19482 // Don't duplicate a load with other uses.
19483 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19486 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19487 LdNode = LdNode.getOperand(0);
19490 if (!ISD::isNormalLoad(LdNode.getNode()))
19493 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19495 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19498 if (HasShuffleIntoBitcast) {
19499 // If there's a bitcast before the shuffle, check if the load type and
19500 // alignment is valid.
19501 unsigned Align = LN0->getAlignment();
19502 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19503 unsigned NewAlign = TLI.getDataLayout()->
19504 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19506 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19510 // All checks match so transform back to vector_shuffle so that DAG combiner
19511 // can finish the job
19514 // Create shuffle node taking into account the case that its a unary shuffle
19515 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19516 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19517 InVec.getOperand(0), Shuffle,
19519 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19520 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19524 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19525 /// generation and convert it from being a bunch of shuffles and extracts
19526 /// to a simple store and scalar loads to extract the elements.
19527 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19528 TargetLowering::DAGCombinerInfo &DCI) {
19529 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19530 if (NewOp.getNode())
19533 SDValue InputVector = N->getOperand(0);
19535 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19536 // from mmx to v2i32 has a single usage.
19537 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19538 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19539 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19540 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19541 N->getValueType(0),
19542 InputVector.getNode()->getOperand(0));
19544 // Only operate on vectors of 4 elements, where the alternative shuffling
19545 // gets to be more expensive.
19546 if (InputVector.getValueType() != MVT::v4i32)
19549 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19550 // single use which is a sign-extend or zero-extend, and all elements are
19552 SmallVector<SDNode *, 4> Uses;
19553 unsigned ExtractedElements = 0;
19554 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19555 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19556 if (UI.getUse().getResNo() != InputVector.getResNo())
19559 SDNode *Extract = *UI;
19560 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19563 if (Extract->getValueType(0) != MVT::i32)
19565 if (!Extract->hasOneUse())
19567 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19568 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19570 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19573 // Record which element was extracted.
19574 ExtractedElements |=
19575 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19577 Uses.push_back(Extract);
19580 // If not all the elements were used, this may not be worthwhile.
19581 if (ExtractedElements != 15)
19584 // Ok, we've now decided to do the transformation.
19585 SDLoc dl(InputVector);
19587 // Store the value to a temporary stack slot.
19588 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19589 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19590 MachinePointerInfo(), false, false, 0);
19592 // Replace each use (extract) with a load of the appropriate element.
19593 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19594 UE = Uses.end(); UI != UE; ++UI) {
19595 SDNode *Extract = *UI;
19597 // cOMpute the element's address.
19598 SDValue Idx = Extract->getOperand(1);
19600 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19601 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19602 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19603 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19605 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19606 StackPtr, OffsetVal);
19608 // Load the scalar.
19609 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19610 ScalarAddr, MachinePointerInfo(),
19611 false, false, false, 0);
19613 // Replace the exact with the load.
19614 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19617 // The replacement was made in place; don't return anything.
19621 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19622 static std::pair<unsigned, bool>
19623 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19624 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19625 if (!VT.isVector())
19626 return std::make_pair(0, false);
19628 bool NeedSplit = false;
19629 switch (VT.getSimpleVT().SimpleTy) {
19630 default: return std::make_pair(0, false);
19634 if (!Subtarget->hasAVX2())
19636 if (!Subtarget->hasAVX())
19637 return std::make_pair(0, false);
19642 if (!Subtarget->hasSSE2())
19643 return std::make_pair(0, false);
19646 // SSE2 has only a small subset of the operations.
19647 bool hasUnsigned = Subtarget->hasSSE41() ||
19648 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19649 bool hasSigned = Subtarget->hasSSE41() ||
19650 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19652 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19655 // Check for x CC y ? x : y.
19656 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19657 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19662 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19665 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19668 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19671 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19673 // Check for x CC y ? y : x -- a min/max with reversed arms.
19674 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19675 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19680 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19683 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19686 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19689 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19693 return std::make_pair(Opc, NeedSplit);
19697 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19698 const X86Subtarget *Subtarget) {
19700 SDValue Cond = N->getOperand(0);
19701 SDValue LHS = N->getOperand(1);
19702 SDValue RHS = N->getOperand(2);
19704 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19705 SDValue CondSrc = Cond->getOperand(0);
19706 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19707 Cond = CondSrc->getOperand(0);
19710 MVT VT = N->getSimpleValueType(0);
19711 MVT EltVT = VT.getVectorElementType();
19712 unsigned NumElems = VT.getVectorNumElements();
19713 // There is no blend with immediate in AVX-512.
19714 if (VT.is512BitVector())
19717 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19719 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19722 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19725 unsigned MaskValue = 0;
19726 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19729 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19730 for (unsigned i = 0; i < NumElems; ++i) {
19731 // Be sure we emit undef where we can.
19732 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19733 ShuffleMask[i] = -1;
19735 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19738 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19741 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19743 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19744 TargetLowering::DAGCombinerInfo &DCI,
19745 const X86Subtarget *Subtarget) {
19747 SDValue Cond = N->getOperand(0);
19748 // Get the LHS/RHS of the select.
19749 SDValue LHS = N->getOperand(1);
19750 SDValue RHS = N->getOperand(2);
19751 EVT VT = LHS.getValueType();
19752 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19754 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19755 // instructions match the semantics of the common C idiom x<y?x:y but not
19756 // x<=y?x:y, because of how they handle negative zero (which can be
19757 // ignored in unsafe-math mode).
19758 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19759 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19760 (Subtarget->hasSSE2() ||
19761 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19762 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19764 unsigned Opcode = 0;
19765 // Check for x CC y ? x : y.
19766 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19767 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19771 // Converting this to a min would handle NaNs incorrectly, and swapping
19772 // the operands would cause it to handle comparisons between positive
19773 // and negative zero incorrectly.
19774 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19775 if (!DAG.getTarget().Options.UnsafeFPMath &&
19776 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19778 std::swap(LHS, RHS);
19780 Opcode = X86ISD::FMIN;
19783 // Converting this to a min would handle comparisons between positive
19784 // and negative zero incorrectly.
19785 if (!DAG.getTarget().Options.UnsafeFPMath &&
19786 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19788 Opcode = X86ISD::FMIN;
19791 // Converting this to a min would handle both negative zeros and NaNs
19792 // incorrectly, but we can swap the operands to fix both.
19793 std::swap(LHS, RHS);
19797 Opcode = X86ISD::FMIN;
19801 // Converting this to a max would handle comparisons between positive
19802 // and negative zero incorrectly.
19803 if (!DAG.getTarget().Options.UnsafeFPMath &&
19804 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19806 Opcode = X86ISD::FMAX;
19809 // Converting this to a max would handle NaNs incorrectly, and swapping
19810 // the operands would cause it to handle comparisons between positive
19811 // and negative zero incorrectly.
19812 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19813 if (!DAG.getTarget().Options.UnsafeFPMath &&
19814 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19816 std::swap(LHS, RHS);
19818 Opcode = X86ISD::FMAX;
19821 // Converting this to a max would handle both negative zeros and NaNs
19822 // incorrectly, but we can swap the operands to fix both.
19823 std::swap(LHS, RHS);
19827 Opcode = X86ISD::FMAX;
19830 // Check for x CC y ? y : x -- a min/max with reversed arms.
19831 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19832 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19836 // Converting this to a min would handle comparisons between positive
19837 // and negative zero incorrectly, and swapping the operands would
19838 // cause it to handle NaNs incorrectly.
19839 if (!DAG.getTarget().Options.UnsafeFPMath &&
19840 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19841 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19843 std::swap(LHS, RHS);
19845 Opcode = X86ISD::FMIN;
19848 // Converting this to a min would handle NaNs incorrectly.
19849 if (!DAG.getTarget().Options.UnsafeFPMath &&
19850 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19852 Opcode = X86ISD::FMIN;
19855 // Converting this to a min would handle both negative zeros and NaNs
19856 // incorrectly, but we can swap the operands to fix both.
19857 std::swap(LHS, RHS);
19861 Opcode = X86ISD::FMIN;
19865 // Converting this to a max would handle NaNs incorrectly.
19866 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19868 Opcode = X86ISD::FMAX;
19871 // Converting this to a max would handle comparisons between positive
19872 // and negative zero incorrectly, and swapping the operands would
19873 // cause it to handle NaNs incorrectly.
19874 if (!DAG.getTarget().Options.UnsafeFPMath &&
19875 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19876 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19878 std::swap(LHS, RHS);
19880 Opcode = X86ISD::FMAX;
19883 // Converting this to a max would handle both negative zeros and NaNs
19884 // incorrectly, but we can swap the operands to fix both.
19885 std::swap(LHS, RHS);
19889 Opcode = X86ISD::FMAX;
19895 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19898 EVT CondVT = Cond.getValueType();
19899 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19900 CondVT.getVectorElementType() == MVT::i1) {
19901 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19902 // lowering on AVX-512. In this case we convert it to
19903 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19904 // The same situation for all 128 and 256-bit vectors of i8 and i16
19905 EVT OpVT = LHS.getValueType();
19906 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19907 (OpVT.getVectorElementType() == MVT::i8 ||
19908 OpVT.getVectorElementType() == MVT::i16)) {
19909 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19910 DCI.AddToWorklist(Cond.getNode());
19911 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19914 // If this is a select between two integer constants, try to do some
19916 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19917 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19918 // Don't do this for crazy integer types.
19919 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19920 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19921 // so that TrueC (the true value) is larger than FalseC.
19922 bool NeedsCondInvert = false;
19924 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19925 // Efficiently invertible.
19926 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19927 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19928 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19929 NeedsCondInvert = true;
19930 std::swap(TrueC, FalseC);
19933 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19934 if (FalseC->getAPIntValue() == 0 &&
19935 TrueC->getAPIntValue().isPowerOf2()) {
19936 if (NeedsCondInvert) // Invert the condition if needed.
19937 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19938 DAG.getConstant(1, Cond.getValueType()));
19940 // Zero extend the condition if needed.
19941 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19943 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19944 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19945 DAG.getConstant(ShAmt, MVT::i8));
19948 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19949 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19950 if (NeedsCondInvert) // Invert the condition if needed.
19951 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19952 DAG.getConstant(1, Cond.getValueType()));
19954 // Zero extend the condition if needed.
19955 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19956 FalseC->getValueType(0), Cond);
19957 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19958 SDValue(FalseC, 0));
19961 // Optimize cases that will turn into an LEA instruction. This requires
19962 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19963 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19964 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19965 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19967 bool isFastMultiplier = false;
19969 switch ((unsigned char)Diff) {
19971 case 1: // result = add base, cond
19972 case 2: // result = lea base( , cond*2)
19973 case 3: // result = lea base(cond, cond*2)
19974 case 4: // result = lea base( , cond*4)
19975 case 5: // result = lea base(cond, cond*4)
19976 case 8: // result = lea base( , cond*8)
19977 case 9: // result = lea base(cond, cond*8)
19978 isFastMultiplier = true;
19983 if (isFastMultiplier) {
19984 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19985 if (NeedsCondInvert) // Invert the condition if needed.
19986 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19987 DAG.getConstant(1, Cond.getValueType()));
19989 // Zero extend the condition if needed.
19990 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19992 // Scale the condition by the difference.
19994 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19995 DAG.getConstant(Diff, Cond.getValueType()));
19997 // Add the base if non-zero.
19998 if (FalseC->getAPIntValue() != 0)
19999 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20000 SDValue(FalseC, 0));
20007 // Canonicalize max and min:
20008 // (x > y) ? x : y -> (x >= y) ? x : y
20009 // (x < y) ? x : y -> (x <= y) ? x : y
20010 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20011 // the need for an extra compare
20012 // against zero. e.g.
20013 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20015 // testl %edi, %edi
20017 // cmovgl %edi, %eax
20021 // cmovsl %eax, %edi
20022 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20023 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20024 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20025 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20030 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20031 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20032 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20033 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20038 // Early exit check
20039 if (!TLI.isTypeLegal(VT))
20042 // Match VSELECTs into subs with unsigned saturation.
20043 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20044 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20045 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20046 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20047 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20049 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20050 // left side invert the predicate to simplify logic below.
20052 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20054 CC = ISD::getSetCCInverse(CC, true);
20055 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20059 if (Other.getNode() && Other->getNumOperands() == 2 &&
20060 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20061 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20062 SDValue CondRHS = Cond->getOperand(1);
20064 // Look for a general sub with unsigned saturation first.
20065 // x >= y ? x-y : 0 --> subus x, y
20066 // x > y ? x-y : 0 --> subus x, y
20067 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20068 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20069 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20071 // If the RHS is a constant we have to reverse the const canonicalization.
20072 // x > C-1 ? x+-C : 0 --> subus x, C
20073 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20074 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
20075 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20076 if (CondRHS.getConstantOperandVal(0) == -A-1)
20077 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
20078 DAG.getConstant(-A, VT));
20081 // Another special case: If C was a sign bit, the sub has been
20082 // canonicalized into a xor.
20083 // FIXME: Would it be better to use computeKnownBits to determine whether
20084 // it's safe to decanonicalize the xor?
20085 // x s< 0 ? x^C : 0 --> subus x, C
20086 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20087 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20088 isSplatVector(OpRHS.getNode())) {
20089 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20091 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20096 // Try to match a min/max vector operation.
20097 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20098 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20099 unsigned Opc = ret.first;
20100 bool NeedSplit = ret.second;
20102 if (Opc && NeedSplit) {
20103 unsigned NumElems = VT.getVectorNumElements();
20104 // Extract the LHS vectors
20105 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20106 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20108 // Extract the RHS vectors
20109 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20110 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20112 // Create min/max for each subvector
20113 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20114 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20116 // Merge the result
20117 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20119 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20122 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20123 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20124 // Check if SETCC has already been promoted
20125 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20126 // Check that condition value type matches vselect operand type
20129 assert(Cond.getValueType().isVector() &&
20130 "vector select expects a vector selector!");
20132 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20133 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20135 if (!TValIsAllOnes && !FValIsAllZeros) {
20136 // Try invert the condition if true value is not all 1s and false value
20138 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20139 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20141 if (TValIsAllZeros || FValIsAllOnes) {
20142 SDValue CC = Cond.getOperand(2);
20143 ISD::CondCode NewCC =
20144 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20145 Cond.getOperand(0).getValueType().isInteger());
20146 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20147 std::swap(LHS, RHS);
20148 TValIsAllOnes = FValIsAllOnes;
20149 FValIsAllZeros = TValIsAllZeros;
20153 if (TValIsAllOnes || FValIsAllZeros) {
20156 if (TValIsAllOnes && FValIsAllZeros)
20158 else if (TValIsAllOnes)
20159 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20160 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20161 else if (FValIsAllZeros)
20162 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20163 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20165 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20169 // Try to fold this VSELECT into a MOVSS/MOVSD
20170 if (N->getOpcode() == ISD::VSELECT &&
20171 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20172 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20173 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20174 bool CanFold = false;
20175 unsigned NumElems = Cond.getNumOperands();
20179 if (isZero(Cond.getOperand(0))) {
20182 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20183 // fold (vselect <0,-1> -> (movsd A, B)
20184 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20185 CanFold = isAllOnes(Cond.getOperand(i));
20186 } else if (isAllOnes(Cond.getOperand(0))) {
20190 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20191 // fold (vselect <-1,0> -> (movsd B, A)
20192 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20193 CanFold = isZero(Cond.getOperand(i));
20197 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20198 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20199 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20202 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20203 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20204 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20205 // (v2i64 (bitcast B)))))
20207 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20208 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20209 // (v2f64 (bitcast B)))))
20211 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20212 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20213 // (v2i64 (bitcast A)))))
20215 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20216 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20217 // (v2f64 (bitcast A)))))
20219 CanFold = (isZero(Cond.getOperand(0)) &&
20220 isZero(Cond.getOperand(1)) &&
20221 isAllOnes(Cond.getOperand(2)) &&
20222 isAllOnes(Cond.getOperand(3)));
20224 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20225 isAllOnes(Cond.getOperand(1)) &&
20226 isZero(Cond.getOperand(2)) &&
20227 isZero(Cond.getOperand(3))) {
20229 std::swap(LHS, RHS);
20233 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20234 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20235 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20236 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20238 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20244 // If we know that this node is legal then we know that it is going to be
20245 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20246 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20247 // to simplify previous instructions.
20248 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20249 !DCI.isBeforeLegalize() &&
20250 // We explicitly check against v8i16 and v16i16 because, although
20251 // they're marked as Custom, they might only be legal when Cond is a
20252 // build_vector of constants. This will be taken care in a later
20254 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20255 VT != MVT::v8i16)) {
20256 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20258 // Don't optimize vector selects that map to mask-registers.
20262 // Check all uses of that condition operand to check whether it will be
20263 // consumed by non-BLEND instructions, which may depend on all bits are set
20265 for (SDNode::use_iterator I = Cond->use_begin(),
20266 E = Cond->use_end(); I != E; ++I)
20267 if (I->getOpcode() != ISD::VSELECT)
20268 // TODO: Add other opcodes eventually lowered into BLEND.
20271 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20272 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20274 APInt KnownZero, KnownOne;
20275 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20276 DCI.isBeforeLegalizeOps());
20277 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20278 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20279 DCI.CommitTargetLoweringOpt(TLO);
20282 // We should generate an X86ISD::BLENDI from a vselect if its argument
20283 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20284 // constants. This specific pattern gets generated when we split a
20285 // selector for a 512 bit vector in a machine without AVX512 (but with
20286 // 256-bit vectors), during legalization:
20288 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20290 // Iff we find this pattern and the build_vectors are built from
20291 // constants, we translate the vselect into a shuffle_vector that we
20292 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20293 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20294 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20295 if (Shuffle.getNode())
20302 // Check whether a boolean test is testing a boolean value generated by
20303 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20306 // Simplify the following patterns:
20307 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20308 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20309 // to (Op EFLAGS Cond)
20311 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20312 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20313 // to (Op EFLAGS !Cond)
20315 // where Op could be BRCOND or CMOV.
20317 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20318 // Quit if not CMP and SUB with its value result used.
20319 if (Cmp.getOpcode() != X86ISD::CMP &&
20320 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20323 // Quit if not used as a boolean value.
20324 if (CC != X86::COND_E && CC != X86::COND_NE)
20327 // Check CMP operands. One of them should be 0 or 1 and the other should be
20328 // an SetCC or extended from it.
20329 SDValue Op1 = Cmp.getOperand(0);
20330 SDValue Op2 = Cmp.getOperand(1);
20333 const ConstantSDNode* C = nullptr;
20334 bool needOppositeCond = (CC == X86::COND_E);
20335 bool checkAgainstTrue = false; // Is it a comparison against 1?
20337 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20339 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20341 else // Quit if all operands are not constants.
20344 if (C->getZExtValue() == 1) {
20345 needOppositeCond = !needOppositeCond;
20346 checkAgainstTrue = true;
20347 } else if (C->getZExtValue() != 0)
20348 // Quit if the constant is neither 0 or 1.
20351 bool truncatedToBoolWithAnd = false;
20352 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20353 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20354 SetCC.getOpcode() == ISD::TRUNCATE ||
20355 SetCC.getOpcode() == ISD::AND) {
20356 if (SetCC.getOpcode() == ISD::AND) {
20358 ConstantSDNode *CS;
20359 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20360 CS->getZExtValue() == 1)
20362 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20363 CS->getZExtValue() == 1)
20367 SetCC = SetCC.getOperand(OpIdx);
20368 truncatedToBoolWithAnd = true;
20370 SetCC = SetCC.getOperand(0);
20373 switch (SetCC.getOpcode()) {
20374 case X86ISD::SETCC_CARRY:
20375 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20376 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20377 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20378 // truncated to i1 using 'and'.
20379 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20381 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20382 "Invalid use of SETCC_CARRY!");
20384 case X86ISD::SETCC:
20385 // Set the condition code or opposite one if necessary.
20386 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20387 if (needOppositeCond)
20388 CC = X86::GetOppositeBranchCondition(CC);
20389 return SetCC.getOperand(1);
20390 case X86ISD::CMOV: {
20391 // Check whether false/true value has canonical one, i.e. 0 or 1.
20392 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20393 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20394 // Quit if true value is not a constant.
20397 // Quit if false value is not a constant.
20399 SDValue Op = SetCC.getOperand(0);
20400 // Skip 'zext' or 'trunc' node.
20401 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20402 Op.getOpcode() == ISD::TRUNCATE)
20403 Op = Op.getOperand(0);
20404 // A special case for rdrand/rdseed, where 0 is set if false cond is
20406 if ((Op.getOpcode() != X86ISD::RDRAND &&
20407 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20410 // Quit if false value is not the constant 0 or 1.
20411 bool FValIsFalse = true;
20412 if (FVal && FVal->getZExtValue() != 0) {
20413 if (FVal->getZExtValue() != 1)
20415 // If FVal is 1, opposite cond is needed.
20416 needOppositeCond = !needOppositeCond;
20417 FValIsFalse = false;
20419 // Quit if TVal is not the constant opposite of FVal.
20420 if (FValIsFalse && TVal->getZExtValue() != 1)
20422 if (!FValIsFalse && TVal->getZExtValue() != 0)
20424 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20425 if (needOppositeCond)
20426 CC = X86::GetOppositeBranchCondition(CC);
20427 return SetCC.getOperand(3);
20434 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20435 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20436 TargetLowering::DAGCombinerInfo &DCI,
20437 const X86Subtarget *Subtarget) {
20440 // If the flag operand isn't dead, don't touch this CMOV.
20441 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20444 SDValue FalseOp = N->getOperand(0);
20445 SDValue TrueOp = N->getOperand(1);
20446 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20447 SDValue Cond = N->getOperand(3);
20449 if (CC == X86::COND_E || CC == X86::COND_NE) {
20450 switch (Cond.getOpcode()) {
20454 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20455 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20456 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20462 Flags = checkBoolTestSetCCCombine(Cond, CC);
20463 if (Flags.getNode() &&
20464 // Extra check as FCMOV only supports a subset of X86 cond.
20465 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20466 SDValue Ops[] = { FalseOp, TrueOp,
20467 DAG.getConstant(CC, MVT::i8), Flags };
20468 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20471 // If this is a select between two integer constants, try to do some
20472 // optimizations. Note that the operands are ordered the opposite of SELECT
20474 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20475 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20476 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20477 // larger than FalseC (the false value).
20478 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20479 CC = X86::GetOppositeBranchCondition(CC);
20480 std::swap(TrueC, FalseC);
20481 std::swap(TrueOp, FalseOp);
20484 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20485 // This is efficient for any integer data type (including i8/i16) and
20487 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20488 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20489 DAG.getConstant(CC, MVT::i8), Cond);
20491 // Zero extend the condition if needed.
20492 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20494 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20495 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20496 DAG.getConstant(ShAmt, MVT::i8));
20497 if (N->getNumValues() == 2) // Dead flag value?
20498 return DCI.CombineTo(N, Cond, SDValue());
20502 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20503 // for any integer data type, including i8/i16.
20504 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20505 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20506 DAG.getConstant(CC, MVT::i8), Cond);
20508 // Zero extend the condition if needed.
20509 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20510 FalseC->getValueType(0), Cond);
20511 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20512 SDValue(FalseC, 0));
20514 if (N->getNumValues() == 2) // Dead flag value?
20515 return DCI.CombineTo(N, Cond, SDValue());
20519 // Optimize cases that will turn into an LEA instruction. This requires
20520 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20521 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20522 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20523 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20525 bool isFastMultiplier = false;
20527 switch ((unsigned char)Diff) {
20529 case 1: // result = add base, cond
20530 case 2: // result = lea base( , cond*2)
20531 case 3: // result = lea base(cond, cond*2)
20532 case 4: // result = lea base( , cond*4)
20533 case 5: // result = lea base(cond, cond*4)
20534 case 8: // result = lea base( , cond*8)
20535 case 9: // result = lea base(cond, cond*8)
20536 isFastMultiplier = true;
20541 if (isFastMultiplier) {
20542 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20543 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20544 DAG.getConstant(CC, MVT::i8), Cond);
20545 // Zero extend the condition if needed.
20546 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20548 // Scale the condition by the difference.
20550 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20551 DAG.getConstant(Diff, Cond.getValueType()));
20553 // Add the base if non-zero.
20554 if (FalseC->getAPIntValue() != 0)
20555 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20556 SDValue(FalseC, 0));
20557 if (N->getNumValues() == 2) // Dead flag value?
20558 return DCI.CombineTo(N, Cond, SDValue());
20565 // Handle these cases:
20566 // (select (x != c), e, c) -> select (x != c), e, x),
20567 // (select (x == c), c, e) -> select (x == c), x, e)
20568 // where the c is an integer constant, and the "select" is the combination
20569 // of CMOV and CMP.
20571 // The rationale for this change is that the conditional-move from a constant
20572 // needs two instructions, however, conditional-move from a register needs
20573 // only one instruction.
20575 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20576 // some instruction-combining opportunities. This opt needs to be
20577 // postponed as late as possible.
20579 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20580 // the DCI.xxxx conditions are provided to postpone the optimization as
20581 // late as possible.
20583 ConstantSDNode *CmpAgainst = nullptr;
20584 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20585 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20586 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20588 if (CC == X86::COND_NE &&
20589 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20590 CC = X86::GetOppositeBranchCondition(CC);
20591 std::swap(TrueOp, FalseOp);
20594 if (CC == X86::COND_E &&
20595 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20596 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20597 DAG.getConstant(CC, MVT::i8), Cond };
20598 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20606 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20607 const X86Subtarget *Subtarget) {
20608 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20610 default: return SDValue();
20611 // SSE/AVX/AVX2 blend intrinsics.
20612 case Intrinsic::x86_avx2_pblendvb:
20613 case Intrinsic::x86_avx2_pblendw:
20614 case Intrinsic::x86_avx2_pblendd_128:
20615 case Intrinsic::x86_avx2_pblendd_256:
20616 // Don't try to simplify this intrinsic if we don't have AVX2.
20617 if (!Subtarget->hasAVX2())
20620 case Intrinsic::x86_avx_blend_pd_256:
20621 case Intrinsic::x86_avx_blend_ps_256:
20622 case Intrinsic::x86_avx_blendv_pd_256:
20623 case Intrinsic::x86_avx_blendv_ps_256:
20624 // Don't try to simplify this intrinsic if we don't have AVX.
20625 if (!Subtarget->hasAVX())
20628 case Intrinsic::x86_sse41_pblendw:
20629 case Intrinsic::x86_sse41_blendpd:
20630 case Intrinsic::x86_sse41_blendps:
20631 case Intrinsic::x86_sse41_blendvps:
20632 case Intrinsic::x86_sse41_blendvpd:
20633 case Intrinsic::x86_sse41_pblendvb: {
20634 SDValue Op0 = N->getOperand(1);
20635 SDValue Op1 = N->getOperand(2);
20636 SDValue Mask = N->getOperand(3);
20638 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20639 if (!Subtarget->hasSSE41())
20642 // fold (blend A, A, Mask) -> A
20645 // fold (blend A, B, allZeros) -> A
20646 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20648 // fold (blend A, B, allOnes) -> B
20649 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20652 // Simplify the case where the mask is a constant i32 value.
20653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20654 if (C->isNullValue())
20656 if (C->isAllOnesValue())
20663 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20664 case Intrinsic::x86_sse2_psrai_w:
20665 case Intrinsic::x86_sse2_psrai_d:
20666 case Intrinsic::x86_avx2_psrai_w:
20667 case Intrinsic::x86_avx2_psrai_d:
20668 case Intrinsic::x86_sse2_psra_w:
20669 case Intrinsic::x86_sse2_psra_d:
20670 case Intrinsic::x86_avx2_psra_w:
20671 case Intrinsic::x86_avx2_psra_d: {
20672 SDValue Op0 = N->getOperand(1);
20673 SDValue Op1 = N->getOperand(2);
20674 EVT VT = Op0.getValueType();
20675 assert(VT.isVector() && "Expected a vector type!");
20677 if (isa<BuildVectorSDNode>(Op1))
20678 Op1 = Op1.getOperand(0);
20680 if (!isa<ConstantSDNode>(Op1))
20683 EVT SVT = VT.getVectorElementType();
20684 unsigned SVTBits = SVT.getSizeInBits();
20686 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20687 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20688 uint64_t ShAmt = C.getZExtValue();
20690 // Don't try to convert this shift into a ISD::SRA if the shift
20691 // count is bigger than or equal to the element size.
20692 if (ShAmt >= SVTBits)
20695 // Trivial case: if the shift count is zero, then fold this
20696 // into the first operand.
20700 // Replace this packed shift intrinsic with a target independent
20702 SDValue Splat = DAG.getConstant(C, VT);
20703 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20708 /// PerformMulCombine - Optimize a single multiply with constant into two
20709 /// in order to implement it with two cheaper instructions, e.g.
20710 /// LEA + SHL, LEA + LEA.
20711 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20712 TargetLowering::DAGCombinerInfo &DCI) {
20713 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20716 EVT VT = N->getValueType(0);
20717 if (VT != MVT::i64)
20720 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20723 uint64_t MulAmt = C->getZExtValue();
20724 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20727 uint64_t MulAmt1 = 0;
20728 uint64_t MulAmt2 = 0;
20729 if ((MulAmt % 9) == 0) {
20731 MulAmt2 = MulAmt / 9;
20732 } else if ((MulAmt % 5) == 0) {
20734 MulAmt2 = MulAmt / 5;
20735 } else if ((MulAmt % 3) == 0) {
20737 MulAmt2 = MulAmt / 3;
20740 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20743 if (isPowerOf2_64(MulAmt2) &&
20744 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20745 // If second multiplifer is pow2, issue it first. We want the multiply by
20746 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20748 std::swap(MulAmt1, MulAmt2);
20751 if (isPowerOf2_64(MulAmt1))
20752 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20753 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20755 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20756 DAG.getConstant(MulAmt1, VT));
20758 if (isPowerOf2_64(MulAmt2))
20759 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20760 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20762 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20763 DAG.getConstant(MulAmt2, VT));
20765 // Do not add new nodes to DAG combiner worklist.
20766 DCI.CombineTo(N, NewMul, false);
20771 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20772 SDValue N0 = N->getOperand(0);
20773 SDValue N1 = N->getOperand(1);
20774 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20775 EVT VT = N0.getValueType();
20777 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20778 // since the result of setcc_c is all zero's or all ones.
20779 if (VT.isInteger() && !VT.isVector() &&
20780 N1C && N0.getOpcode() == ISD::AND &&
20781 N0.getOperand(1).getOpcode() == ISD::Constant) {
20782 SDValue N00 = N0.getOperand(0);
20783 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20784 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20785 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20786 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20787 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20788 APInt ShAmt = N1C->getAPIntValue();
20789 Mask = Mask.shl(ShAmt);
20791 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20792 N00, DAG.getConstant(Mask, VT));
20796 // Hardware support for vector shifts is sparse which makes us scalarize the
20797 // vector operations in many cases. Also, on sandybridge ADD is faster than
20799 // (shl V, 1) -> add V,V
20800 if (isSplatVector(N1.getNode())) {
20801 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20802 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20803 // We shift all of the values by one. In many cases we do not have
20804 // hardware support for this operation. This is better expressed as an ADD
20806 if (N1C && (1 == N1C->getZExtValue())) {
20807 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20814 /// \brief Returns a vector of 0s if the node in input is a vector logical
20815 /// shift by a constant amount which is known to be bigger than or equal
20816 /// to the vector element size in bits.
20817 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20818 const X86Subtarget *Subtarget) {
20819 EVT VT = N->getValueType(0);
20821 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20822 (!Subtarget->hasInt256() ||
20823 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20826 SDValue Amt = N->getOperand(1);
20828 if (isSplatVector(Amt.getNode())) {
20829 SDValue SclrAmt = Amt->getOperand(0);
20830 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20831 APInt ShiftAmt = C->getAPIntValue();
20832 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20834 // SSE2/AVX2 logical shifts always return a vector of 0s
20835 // if the shift amount is bigger than or equal to
20836 // the element size. The constant shift amount will be
20837 // encoded as a 8-bit immediate.
20838 if (ShiftAmt.trunc(8).uge(MaxAmount))
20839 return getZeroVector(VT, Subtarget, DAG, DL);
20846 /// PerformShiftCombine - Combine shifts.
20847 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20848 TargetLowering::DAGCombinerInfo &DCI,
20849 const X86Subtarget *Subtarget) {
20850 if (N->getOpcode() == ISD::SHL) {
20851 SDValue V = PerformSHLCombine(N, DAG);
20852 if (V.getNode()) return V;
20855 if (N->getOpcode() != ISD::SRA) {
20856 // Try to fold this logical shift into a zero vector.
20857 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20858 if (V.getNode()) return V;
20864 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20865 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20866 // and friends. Likewise for OR -> CMPNEQSS.
20867 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20868 TargetLowering::DAGCombinerInfo &DCI,
20869 const X86Subtarget *Subtarget) {
20872 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20873 // we're requiring SSE2 for both.
20874 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20875 SDValue N0 = N->getOperand(0);
20876 SDValue N1 = N->getOperand(1);
20877 SDValue CMP0 = N0->getOperand(1);
20878 SDValue CMP1 = N1->getOperand(1);
20881 // The SETCCs should both refer to the same CMP.
20882 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20885 SDValue CMP00 = CMP0->getOperand(0);
20886 SDValue CMP01 = CMP0->getOperand(1);
20887 EVT VT = CMP00.getValueType();
20889 if (VT == MVT::f32 || VT == MVT::f64) {
20890 bool ExpectingFlags = false;
20891 // Check for any users that want flags:
20892 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20893 !ExpectingFlags && UI != UE; ++UI)
20894 switch (UI->getOpcode()) {
20899 ExpectingFlags = true;
20901 case ISD::CopyToReg:
20902 case ISD::SIGN_EXTEND:
20903 case ISD::ZERO_EXTEND:
20904 case ISD::ANY_EXTEND:
20908 if (!ExpectingFlags) {
20909 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20910 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20912 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20913 X86::CondCode tmp = cc0;
20918 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20919 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20920 // FIXME: need symbolic constants for these magic numbers.
20921 // See X86ATTInstPrinter.cpp:printSSECC().
20922 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20923 if (Subtarget->hasAVX512()) {
20924 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20925 CMP01, DAG.getConstant(x86cc, MVT::i8));
20926 if (N->getValueType(0) != MVT::i1)
20927 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20931 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20932 CMP00.getValueType(), CMP00, CMP01,
20933 DAG.getConstant(x86cc, MVT::i8));
20935 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20936 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20938 if (is64BitFP && !Subtarget->is64Bit()) {
20939 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20940 // 64-bit integer, since that's not a legal type. Since
20941 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20942 // bits, but can do this little dance to extract the lowest 32 bits
20943 // and work with those going forward.
20944 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20946 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20948 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20949 Vector32, DAG.getIntPtrConstant(0));
20953 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20954 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20955 DAG.getConstant(1, IntVT));
20956 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20957 return OneBitOfTruth;
20965 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20966 /// so it can be folded inside ANDNP.
20967 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20968 EVT VT = N->getValueType(0);
20970 // Match direct AllOnes for 128 and 256-bit vectors
20971 if (ISD::isBuildVectorAllOnes(N))
20974 // Look through a bit convert.
20975 if (N->getOpcode() == ISD::BITCAST)
20976 N = N->getOperand(0).getNode();
20978 // Sometimes the operand may come from a insert_subvector building a 256-bit
20980 if (VT.is256BitVector() &&
20981 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20982 SDValue V1 = N->getOperand(0);
20983 SDValue V2 = N->getOperand(1);
20985 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20986 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20987 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20988 ISD::isBuildVectorAllOnes(V2.getNode()))
20995 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20996 // register. In most cases we actually compare or select YMM-sized registers
20997 // and mixing the two types creates horrible code. This method optimizes
20998 // some of the transition sequences.
20999 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21000 TargetLowering::DAGCombinerInfo &DCI,
21001 const X86Subtarget *Subtarget) {
21002 EVT VT = N->getValueType(0);
21003 if (!VT.is256BitVector())
21006 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21007 N->getOpcode() == ISD::ZERO_EXTEND ||
21008 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21010 SDValue Narrow = N->getOperand(0);
21011 EVT NarrowVT = Narrow->getValueType(0);
21012 if (!NarrowVT.is128BitVector())
21015 if (Narrow->getOpcode() != ISD::XOR &&
21016 Narrow->getOpcode() != ISD::AND &&
21017 Narrow->getOpcode() != ISD::OR)
21020 SDValue N0 = Narrow->getOperand(0);
21021 SDValue N1 = Narrow->getOperand(1);
21024 // The Left side has to be a trunc.
21025 if (N0.getOpcode() != ISD::TRUNCATE)
21028 // The type of the truncated inputs.
21029 EVT WideVT = N0->getOperand(0)->getValueType(0);
21033 // The right side has to be a 'trunc' or a constant vector.
21034 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21035 bool RHSConst = (isSplatVector(N1.getNode()) &&
21036 isa<ConstantSDNode>(N1->getOperand(0)));
21037 if (!RHSTrunc && !RHSConst)
21040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21042 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21045 // Set N0 and N1 to hold the inputs to the new wide operation.
21046 N0 = N0->getOperand(0);
21048 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21049 N1->getOperand(0));
21050 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21051 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21052 } else if (RHSTrunc) {
21053 N1 = N1->getOperand(0);
21056 // Generate the wide operation.
21057 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21058 unsigned Opcode = N->getOpcode();
21060 case ISD::ANY_EXTEND:
21062 case ISD::ZERO_EXTEND: {
21063 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21064 APInt Mask = APInt::getAllOnesValue(InBits);
21065 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21066 return DAG.getNode(ISD::AND, DL, VT,
21067 Op, DAG.getConstant(Mask, VT));
21069 case ISD::SIGN_EXTEND:
21070 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21071 Op, DAG.getValueType(NarrowVT));
21073 llvm_unreachable("Unexpected opcode");
21077 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21078 TargetLowering::DAGCombinerInfo &DCI,
21079 const X86Subtarget *Subtarget) {
21080 EVT VT = N->getValueType(0);
21081 if (DCI.isBeforeLegalizeOps())
21084 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21088 // Create BEXTR instructions
21089 // BEXTR is ((X >> imm) & (2**size-1))
21090 if (VT == MVT::i32 || VT == MVT::i64) {
21091 SDValue N0 = N->getOperand(0);
21092 SDValue N1 = N->getOperand(1);
21095 // Check for BEXTR.
21096 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21097 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21098 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21099 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21100 if (MaskNode && ShiftNode) {
21101 uint64_t Mask = MaskNode->getZExtValue();
21102 uint64_t Shift = ShiftNode->getZExtValue();
21103 if (isMask_64(Mask)) {
21104 uint64_t MaskSize = CountPopulation_64(Mask);
21105 if (Shift + MaskSize <= VT.getSizeInBits())
21106 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21107 DAG.getConstant(Shift | (MaskSize << 8), VT));
21115 // Want to form ANDNP nodes:
21116 // 1) In the hopes of then easily combining them with OR and AND nodes
21117 // to form PBLEND/PSIGN.
21118 // 2) To match ANDN packed intrinsics
21119 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21122 SDValue N0 = N->getOperand(0);
21123 SDValue N1 = N->getOperand(1);
21126 // Check LHS for vnot
21127 if (N0.getOpcode() == ISD::XOR &&
21128 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21129 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21130 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21132 // Check RHS for vnot
21133 if (N1.getOpcode() == ISD::XOR &&
21134 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21135 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21136 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21141 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21142 TargetLowering::DAGCombinerInfo &DCI,
21143 const X86Subtarget *Subtarget) {
21144 if (DCI.isBeforeLegalizeOps())
21147 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21151 SDValue N0 = N->getOperand(0);
21152 SDValue N1 = N->getOperand(1);
21153 EVT VT = N->getValueType(0);
21155 // look for psign/blend
21156 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21157 if (!Subtarget->hasSSSE3() ||
21158 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21161 // Canonicalize pandn to RHS
21162 if (N0.getOpcode() == X86ISD::ANDNP)
21164 // or (and (m, y), (pandn m, x))
21165 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21166 SDValue Mask = N1.getOperand(0);
21167 SDValue X = N1.getOperand(1);
21169 if (N0.getOperand(0) == Mask)
21170 Y = N0.getOperand(1);
21171 if (N0.getOperand(1) == Mask)
21172 Y = N0.getOperand(0);
21174 // Check to see if the mask appeared in both the AND and ANDNP and
21178 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21179 // Look through mask bitcast.
21180 if (Mask.getOpcode() == ISD::BITCAST)
21181 Mask = Mask.getOperand(0);
21182 if (X.getOpcode() == ISD::BITCAST)
21183 X = X.getOperand(0);
21184 if (Y.getOpcode() == ISD::BITCAST)
21185 Y = Y.getOperand(0);
21187 EVT MaskVT = Mask.getValueType();
21189 // Validate that the Mask operand is a vector sra node.
21190 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21191 // there is no psrai.b
21192 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21193 unsigned SraAmt = ~0;
21194 if (Mask.getOpcode() == ISD::SRA) {
21195 SDValue Amt = Mask.getOperand(1);
21196 if (isSplatVector(Amt.getNode())) {
21197 SDValue SclrAmt = Amt->getOperand(0);
21198 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
21199 SraAmt = C->getZExtValue();
21201 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21202 SDValue SraC = Mask.getOperand(1);
21203 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21205 if ((SraAmt + 1) != EltBits)
21210 // Now we know we at least have a plendvb with the mask val. See if
21211 // we can form a psignb/w/d.
21212 // psign = x.type == y.type == mask.type && y = sub(0, x);
21213 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21214 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21215 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21216 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21217 "Unsupported VT for PSIGN");
21218 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21219 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21221 // PBLENDVB only available on SSE 4.1
21222 if (!Subtarget->hasSSE41())
21225 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21227 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21228 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21229 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21230 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21231 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21235 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21238 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21239 MachineFunction &MF = DAG.getMachineFunction();
21240 bool OptForSize = MF.getFunction()->getAttributes().
21241 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21243 // SHLD/SHRD instructions have lower register pressure, but on some
21244 // platforms they have higher latency than the equivalent
21245 // series of shifts/or that would otherwise be generated.
21246 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21247 // have higher latencies and we are not optimizing for size.
21248 if (!OptForSize && Subtarget->isSHLDSlow())
21251 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21253 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21255 if (!N0.hasOneUse() || !N1.hasOneUse())
21258 SDValue ShAmt0 = N0.getOperand(1);
21259 if (ShAmt0.getValueType() != MVT::i8)
21261 SDValue ShAmt1 = N1.getOperand(1);
21262 if (ShAmt1.getValueType() != MVT::i8)
21264 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21265 ShAmt0 = ShAmt0.getOperand(0);
21266 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21267 ShAmt1 = ShAmt1.getOperand(0);
21270 unsigned Opc = X86ISD::SHLD;
21271 SDValue Op0 = N0.getOperand(0);
21272 SDValue Op1 = N1.getOperand(0);
21273 if (ShAmt0.getOpcode() == ISD::SUB) {
21274 Opc = X86ISD::SHRD;
21275 std::swap(Op0, Op1);
21276 std::swap(ShAmt0, ShAmt1);
21279 unsigned Bits = VT.getSizeInBits();
21280 if (ShAmt1.getOpcode() == ISD::SUB) {
21281 SDValue Sum = ShAmt1.getOperand(0);
21282 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21283 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21284 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21285 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21286 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21287 return DAG.getNode(Opc, DL, VT,
21289 DAG.getNode(ISD::TRUNCATE, DL,
21292 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21293 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21295 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21296 return DAG.getNode(Opc, DL, VT,
21297 N0.getOperand(0), N1.getOperand(0),
21298 DAG.getNode(ISD::TRUNCATE, DL,
21305 // Generate NEG and CMOV for integer abs.
21306 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21307 EVT VT = N->getValueType(0);
21309 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21310 // 8-bit integer abs to NEG and CMOV.
21311 if (VT.isInteger() && VT.getSizeInBits() == 8)
21314 SDValue N0 = N->getOperand(0);
21315 SDValue N1 = N->getOperand(1);
21318 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21319 // and change it to SUB and CMOV.
21320 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21321 N0.getOpcode() == ISD::ADD &&
21322 N0.getOperand(1) == N1 &&
21323 N1.getOpcode() == ISD::SRA &&
21324 N1.getOperand(0) == N0.getOperand(0))
21325 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21326 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21327 // Generate SUB & CMOV.
21328 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21329 DAG.getConstant(0, VT), N0.getOperand(0));
21331 SDValue Ops[] = { N0.getOperand(0), Neg,
21332 DAG.getConstant(X86::COND_GE, MVT::i8),
21333 SDValue(Neg.getNode(), 1) };
21334 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21339 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21340 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21341 TargetLowering::DAGCombinerInfo &DCI,
21342 const X86Subtarget *Subtarget) {
21343 if (DCI.isBeforeLegalizeOps())
21346 if (Subtarget->hasCMov()) {
21347 SDValue RV = performIntegerAbsCombine(N, DAG);
21355 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21356 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21357 TargetLowering::DAGCombinerInfo &DCI,
21358 const X86Subtarget *Subtarget) {
21359 LoadSDNode *Ld = cast<LoadSDNode>(N);
21360 EVT RegVT = Ld->getValueType(0);
21361 EVT MemVT = Ld->getMemoryVT();
21363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21364 unsigned RegSz = RegVT.getSizeInBits();
21366 // On Sandybridge unaligned 256bit loads are inefficient.
21367 ISD::LoadExtType Ext = Ld->getExtensionType();
21368 unsigned Alignment = Ld->getAlignment();
21369 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21370 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21371 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21372 unsigned NumElems = RegVT.getVectorNumElements();
21376 SDValue Ptr = Ld->getBasePtr();
21377 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21379 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21381 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21382 Ld->getPointerInfo(), Ld->isVolatile(),
21383 Ld->isNonTemporal(), Ld->isInvariant(),
21385 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21386 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21387 Ld->getPointerInfo(), Ld->isVolatile(),
21388 Ld->isNonTemporal(), Ld->isInvariant(),
21389 std::min(16U, Alignment));
21390 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21392 Load2.getValue(1));
21394 SDValue NewVec = DAG.getUNDEF(RegVT);
21395 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21396 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21397 return DCI.CombineTo(N, NewVec, TF, true);
21400 // If this is a vector EXT Load then attempt to optimize it using a
21401 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
21402 // expansion is still better than scalar code.
21403 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
21404 // emit a shuffle and a arithmetic shift.
21405 // TODO: It is possible to support ZExt by zeroing the undef values
21406 // during the shuffle phase or after the shuffle.
21407 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
21408 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
21409 assert(MemVT != RegVT && "Cannot extend to the same type");
21410 assert(MemVT.isVector() && "Must load a vector from memory");
21412 unsigned NumElems = RegVT.getVectorNumElements();
21413 unsigned MemSz = MemVT.getSizeInBits();
21414 assert(RegSz > MemSz && "Register size must be greater than the mem size");
21416 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
21419 // All sizes must be a power of two.
21420 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
21423 // Attempt to load the original value using scalar loads.
21424 // Find the largest scalar type that divides the total loaded size.
21425 MVT SclrLoadTy = MVT::i8;
21426 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21427 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21428 MVT Tp = (MVT::SimpleValueType)tp;
21429 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
21434 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21435 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
21437 SclrLoadTy = MVT::f64;
21439 // Calculate the number of scalar loads that we need to perform
21440 // in order to load our vector from memory.
21441 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
21442 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
21445 unsigned loadRegZize = RegSz;
21446 if (Ext == ISD::SEXTLOAD && RegSz == 256)
21449 // Represent our vector as a sequence of elements which are the
21450 // largest scalar that we can load.
21451 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
21452 loadRegZize/SclrLoadTy.getSizeInBits());
21454 // Represent the data using the same element type that is stored in
21455 // memory. In practice, we ''widen'' MemVT.
21457 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21458 loadRegZize/MemVT.getScalarType().getSizeInBits());
21460 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
21461 "Invalid vector type");
21463 // We can't shuffle using an illegal type.
21464 if (!TLI.isTypeLegal(WideVecVT))
21467 SmallVector<SDValue, 8> Chains;
21468 SDValue Ptr = Ld->getBasePtr();
21469 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
21470 TLI.getPointerTy());
21471 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
21473 for (unsigned i = 0; i < NumLoads; ++i) {
21474 // Perform a single load.
21475 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
21476 Ptr, Ld->getPointerInfo(),
21477 Ld->isVolatile(), Ld->isNonTemporal(),
21478 Ld->isInvariant(), Ld->getAlignment());
21479 Chains.push_back(ScalarLoad.getValue(1));
21480 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
21481 // another round of DAGCombining.
21483 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
21485 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
21486 ScalarLoad, DAG.getIntPtrConstant(i));
21488 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21491 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21493 // Bitcast the loaded value to a vector of the original element type, in
21494 // the size of the target vector type.
21495 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
21496 unsigned SizeRatio = RegSz/MemSz;
21498 if (Ext == ISD::SEXTLOAD) {
21499 // If we have SSE4.1 we can directly emit a VSEXT node.
21500 if (Subtarget->hasSSE41()) {
21501 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
21502 return DCI.CombineTo(N, Sext, TF, true);
21505 // Otherwise we'll shuffle the small elements in the high bits of the
21506 // larger type and perform an arithmetic shift. If the shift is not legal
21507 // it's better to scalarize.
21508 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
21511 // Redistribute the loaded elements into the different locations.
21512 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21513 for (unsigned i = 0; i != NumElems; ++i)
21514 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
21516 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21517 DAG.getUNDEF(WideVecVT),
21520 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21522 // Build the arithmetic shift.
21523 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21524 MemVT.getVectorElementType().getSizeInBits();
21525 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21526 DAG.getConstant(Amt, RegVT));
21528 return DCI.CombineTo(N, Shuff, TF, true);
21531 // Redistribute the loaded elements into the different locations.
21532 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21533 for (unsigned i = 0; i != NumElems; ++i)
21534 ShuffleVec[i*SizeRatio] = i;
21536 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21537 DAG.getUNDEF(WideVecVT),
21540 // Bitcast to the requested type.
21541 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21542 // Replace the original load with the new sequence
21543 // and return the new chain.
21544 return DCI.CombineTo(N, Shuff, TF, true);
21550 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21551 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21552 const X86Subtarget *Subtarget) {
21553 StoreSDNode *St = cast<StoreSDNode>(N);
21554 EVT VT = St->getValue().getValueType();
21555 EVT StVT = St->getMemoryVT();
21557 SDValue StoredVal = St->getOperand(1);
21558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21560 // If we are saving a concatenation of two XMM registers, perform two stores.
21561 // On Sandy Bridge, 256-bit memory operations are executed by two
21562 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21563 // memory operation.
21564 unsigned Alignment = St->getAlignment();
21565 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21566 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21567 StVT == VT && !IsAligned) {
21568 unsigned NumElems = VT.getVectorNumElements();
21572 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21573 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21575 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21576 SDValue Ptr0 = St->getBasePtr();
21577 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21579 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21580 St->getPointerInfo(), St->isVolatile(),
21581 St->isNonTemporal(), Alignment);
21582 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21583 St->getPointerInfo(), St->isVolatile(),
21584 St->isNonTemporal(),
21585 std::min(16U, Alignment));
21586 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21589 // Optimize trunc store (of multiple scalars) to shuffle and store.
21590 // First, pack all of the elements in one place. Next, store to memory
21591 // in fewer chunks.
21592 if (St->isTruncatingStore() && VT.isVector()) {
21593 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21594 unsigned NumElems = VT.getVectorNumElements();
21595 assert(StVT != VT && "Cannot truncate to the same type");
21596 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21597 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21599 // From, To sizes and ElemCount must be pow of two
21600 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21601 // We are going to use the original vector elt for storing.
21602 // Accumulated smaller vector elements must be a multiple of the store size.
21603 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21605 unsigned SizeRatio = FromSz / ToSz;
21607 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21609 // Create a type on which we perform the shuffle
21610 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21611 StVT.getScalarType(), NumElems*SizeRatio);
21613 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21615 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21616 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21617 for (unsigned i = 0; i != NumElems; ++i)
21618 ShuffleVec[i] = i * SizeRatio;
21620 // Can't shuffle using an illegal type.
21621 if (!TLI.isTypeLegal(WideVecVT))
21624 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21625 DAG.getUNDEF(WideVecVT),
21627 // At this point all of the data is stored at the bottom of the
21628 // register. We now need to save it to mem.
21630 // Find the largest store unit
21631 MVT StoreType = MVT::i8;
21632 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21633 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21634 MVT Tp = (MVT::SimpleValueType)tp;
21635 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21639 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21640 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21641 (64 <= NumElems * ToSz))
21642 StoreType = MVT::f64;
21644 // Bitcast the original vector into a vector of store-size units
21645 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21646 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21647 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21648 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21649 SmallVector<SDValue, 8> Chains;
21650 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21651 TLI.getPointerTy());
21652 SDValue Ptr = St->getBasePtr();
21654 // Perform one or more big stores into memory.
21655 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21656 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21657 StoreType, ShuffWide,
21658 DAG.getIntPtrConstant(i));
21659 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21660 St->getPointerInfo(), St->isVolatile(),
21661 St->isNonTemporal(), St->getAlignment());
21662 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21663 Chains.push_back(Ch);
21666 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21669 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21670 // the FP state in cases where an emms may be missing.
21671 // A preferable solution to the general problem is to figure out the right
21672 // places to insert EMMS. This qualifies as a quick hack.
21674 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21675 if (VT.getSizeInBits() != 64)
21678 const Function *F = DAG.getMachineFunction().getFunction();
21679 bool NoImplicitFloatOps = F->getAttributes().
21680 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21681 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21682 && Subtarget->hasSSE2();
21683 if ((VT.isVector() ||
21684 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21685 isa<LoadSDNode>(St->getValue()) &&
21686 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21687 St->getChain().hasOneUse() && !St->isVolatile()) {
21688 SDNode* LdVal = St->getValue().getNode();
21689 LoadSDNode *Ld = nullptr;
21690 int TokenFactorIndex = -1;
21691 SmallVector<SDValue, 8> Ops;
21692 SDNode* ChainVal = St->getChain().getNode();
21693 // Must be a store of a load. We currently handle two cases: the load
21694 // is a direct child, and it's under an intervening TokenFactor. It is
21695 // possible to dig deeper under nested TokenFactors.
21696 if (ChainVal == LdVal)
21697 Ld = cast<LoadSDNode>(St->getChain());
21698 else if (St->getValue().hasOneUse() &&
21699 ChainVal->getOpcode() == ISD::TokenFactor) {
21700 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21701 if (ChainVal->getOperand(i).getNode() == LdVal) {
21702 TokenFactorIndex = i;
21703 Ld = cast<LoadSDNode>(St->getValue());
21705 Ops.push_back(ChainVal->getOperand(i));
21709 if (!Ld || !ISD::isNormalLoad(Ld))
21712 // If this is not the MMX case, i.e. we are just turning i64 load/store
21713 // into f64 load/store, avoid the transformation if there are multiple
21714 // uses of the loaded value.
21715 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21720 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21721 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21723 if (Subtarget->is64Bit() || F64IsLegal) {
21724 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21725 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21726 Ld->getPointerInfo(), Ld->isVolatile(),
21727 Ld->isNonTemporal(), Ld->isInvariant(),
21728 Ld->getAlignment());
21729 SDValue NewChain = NewLd.getValue(1);
21730 if (TokenFactorIndex != -1) {
21731 Ops.push_back(NewChain);
21732 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21734 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21735 St->getPointerInfo(),
21736 St->isVolatile(), St->isNonTemporal(),
21737 St->getAlignment());
21740 // Otherwise, lower to two pairs of 32-bit loads / stores.
21741 SDValue LoAddr = Ld->getBasePtr();
21742 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21743 DAG.getConstant(4, MVT::i32));
21745 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21746 Ld->getPointerInfo(),
21747 Ld->isVolatile(), Ld->isNonTemporal(),
21748 Ld->isInvariant(), Ld->getAlignment());
21749 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21750 Ld->getPointerInfo().getWithOffset(4),
21751 Ld->isVolatile(), Ld->isNonTemporal(),
21753 MinAlign(Ld->getAlignment(), 4));
21755 SDValue NewChain = LoLd.getValue(1);
21756 if (TokenFactorIndex != -1) {
21757 Ops.push_back(LoLd);
21758 Ops.push_back(HiLd);
21759 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21762 LoAddr = St->getBasePtr();
21763 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21764 DAG.getConstant(4, MVT::i32));
21766 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21767 St->getPointerInfo(),
21768 St->isVolatile(), St->isNonTemporal(),
21769 St->getAlignment());
21770 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21771 St->getPointerInfo().getWithOffset(4),
21773 St->isNonTemporal(),
21774 MinAlign(St->getAlignment(), 4));
21775 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21780 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21781 /// and return the operands for the horizontal operation in LHS and RHS. A
21782 /// horizontal operation performs the binary operation on successive elements
21783 /// of its first operand, then on successive elements of its second operand,
21784 /// returning the resulting values in a vector. For example, if
21785 /// A = < float a0, float a1, float a2, float a3 >
21787 /// B = < float b0, float b1, float b2, float b3 >
21788 /// then the result of doing a horizontal operation on A and B is
21789 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21790 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21791 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21792 /// set to A, RHS to B, and the routine returns 'true'.
21793 /// Note that the binary operation should have the property that if one of the
21794 /// operands is UNDEF then the result is UNDEF.
21795 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21796 // Look for the following pattern: if
21797 // A = < float a0, float a1, float a2, float a3 >
21798 // B = < float b0, float b1, float b2, float b3 >
21800 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21801 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21802 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21803 // which is A horizontal-op B.
21805 // At least one of the operands should be a vector shuffle.
21806 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21807 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21810 MVT VT = LHS.getSimpleValueType();
21812 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21813 "Unsupported vector type for horizontal add/sub");
21815 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21816 // operate independently on 128-bit lanes.
21817 unsigned NumElts = VT.getVectorNumElements();
21818 unsigned NumLanes = VT.getSizeInBits()/128;
21819 unsigned NumLaneElts = NumElts / NumLanes;
21820 assert((NumLaneElts % 2 == 0) &&
21821 "Vector type should have an even number of elements in each lane");
21822 unsigned HalfLaneElts = NumLaneElts/2;
21824 // View LHS in the form
21825 // LHS = VECTOR_SHUFFLE A, B, LMask
21826 // If LHS is not a shuffle then pretend it is the shuffle
21827 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21828 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21831 SmallVector<int, 16> LMask(NumElts);
21832 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21833 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21834 A = LHS.getOperand(0);
21835 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21836 B = LHS.getOperand(1);
21837 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21838 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21840 if (LHS.getOpcode() != ISD::UNDEF)
21842 for (unsigned i = 0; i != NumElts; ++i)
21846 // Likewise, view RHS in the form
21847 // RHS = VECTOR_SHUFFLE C, D, RMask
21849 SmallVector<int, 16> RMask(NumElts);
21850 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21851 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21852 C = RHS.getOperand(0);
21853 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21854 D = RHS.getOperand(1);
21855 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21856 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21858 if (RHS.getOpcode() != ISD::UNDEF)
21860 for (unsigned i = 0; i != NumElts; ++i)
21864 // Check that the shuffles are both shuffling the same vectors.
21865 if (!(A == C && B == D) && !(A == D && B == C))
21868 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21869 if (!A.getNode() && !B.getNode())
21872 // If A and B occur in reverse order in RHS, then "swap" them (which means
21873 // rewriting the mask).
21875 CommuteVectorShuffleMask(RMask, NumElts);
21877 // At this point LHS and RHS are equivalent to
21878 // LHS = VECTOR_SHUFFLE A, B, LMask
21879 // RHS = VECTOR_SHUFFLE A, B, RMask
21880 // Check that the masks correspond to performing a horizontal operation.
21881 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21882 for (unsigned i = 0; i != NumLaneElts; ++i) {
21883 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21885 // Ignore any UNDEF components.
21886 if (LIdx < 0 || RIdx < 0 ||
21887 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21888 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21891 // Check that successive elements are being operated on. If not, this is
21892 // not a horizontal operation.
21893 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21894 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21895 if (!(LIdx == Index && RIdx == Index + 1) &&
21896 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21901 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21902 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21906 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21907 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21908 const X86Subtarget *Subtarget) {
21909 EVT VT = N->getValueType(0);
21910 SDValue LHS = N->getOperand(0);
21911 SDValue RHS = N->getOperand(1);
21913 // Try to synthesize horizontal adds from adds of shuffles.
21914 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21915 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21916 isHorizontalBinOp(LHS, RHS, true))
21917 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21921 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21922 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21923 const X86Subtarget *Subtarget) {
21924 EVT VT = N->getValueType(0);
21925 SDValue LHS = N->getOperand(0);
21926 SDValue RHS = N->getOperand(1);
21928 // Try to synthesize horizontal subs from subs of shuffles.
21929 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21930 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21931 isHorizontalBinOp(LHS, RHS, false))
21932 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21936 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21937 /// X86ISD::FXOR nodes.
21938 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21939 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21940 // F[X]OR(0.0, x) -> x
21941 // F[X]OR(x, 0.0) -> x
21942 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21943 if (C->getValueAPF().isPosZero())
21944 return N->getOperand(1);
21945 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21946 if (C->getValueAPF().isPosZero())
21947 return N->getOperand(0);
21951 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21952 /// X86ISD::FMAX nodes.
21953 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21954 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21956 // Only perform optimizations if UnsafeMath is used.
21957 if (!DAG.getTarget().Options.UnsafeFPMath)
21960 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21961 // into FMINC and FMAXC, which are Commutative operations.
21962 unsigned NewOp = 0;
21963 switch (N->getOpcode()) {
21964 default: llvm_unreachable("unknown opcode");
21965 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21966 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21969 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21970 N->getOperand(0), N->getOperand(1));
21973 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21974 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21975 // FAND(0.0, x) -> 0.0
21976 // FAND(x, 0.0) -> 0.0
21977 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21978 if (C->getValueAPF().isPosZero())
21979 return N->getOperand(0);
21980 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21981 if (C->getValueAPF().isPosZero())
21982 return N->getOperand(1);
21986 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21987 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21988 // FANDN(x, 0.0) -> 0.0
21989 // FANDN(0.0, x) -> x
21990 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21991 if (C->getValueAPF().isPosZero())
21992 return N->getOperand(1);
21993 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21994 if (C->getValueAPF().isPosZero())
21995 return N->getOperand(1);
21999 static SDValue PerformBTCombine(SDNode *N,
22001 TargetLowering::DAGCombinerInfo &DCI) {
22002 // BT ignores high bits in the bit index operand.
22003 SDValue Op1 = N->getOperand(1);
22004 if (Op1.hasOneUse()) {
22005 unsigned BitWidth = Op1.getValueSizeInBits();
22006 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22007 APInt KnownZero, KnownOne;
22008 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22009 !DCI.isBeforeLegalizeOps());
22010 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22011 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22012 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22013 DCI.CommitTargetLoweringOpt(TLO);
22018 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22019 SDValue Op = N->getOperand(0);
22020 if (Op.getOpcode() == ISD::BITCAST)
22021 Op = Op.getOperand(0);
22022 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22023 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22024 VT.getVectorElementType().getSizeInBits() ==
22025 OpVT.getVectorElementType().getSizeInBits()) {
22026 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22031 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22032 const X86Subtarget *Subtarget) {
22033 EVT VT = N->getValueType(0);
22034 if (!VT.isVector())
22037 SDValue N0 = N->getOperand(0);
22038 SDValue N1 = N->getOperand(1);
22039 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22042 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22043 // both SSE and AVX2 since there is no sign-extended shift right
22044 // operation on a vector with 64-bit elements.
22045 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22046 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22047 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22048 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22049 SDValue N00 = N0.getOperand(0);
22051 // EXTLOAD has a better solution on AVX2,
22052 // it may be replaced with X86ISD::VSEXT node.
22053 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22054 if (!ISD::isNormalLoad(N00.getNode()))
22057 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22058 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22060 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22066 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22067 TargetLowering::DAGCombinerInfo &DCI,
22068 const X86Subtarget *Subtarget) {
22069 if (!DCI.isBeforeLegalizeOps())
22072 if (!Subtarget->hasFp256())
22075 EVT VT = N->getValueType(0);
22076 if (VT.isVector() && VT.getSizeInBits() == 256) {
22077 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22085 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22086 const X86Subtarget* Subtarget) {
22088 EVT VT = N->getValueType(0);
22090 // Let legalize expand this if it isn't a legal type yet.
22091 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22094 EVT ScalarVT = VT.getScalarType();
22095 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22096 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22099 SDValue A = N->getOperand(0);
22100 SDValue B = N->getOperand(1);
22101 SDValue C = N->getOperand(2);
22103 bool NegA = (A.getOpcode() == ISD::FNEG);
22104 bool NegB = (B.getOpcode() == ISD::FNEG);
22105 bool NegC = (C.getOpcode() == ISD::FNEG);
22107 // Negative multiplication when NegA xor NegB
22108 bool NegMul = (NegA != NegB);
22110 A = A.getOperand(0);
22112 B = B.getOperand(0);
22114 C = C.getOperand(0);
22118 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22120 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22122 return DAG.getNode(Opcode, dl, VT, A, B, C);
22125 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22126 TargetLowering::DAGCombinerInfo &DCI,
22127 const X86Subtarget *Subtarget) {
22128 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22129 // (and (i32 x86isd::setcc_carry), 1)
22130 // This eliminates the zext. This transformation is necessary because
22131 // ISD::SETCC is always legalized to i8.
22133 SDValue N0 = N->getOperand(0);
22134 EVT VT = N->getValueType(0);
22136 if (N0.getOpcode() == ISD::AND &&
22138 N0.getOperand(0).hasOneUse()) {
22139 SDValue N00 = N0.getOperand(0);
22140 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22141 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22142 if (!C || C->getZExtValue() != 1)
22144 return DAG.getNode(ISD::AND, dl, VT,
22145 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22146 N00.getOperand(0), N00.getOperand(1)),
22147 DAG.getConstant(1, VT));
22151 if (N0.getOpcode() == ISD::TRUNCATE &&
22153 N0.getOperand(0).hasOneUse()) {
22154 SDValue N00 = N0.getOperand(0);
22155 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22156 return DAG.getNode(ISD::AND, dl, VT,
22157 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22158 N00.getOperand(0), N00.getOperand(1)),
22159 DAG.getConstant(1, VT));
22162 if (VT.is256BitVector()) {
22163 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22171 // Optimize x == -y --> x+y == 0
22172 // x != -y --> x+y != 0
22173 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22174 const X86Subtarget* Subtarget) {
22175 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22176 SDValue LHS = N->getOperand(0);
22177 SDValue RHS = N->getOperand(1);
22178 EVT VT = N->getValueType(0);
22181 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22183 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22184 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22185 LHS.getValueType(), RHS, LHS.getOperand(1));
22186 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22187 addV, DAG.getConstant(0, addV.getValueType()), CC);
22189 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22190 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22191 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22192 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22193 RHS.getValueType(), LHS, RHS.getOperand(1));
22194 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22195 addV, DAG.getConstant(0, addV.getValueType()), CC);
22198 if (VT.getScalarType() == MVT::i1) {
22199 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22200 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22201 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22202 if (!IsSEXT0 && !IsVZero0)
22204 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22205 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22206 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22208 if (!IsSEXT1 && !IsVZero1)
22211 if (IsSEXT0 && IsVZero1) {
22212 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22213 if (CC == ISD::SETEQ)
22214 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22215 return LHS.getOperand(0);
22217 if (IsSEXT1 && IsVZero0) {
22218 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22219 if (CC == ISD::SETEQ)
22220 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22221 return RHS.getOperand(0);
22228 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22229 const X86Subtarget *Subtarget) {
22231 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22232 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22233 "X86insertps is only defined for v4x32");
22235 SDValue Ld = N->getOperand(1);
22236 if (MayFoldLoad(Ld)) {
22237 // Extract the countS bits from the immediate so we can get the proper
22238 // address when narrowing the vector load to a specific element.
22239 // When the second source op is a memory address, interps doesn't use
22240 // countS and just gets an f32 from that address.
22241 unsigned DestIndex =
22242 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22243 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22247 // Create this as a scalar to vector to match the instruction pattern.
22248 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22249 // countS bits are ignored when loading from memory on insertps, which
22250 // means we don't need to explicitly set them to 0.
22251 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22252 LoadScalarToVector, N->getOperand(2));
22255 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22256 // as "sbb reg,reg", since it can be extended without zext and produces
22257 // an all-ones bit which is more useful than 0/1 in some cases.
22258 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22261 return DAG.getNode(ISD::AND, DL, VT,
22262 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22263 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22264 DAG.getConstant(1, VT));
22265 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22266 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22267 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22268 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22271 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22272 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22273 TargetLowering::DAGCombinerInfo &DCI,
22274 const X86Subtarget *Subtarget) {
22276 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22277 SDValue EFLAGS = N->getOperand(1);
22279 if (CC == X86::COND_A) {
22280 // Try to convert COND_A into COND_B in an attempt to facilitate
22281 // materializing "setb reg".
22283 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22284 // cannot take an immediate as its first operand.
22286 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22287 EFLAGS.getValueType().isInteger() &&
22288 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22289 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22290 EFLAGS.getNode()->getVTList(),
22291 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22292 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22293 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22297 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22298 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22300 if (CC == X86::COND_B)
22301 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22305 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22306 if (Flags.getNode()) {
22307 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22308 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22314 // Optimize branch condition evaluation.
22316 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22317 TargetLowering::DAGCombinerInfo &DCI,
22318 const X86Subtarget *Subtarget) {
22320 SDValue Chain = N->getOperand(0);
22321 SDValue Dest = N->getOperand(1);
22322 SDValue EFLAGS = N->getOperand(3);
22323 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22327 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22328 if (Flags.getNode()) {
22329 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22330 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22337 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22338 const X86TargetLowering *XTLI) {
22339 SDValue Op0 = N->getOperand(0);
22340 EVT InVT = Op0->getValueType(0);
22342 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22343 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22345 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22346 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22347 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22350 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22351 // a 32-bit target where SSE doesn't support i64->FP operations.
22352 if (Op0.getOpcode() == ISD::LOAD) {
22353 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22354 EVT VT = Ld->getValueType(0);
22355 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22356 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22357 !XTLI->getSubtarget()->is64Bit() &&
22359 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22360 Ld->getChain(), Op0, DAG);
22361 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22368 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22369 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22370 X86TargetLowering::DAGCombinerInfo &DCI) {
22371 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22372 // the result is either zero or one (depending on the input carry bit).
22373 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22374 if (X86::isZeroNode(N->getOperand(0)) &&
22375 X86::isZeroNode(N->getOperand(1)) &&
22376 // We don't have a good way to replace an EFLAGS use, so only do this when
22378 SDValue(N, 1).use_empty()) {
22380 EVT VT = N->getValueType(0);
22381 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22382 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22383 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22384 DAG.getConstant(X86::COND_B,MVT::i8),
22386 DAG.getConstant(1, VT));
22387 return DCI.CombineTo(N, Res1, CarryOut);
22393 // fold (add Y, (sete X, 0)) -> adc 0, Y
22394 // (add Y, (setne X, 0)) -> sbb -1, Y
22395 // (sub (sete X, 0), Y) -> sbb 0, Y
22396 // (sub (setne X, 0), Y) -> adc -1, Y
22397 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22400 // Look through ZExts.
22401 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22402 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22405 SDValue SetCC = Ext.getOperand(0);
22406 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22409 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22410 if (CC != X86::COND_E && CC != X86::COND_NE)
22413 SDValue Cmp = SetCC.getOperand(1);
22414 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22415 !X86::isZeroNode(Cmp.getOperand(1)) ||
22416 !Cmp.getOperand(0).getValueType().isInteger())
22419 SDValue CmpOp0 = Cmp.getOperand(0);
22420 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22421 DAG.getConstant(1, CmpOp0.getValueType()));
22423 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22424 if (CC == X86::COND_NE)
22425 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22426 DL, OtherVal.getValueType(), OtherVal,
22427 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22428 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22429 DL, OtherVal.getValueType(), OtherVal,
22430 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22433 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22434 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22435 const X86Subtarget *Subtarget) {
22436 EVT VT = N->getValueType(0);
22437 SDValue Op0 = N->getOperand(0);
22438 SDValue Op1 = N->getOperand(1);
22440 // Try to synthesize horizontal adds from adds of shuffles.
22441 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22442 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22443 isHorizontalBinOp(Op0, Op1, true))
22444 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22446 return OptimizeConditionalInDecrement(N, DAG);
22449 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22450 const X86Subtarget *Subtarget) {
22451 SDValue Op0 = N->getOperand(0);
22452 SDValue Op1 = N->getOperand(1);
22454 // X86 can't encode an immediate LHS of a sub. See if we can push the
22455 // negation into a preceding instruction.
22456 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22457 // If the RHS of the sub is a XOR with one use and a constant, invert the
22458 // immediate. Then add one to the LHS of the sub so we can turn
22459 // X-Y -> X+~Y+1, saving one register.
22460 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22461 isa<ConstantSDNode>(Op1.getOperand(1))) {
22462 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22463 EVT VT = Op0.getValueType();
22464 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22466 DAG.getConstant(~XorC, VT));
22467 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22468 DAG.getConstant(C->getAPIntValue()+1, VT));
22472 // Try to synthesize horizontal adds from adds of shuffles.
22473 EVT VT = N->getValueType(0);
22474 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22475 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22476 isHorizontalBinOp(Op0, Op1, true))
22477 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22479 return OptimizeConditionalInDecrement(N, DAG);
22482 /// performVZEXTCombine - Performs build vector combines
22483 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22484 TargetLowering::DAGCombinerInfo &DCI,
22485 const X86Subtarget *Subtarget) {
22486 // (vzext (bitcast (vzext (x)) -> (vzext x)
22487 SDValue In = N->getOperand(0);
22488 while (In.getOpcode() == ISD::BITCAST)
22489 In = In.getOperand(0);
22491 if (In.getOpcode() != X86ISD::VZEXT)
22494 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22498 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22499 DAGCombinerInfo &DCI) const {
22500 SelectionDAG &DAG = DCI.DAG;
22501 switch (N->getOpcode()) {
22503 case ISD::EXTRACT_VECTOR_ELT:
22504 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22506 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22507 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22508 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22509 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22510 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22511 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22514 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22515 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22516 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22517 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22518 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22519 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22520 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22521 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22522 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22524 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22526 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22527 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22528 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22529 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22530 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22531 case ISD::ANY_EXTEND:
22532 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22533 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22534 case ISD::SIGN_EXTEND_INREG:
22535 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22536 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22537 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22538 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22539 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22540 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22541 case X86ISD::SHUFP: // Handle all target specific shuffles
22542 case X86ISD::PALIGNR:
22543 case X86ISD::UNPCKH:
22544 case X86ISD::UNPCKL:
22545 case X86ISD::MOVHLPS:
22546 case X86ISD::MOVLHPS:
22547 case X86ISD::PSHUFD:
22548 case X86ISD::PSHUFHW:
22549 case X86ISD::PSHUFLW:
22550 case X86ISD::MOVSS:
22551 case X86ISD::MOVSD:
22552 case X86ISD::VPERMILP:
22553 case X86ISD::VPERM2X128:
22554 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22555 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22556 case ISD::INTRINSIC_WO_CHAIN:
22557 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22558 case X86ISD::INSERTPS:
22559 return PerformINSERTPSCombine(N, DAG, Subtarget);
22560 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22566 /// isTypeDesirableForOp - Return true if the target has native support for
22567 /// the specified value type and it is 'desirable' to use the type for the
22568 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22569 /// instruction encodings are longer and some i16 instructions are slow.
22570 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22571 if (!isTypeLegal(VT))
22573 if (VT != MVT::i16)
22580 case ISD::SIGN_EXTEND:
22581 case ISD::ZERO_EXTEND:
22582 case ISD::ANY_EXTEND:
22595 /// IsDesirableToPromoteOp - This method query the target whether it is
22596 /// beneficial for dag combiner to promote the specified node. If true, it
22597 /// should return the desired promotion type by reference.
22598 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22599 EVT VT = Op.getValueType();
22600 if (VT != MVT::i16)
22603 bool Promote = false;
22604 bool Commute = false;
22605 switch (Op.getOpcode()) {
22608 LoadSDNode *LD = cast<LoadSDNode>(Op);
22609 // If the non-extending load has a single use and it's not live out, then it
22610 // might be folded.
22611 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22612 Op.hasOneUse()*/) {
22613 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22614 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22615 // The only case where we'd want to promote LOAD (rather then it being
22616 // promoted as an operand is when it's only use is liveout.
22617 if (UI->getOpcode() != ISD::CopyToReg)
22624 case ISD::SIGN_EXTEND:
22625 case ISD::ZERO_EXTEND:
22626 case ISD::ANY_EXTEND:
22631 SDValue N0 = Op.getOperand(0);
22632 // Look out for (store (shl (load), x)).
22633 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22646 SDValue N0 = Op.getOperand(0);
22647 SDValue N1 = Op.getOperand(1);
22648 if (!Commute && MayFoldLoad(N1))
22650 // Avoid disabling potential load folding opportunities.
22651 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22653 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22663 //===----------------------------------------------------------------------===//
22664 // X86 Inline Assembly Support
22665 //===----------------------------------------------------------------------===//
22668 // Helper to match a string separated by whitespace.
22669 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22670 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22672 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22673 StringRef piece(*args[i]);
22674 if (!s.startswith(piece)) // Check if the piece matches.
22677 s = s.substr(piece.size());
22678 StringRef::size_type pos = s.find_first_not_of(" \t");
22679 if (pos == 0) // We matched a prefix.
22687 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22690 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22692 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22693 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22694 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22695 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22697 if (AsmPieces.size() == 3)
22699 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22706 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22707 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22709 std::string AsmStr = IA->getAsmString();
22711 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22712 if (!Ty || Ty->getBitWidth() % 16 != 0)
22715 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22716 SmallVector<StringRef, 4> AsmPieces;
22717 SplitString(AsmStr, AsmPieces, ";\n");
22719 switch (AsmPieces.size()) {
22720 default: return false;
22722 // FIXME: this should verify that we are targeting a 486 or better. If not,
22723 // we will turn this bswap into something that will be lowered to logical
22724 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22725 // lower so don't worry about this.
22727 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22728 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22729 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22730 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22731 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22732 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22733 // No need to check constraints, nothing other than the equivalent of
22734 // "=r,0" would be valid here.
22735 return IntrinsicLowering::LowerToByteSwap(CI);
22738 // rorw $$8, ${0:w} --> llvm.bswap.i16
22739 if (CI->getType()->isIntegerTy(16) &&
22740 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22741 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22742 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22744 const std::string &ConstraintsStr = IA->getConstraintString();
22745 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22746 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22747 if (clobbersFlagRegisters(AsmPieces))
22748 return IntrinsicLowering::LowerToByteSwap(CI);
22752 if (CI->getType()->isIntegerTy(32) &&
22753 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22754 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22755 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22756 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22758 const std::string &ConstraintsStr = IA->getConstraintString();
22759 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22760 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22761 if (clobbersFlagRegisters(AsmPieces))
22762 return IntrinsicLowering::LowerToByteSwap(CI);
22765 if (CI->getType()->isIntegerTy(64)) {
22766 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22767 if (Constraints.size() >= 2 &&
22768 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22769 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22770 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22771 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22772 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22773 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22774 return IntrinsicLowering::LowerToByteSwap(CI);
22782 /// getConstraintType - Given a constraint letter, return the type of
22783 /// constraint it is for this target.
22784 X86TargetLowering::ConstraintType
22785 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22786 if (Constraint.size() == 1) {
22787 switch (Constraint[0]) {
22798 return C_RegisterClass;
22822 return TargetLowering::getConstraintType(Constraint);
22825 /// Examine constraint type and operand type and determine a weight value.
22826 /// This object must already have been set up with the operand type
22827 /// and the current alternative constraint selected.
22828 TargetLowering::ConstraintWeight
22829 X86TargetLowering::getSingleConstraintMatchWeight(
22830 AsmOperandInfo &info, const char *constraint) const {
22831 ConstraintWeight weight = CW_Invalid;
22832 Value *CallOperandVal = info.CallOperandVal;
22833 // If we don't have a value, we can't do a match,
22834 // but allow it at the lowest weight.
22835 if (!CallOperandVal)
22837 Type *type = CallOperandVal->getType();
22838 // Look at the constraint type.
22839 switch (*constraint) {
22841 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22852 if (CallOperandVal->getType()->isIntegerTy())
22853 weight = CW_SpecificReg;
22858 if (type->isFloatingPointTy())
22859 weight = CW_SpecificReg;
22862 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22863 weight = CW_SpecificReg;
22867 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22868 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22869 weight = CW_Register;
22872 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22873 if (C->getZExtValue() <= 31)
22874 weight = CW_Constant;
22878 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22879 if (C->getZExtValue() <= 63)
22880 weight = CW_Constant;
22884 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22885 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22886 weight = CW_Constant;
22890 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22891 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22892 weight = CW_Constant;
22896 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22897 if (C->getZExtValue() <= 3)
22898 weight = CW_Constant;
22902 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22903 if (C->getZExtValue() <= 0xff)
22904 weight = CW_Constant;
22909 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22910 weight = CW_Constant;
22914 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22915 if ((C->getSExtValue() >= -0x80000000LL) &&
22916 (C->getSExtValue() <= 0x7fffffffLL))
22917 weight = CW_Constant;
22921 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22922 if (C->getZExtValue() <= 0xffffffff)
22923 weight = CW_Constant;
22930 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22931 /// with another that has more specific requirements based on the type of the
22932 /// corresponding operand.
22933 const char *X86TargetLowering::
22934 LowerXConstraint(EVT ConstraintVT) const {
22935 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22936 // 'f' like normal targets.
22937 if (ConstraintVT.isFloatingPoint()) {
22938 if (Subtarget->hasSSE2())
22940 if (Subtarget->hasSSE1())
22944 return TargetLowering::LowerXConstraint(ConstraintVT);
22947 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22948 /// vector. If it is invalid, don't add anything to Ops.
22949 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22950 std::string &Constraint,
22951 std::vector<SDValue>&Ops,
22952 SelectionDAG &DAG) const {
22955 // Only support length 1 constraints for now.
22956 if (Constraint.length() > 1) return;
22958 char ConstraintLetter = Constraint[0];
22959 switch (ConstraintLetter) {
22962 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22963 if (C->getZExtValue() <= 31) {
22964 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22970 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22971 if (C->getZExtValue() <= 63) {
22972 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22978 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22979 if (isInt<8>(C->getSExtValue())) {
22980 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22987 if (C->getZExtValue() <= 255) {
22988 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22994 // 32-bit signed value
22995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22996 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22997 C->getSExtValue())) {
22998 // Widen to 64 bits here to get it sign extended.
22999 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23002 // FIXME gcc accepts some relocatable values here too, but only in certain
23003 // memory models; it's complicated.
23008 // 32-bit unsigned value
23009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23010 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23011 C->getZExtValue())) {
23012 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23016 // FIXME gcc accepts some relocatable values here too, but only in certain
23017 // memory models; it's complicated.
23021 // Literal immediates are always ok.
23022 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23023 // Widen to 64 bits here to get it sign extended.
23024 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23028 // In any sort of PIC mode addresses need to be computed at runtime by
23029 // adding in a register or some sort of table lookup. These can't
23030 // be used as immediates.
23031 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23034 // If we are in non-pic codegen mode, we allow the address of a global (with
23035 // an optional displacement) to be used with 'i'.
23036 GlobalAddressSDNode *GA = nullptr;
23037 int64_t Offset = 0;
23039 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23041 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23042 Offset += GA->getOffset();
23044 } else if (Op.getOpcode() == ISD::ADD) {
23045 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23046 Offset += C->getZExtValue();
23047 Op = Op.getOperand(0);
23050 } else if (Op.getOpcode() == ISD::SUB) {
23051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23052 Offset += -C->getZExtValue();
23053 Op = Op.getOperand(0);
23058 // Otherwise, this isn't something we can handle, reject it.
23062 const GlobalValue *GV = GA->getGlobal();
23063 // If we require an extra load to get this address, as in PIC mode, we
23064 // can't accept it.
23065 if (isGlobalStubReference(
23066 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23069 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23070 GA->getValueType(0), Offset);
23075 if (Result.getNode()) {
23076 Ops.push_back(Result);
23079 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23082 std::pair<unsigned, const TargetRegisterClass*>
23083 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23085 // First, see if this is a constraint that directly corresponds to an LLVM
23087 if (Constraint.size() == 1) {
23088 // GCC Constraint Letters
23089 switch (Constraint[0]) {
23091 // TODO: Slight differences here in allocation order and leaving
23092 // RIP in the class. Do they matter any more here than they do
23093 // in the normal allocation?
23094 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23095 if (Subtarget->is64Bit()) {
23096 if (VT == MVT::i32 || VT == MVT::f32)
23097 return std::make_pair(0U, &X86::GR32RegClass);
23098 if (VT == MVT::i16)
23099 return std::make_pair(0U, &X86::GR16RegClass);
23100 if (VT == MVT::i8 || VT == MVT::i1)
23101 return std::make_pair(0U, &X86::GR8RegClass);
23102 if (VT == MVT::i64 || VT == MVT::f64)
23103 return std::make_pair(0U, &X86::GR64RegClass);
23106 // 32-bit fallthrough
23107 case 'Q': // Q_REGS
23108 if (VT == MVT::i32 || VT == MVT::f32)
23109 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23110 if (VT == MVT::i16)
23111 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23112 if (VT == MVT::i8 || VT == MVT::i1)
23113 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23114 if (VT == MVT::i64)
23115 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23117 case 'r': // GENERAL_REGS
23118 case 'l': // INDEX_REGS
23119 if (VT == MVT::i8 || VT == MVT::i1)
23120 return std::make_pair(0U, &X86::GR8RegClass);
23121 if (VT == MVT::i16)
23122 return std::make_pair(0U, &X86::GR16RegClass);
23123 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23124 return std::make_pair(0U, &X86::GR32RegClass);
23125 return std::make_pair(0U, &X86::GR64RegClass);
23126 case 'R': // LEGACY_REGS
23127 if (VT == MVT::i8 || VT == MVT::i1)
23128 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23129 if (VT == MVT::i16)
23130 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23131 if (VT == MVT::i32 || !Subtarget->is64Bit())
23132 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23133 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23134 case 'f': // FP Stack registers.
23135 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23136 // value to the correct fpstack register class.
23137 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23138 return std::make_pair(0U, &X86::RFP32RegClass);
23139 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23140 return std::make_pair(0U, &X86::RFP64RegClass);
23141 return std::make_pair(0U, &X86::RFP80RegClass);
23142 case 'y': // MMX_REGS if MMX allowed.
23143 if (!Subtarget->hasMMX()) break;
23144 return std::make_pair(0U, &X86::VR64RegClass);
23145 case 'Y': // SSE_REGS if SSE2 allowed
23146 if (!Subtarget->hasSSE2()) break;
23148 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23149 if (!Subtarget->hasSSE1()) break;
23151 switch (VT.SimpleTy) {
23153 // Scalar SSE types.
23156 return std::make_pair(0U, &X86::FR32RegClass);
23159 return std::make_pair(0U, &X86::FR64RegClass);
23167 return std::make_pair(0U, &X86::VR128RegClass);
23175 return std::make_pair(0U, &X86::VR256RegClass);
23180 return std::make_pair(0U, &X86::VR512RegClass);
23186 // Use the default implementation in TargetLowering to convert the register
23187 // constraint into a member of a register class.
23188 std::pair<unsigned, const TargetRegisterClass*> Res;
23189 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23191 // Not found as a standard register?
23193 // Map st(0) -> st(7) -> ST0
23194 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23195 tolower(Constraint[1]) == 's' &&
23196 tolower(Constraint[2]) == 't' &&
23197 Constraint[3] == '(' &&
23198 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23199 Constraint[5] == ')' &&
23200 Constraint[6] == '}') {
23202 Res.first = X86::ST0+Constraint[4]-'0';
23203 Res.second = &X86::RFP80RegClass;
23207 // GCC allows "st(0)" to be called just plain "st".
23208 if (StringRef("{st}").equals_lower(Constraint)) {
23209 Res.first = X86::ST0;
23210 Res.second = &X86::RFP80RegClass;
23215 if (StringRef("{flags}").equals_lower(Constraint)) {
23216 Res.first = X86::EFLAGS;
23217 Res.second = &X86::CCRRegClass;
23221 // 'A' means EAX + EDX.
23222 if (Constraint == "A") {
23223 Res.first = X86::EAX;
23224 Res.second = &X86::GR32_ADRegClass;
23230 // Otherwise, check to see if this is a register class of the wrong value
23231 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23232 // turn into {ax},{dx}.
23233 if (Res.second->hasType(VT))
23234 return Res; // Correct type already, nothing to do.
23236 // All of the single-register GCC register classes map their values onto
23237 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23238 // really want an 8-bit or 32-bit register, map to the appropriate register
23239 // class and return the appropriate register.
23240 if (Res.second == &X86::GR16RegClass) {
23241 if (VT == MVT::i8 || VT == MVT::i1) {
23242 unsigned DestReg = 0;
23243 switch (Res.first) {
23245 case X86::AX: DestReg = X86::AL; break;
23246 case X86::DX: DestReg = X86::DL; break;
23247 case X86::CX: DestReg = X86::CL; break;
23248 case X86::BX: DestReg = X86::BL; break;
23251 Res.first = DestReg;
23252 Res.second = &X86::GR8RegClass;
23254 } else if (VT == MVT::i32 || VT == MVT::f32) {
23255 unsigned DestReg = 0;
23256 switch (Res.first) {
23258 case X86::AX: DestReg = X86::EAX; break;
23259 case X86::DX: DestReg = X86::EDX; break;
23260 case X86::CX: DestReg = X86::ECX; break;
23261 case X86::BX: DestReg = X86::EBX; break;
23262 case X86::SI: DestReg = X86::ESI; break;
23263 case X86::DI: DestReg = X86::EDI; break;
23264 case X86::BP: DestReg = X86::EBP; break;
23265 case X86::SP: DestReg = X86::ESP; break;
23268 Res.first = DestReg;
23269 Res.second = &X86::GR32RegClass;
23271 } else if (VT == MVT::i64 || VT == MVT::f64) {
23272 unsigned DestReg = 0;
23273 switch (Res.first) {
23275 case X86::AX: DestReg = X86::RAX; break;
23276 case X86::DX: DestReg = X86::RDX; break;
23277 case X86::CX: DestReg = X86::RCX; break;
23278 case X86::BX: DestReg = X86::RBX; break;
23279 case X86::SI: DestReg = X86::RSI; break;
23280 case X86::DI: DestReg = X86::RDI; break;
23281 case X86::BP: DestReg = X86::RBP; break;
23282 case X86::SP: DestReg = X86::RSP; break;
23285 Res.first = DestReg;
23286 Res.second = &X86::GR64RegClass;
23289 } else if (Res.second == &X86::FR32RegClass ||
23290 Res.second == &X86::FR64RegClass ||
23291 Res.second == &X86::VR128RegClass ||
23292 Res.second == &X86::VR256RegClass ||
23293 Res.second == &X86::FR32XRegClass ||
23294 Res.second == &X86::FR64XRegClass ||
23295 Res.second == &X86::VR128XRegClass ||
23296 Res.second == &X86::VR256XRegClass ||
23297 Res.second == &X86::VR512RegClass) {
23298 // Handle references to XMM physical registers that got mapped into the
23299 // wrong class. This can happen with constraints like {xmm0} where the
23300 // target independent register mapper will just pick the first match it can
23301 // find, ignoring the required type.
23303 if (VT == MVT::f32 || VT == MVT::i32)
23304 Res.second = &X86::FR32RegClass;
23305 else if (VT == MVT::f64 || VT == MVT::i64)
23306 Res.second = &X86::FR64RegClass;
23307 else if (X86::VR128RegClass.hasType(VT))
23308 Res.second = &X86::VR128RegClass;
23309 else if (X86::VR256RegClass.hasType(VT))
23310 Res.second = &X86::VR256RegClass;
23311 else if (X86::VR512RegClass.hasType(VT))
23312 Res.second = &X86::VR512RegClass;
23318 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23320 // Scaling factors are not free at all.
23321 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23322 // will take 2 allocations in the out of order engine instead of 1
23323 // for plain addressing mode, i.e. inst (reg1).
23325 // vaddps (%rsi,%drx), %ymm0, %ymm1
23326 // Requires two allocations (one for the load, one for the computation)
23328 // vaddps (%rsi), %ymm0, %ymm1
23329 // Requires just 1 allocation, i.e., freeing allocations for other operations
23330 // and having less micro operations to execute.
23332 // For some X86 architectures, this is even worse because for instance for
23333 // stores, the complex addressing mode forces the instruction to use the
23334 // "load" ports instead of the dedicated "store" port.
23335 // E.g., on Haswell:
23336 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23337 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23338 if (isLegalAddressingMode(AM, Ty))
23339 // Scale represents reg2 * scale, thus account for 1
23340 // as soon as we use a second register.
23341 return AM.Scale != 0;
23345 bool X86TargetLowering::isTargetFTOL() const {
23346 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();