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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "x86-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64 SelectionDAG &DAG, SDLoc dl,
65 unsigned vectorWidth) {
66 assert((vectorWidth == 128 || vectorWidth == 256) &&
67 "Unsupported vector width");
68 EVT VT = Vec.getValueType();
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/vectorWidth;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
79 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
81 // This is the index of the first element of the vectorWidth-bit chunk
83 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
86 // If the input is a buildvector just emit a smaller one.
87 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
92 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106 SelectionDAG &DAG, SDLoc dl) {
107 assert((Vec.getValueType().is256BitVector() ||
108 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114 SelectionDAG &DAG, SDLoc dl) {
115 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120 unsigned IdxVal, SelectionDAG &DAG,
121 SDLoc dl, unsigned vectorWidth) {
122 assert((vectorWidth == 128 || vectorWidth == 256) &&
123 "Unsupported vector width");
124 // Inserting UNDEF is Result
125 if (Vec.getOpcode() == ISD::UNDEF)
127 EVT VT = Vec.getValueType();
128 EVT ElVT = VT.getVectorElementType();
129 EVT ResultVT = Result.getValueType();
131 // Insert the relevant vectorWidth bits.
132 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
134 // This is the index of the first element of the vectorWidth-bit chunk
136 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
139 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
143 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference. Idx is an index in the 128 bits
147 /// we want. It need not be aligned to a 128-bit bounday. That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150 unsigned IdxVal, SelectionDAG &DAG,
152 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168 unsigned NumElems, SelectionDAG &DAG,
170 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182 if (TT.isOSBinFormatMachO()) {
183 if (TT.getArch() == Triple::x86_64)
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
189 return new X86LinuxTargetObjectFile();
190 if (TT.isOSBinFormatELF())
191 return new TargetLoweringObjectFileELF();
192 if (TT.isKnownWindowsMSVCEnvironment())
193 return new X86WindowsTargetObjectFile();
194 if (TT.isOSBinFormatCOFF())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 // FIXME: This should stop caching the target machine as soon as
200 // we can remove resetOperationActions et al.
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
203 Subtarget = &TM.getSubtarget<X86Subtarget>();
204 X86ScalarSSEf64 = Subtarget->hasSSE2();
205 X86ScalarSSEf32 = Subtarget->hasSSE1();
206 TD = getDataLayout();
208 resetOperationActions();
211 void X86TargetLowering::resetOperationActions() {
212 const TargetMachine &TM = getTargetMachine();
213 static bool FirstTimeThrough = true;
215 // If none of the target options have changed, then we don't need to reset the
216 // operation actions.
217 if (!FirstTimeThrough && TO == TM.Options) return;
219 if (!FirstTimeThrough) {
220 // Reinitialize the actions.
222 FirstTimeThrough = false;
227 // Set up the TargetLowering object.
228 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230 // X86 is weird, it always uses i8 for shift amounts and setcc results.
231 setBooleanContents(ZeroOrOneBooleanContent);
232 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
233 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235 // For 64-bit since we have so many registers use the ILP scheduler, for
236 // 32-bit code use the register pressure specific scheduling.
237 // For Atom, always use ILP scheduling.
238 if (Subtarget->isAtom())
239 setSchedulingPreference(Sched::ILP);
240 else if (Subtarget->is64Bit())
241 setSchedulingPreference(Sched::ILP);
243 setSchedulingPreference(Sched::RegPressure);
244 const X86RegisterInfo *RegInfo =
245 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248 // Bypass expensive divides on Atom when compiling with O2
249 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
250 addBypassSlowDiv(32, 8);
251 if (Subtarget->is64Bit())
252 addBypassSlowDiv(64, 16);
255 if (Subtarget->isTargetKnownWindowsMSVC()) {
256 // Setup Windows compiler runtime calls.
257 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
258 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
259 setLibcallName(RTLIB::SREM_I64, "_allrem");
260 setLibcallName(RTLIB::UREM_I64, "_aullrem");
261 setLibcallName(RTLIB::MUL_I64, "_allmul");
262 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268 // The _ftol2 runtime function has an unusual calling conv, which
269 // is modeled by a special pseudo-instruction.
270 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
276 if (Subtarget->isTargetDarwin()) {
277 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
278 setUseUnderscoreSetJmp(false);
279 setUseUnderscoreLongJmp(false);
280 } else if (Subtarget->isTargetWindowsGNU()) {
281 // MS runtime is weird: it exports _setjmp, but longjmp!
282 setUseUnderscoreSetJmp(true);
283 setUseUnderscoreLongJmp(false);
285 setUseUnderscoreSetJmp(true);
286 setUseUnderscoreLongJmp(true);
289 // Set up the register classes.
290 addRegisterClass(MVT::i8, &X86::GR8RegClass);
291 addRegisterClass(MVT::i16, &X86::GR16RegClass);
292 addRegisterClass(MVT::i32, &X86::GR32RegClass);
293 if (Subtarget->is64Bit())
294 addRegisterClass(MVT::i64, &X86::GR64RegClass);
296 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298 // We don't accept any truncstore of integer registers.
299 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
303 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
304 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
306 // SETOEQ and SETUNE require checking two conditions.
307 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
320 if (Subtarget->is64Bit()) {
321 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 } else if (!TM.Options.UseSoftFloat) {
324 // We have an algorithm for SSE2->double, and we turn this into a
325 // 64-bit FILD followed by conditional FADD for other targets.
326 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
327 // We have an algorithm for SSE2, and we turn this into a 64-bit
328 // FILD for other targets.
329 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
332 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
335 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
337 if (!TM.Options.UseSoftFloat) {
338 // SSE has no i16 to fp conversion, only i32
339 if (X86ScalarSSEf32) {
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
341 // f32 and f64 cases are Legal, f80 case is not
342 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
352 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
353 // are Legal, f80 is custom lowered.
354 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
355 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
357 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
360 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
362 if (X86ScalarSSEf32) {
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
364 // f32 and f64 cases are Legal, f80 case is not
365 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
371 // Handle FP_TO_UINT by promoting the destination to a larger signed
373 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
377 if (Subtarget->is64Bit()) {
378 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
379 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
380 } else if (!TM.Options.UseSoftFloat) {
381 // Since AVX is a superset of SSE3, only check for SSE here.
382 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
383 // Expand FP_TO_UINT into a select.
384 // FIXME: We would like to use a Custom expander here eventually to do
385 // the optimal thing for SSE vs. the default expansion in the legalizer.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
388 // With SSE3 we can use fisttpll to convert to a signed i64; without
389 // SSE, we're stuck with a fistpll.
390 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
393 if (isTargetFTOL()) {
394 // Use the _ftol2 runtime function, which has a pseudo-instruction
395 // to handle its weird calling convention.
396 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
399 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
400 if (!X86ScalarSSEf64) {
401 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
402 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
403 if (Subtarget->is64Bit()) {
404 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
405 // Without SSE, i64->f64 goes through memory.
406 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
410 // Scalar integer divide and remainder are lowered to use operations that
411 // produce two results, to match the available instructions. This exposes
412 // the two-result form to trivial CSE, which is able to combine x/y and x%y
413 // into a single instruction.
415 // Scalar integer multiply-high is also lowered to use two-result
416 // operations, to match the available instructions. However, plain multiply
417 // (low) operations are left as Legal, as there are single-result
418 // instructions for this in x86. Using the two-result multiply instructions
419 // when both high and low results are needed must be arranged by dagcombine.
420 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422 setOperationAction(ISD::MULHS, VT, Expand);
423 setOperationAction(ISD::MULHU, VT, Expand);
424 setOperationAction(ISD::SDIV, VT, Expand);
425 setOperationAction(ISD::UDIV, VT, Expand);
426 setOperationAction(ISD::SREM, VT, Expand);
427 setOperationAction(ISD::UREM, VT, Expand);
429 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
430 setOperationAction(ISD::ADDC, VT, Custom);
431 setOperationAction(ISD::ADDE, VT, Custom);
432 setOperationAction(ISD::SUBC, VT, Custom);
433 setOperationAction(ISD::SUBE, VT, Custom);
436 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
437 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
438 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
445 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
447 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
448 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
449 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
450 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
451 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
452 if (Subtarget->is64Bit())
453 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
455 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
456 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
457 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
458 setOperationAction(ISD::FREM , MVT::f32 , Expand);
459 setOperationAction(ISD::FREM , MVT::f64 , Expand);
460 setOperationAction(ISD::FREM , MVT::f80 , Expand);
461 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
463 // Promote the i8 variants and force them on up to i32 which has a shorter
465 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
466 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
468 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
469 if (Subtarget->hasBMI()) {
470 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
471 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
472 if (Subtarget->is64Bit())
473 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
475 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
476 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
477 if (Subtarget->is64Bit())
478 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
481 if (Subtarget->hasLZCNT()) {
482 // When promoting the i8 variants, force them to i32 for a shorter
484 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
485 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
487 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
493 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
494 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
495 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
497 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
498 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
499 if (Subtarget->is64Bit()) {
500 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
505 if (Subtarget->hasPOPCNT()) {
506 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
508 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
509 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
510 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
511 if (Subtarget->is64Bit())
512 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
515 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
517 if (!Subtarget->hasMOVBE())
518 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
520 // These should be promoted to a larger select which is supported.
521 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
522 // X86 wants to expand cmov itself.
523 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
524 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
525 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
526 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
527 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
528 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
531 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
532 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
533 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
534 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
535 if (Subtarget->is64Bit()) {
536 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
537 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
539 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
540 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
541 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
542 // support continuation, user-level threading, and etc.. As a result, no
543 // other SjLj exception interfaces are implemented and please don't build
544 // your own exception handling based on them.
545 // LLVM/Clang supports zero-cost DWARF exception handling.
546 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
547 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
550 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
551 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
552 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
553 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
554 if (Subtarget->is64Bit())
555 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
556 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
557 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
558 if (Subtarget->is64Bit()) {
559 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
560 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
561 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
562 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
563 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
565 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
566 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
567 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
568 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
569 if (Subtarget->is64Bit()) {
570 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
571 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
572 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
575 if (Subtarget->hasSSE1())
576 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
578 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
580 // Expand certain atomics
581 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
583 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
585 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
588 if (!Subtarget->is64Bit()) {
589 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
596 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
598 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
599 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
600 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
603 if (Subtarget->hasCmpxchg16b()) {
604 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
607 // FIXME - use subtarget debug flags
608 if (!Subtarget->isTargetDarwin() &&
609 !Subtarget->isTargetELF() &&
610 !Subtarget->isTargetCygMing()) {
611 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
614 if (Subtarget->is64Bit()) {
615 setExceptionPointerRegister(X86::RAX);
616 setExceptionSelectorRegister(X86::RDX);
618 setExceptionPointerRegister(X86::EAX);
619 setExceptionSelectorRegister(X86::EDX);
621 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
622 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
624 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
625 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
627 setOperationAction(ISD::TRAP, MVT::Other, Legal);
628 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
630 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
631 setOperationAction(ISD::VASTART , MVT::Other, Custom);
632 setOperationAction(ISD::VAEND , MVT::Other, Expand);
633 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
634 // TargetInfo::X86_64ABIBuiltinVaList
635 setOperationAction(ISD::VAARG , MVT::Other, Custom);
636 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
638 // TargetInfo::CharPtrBuiltinVaList
639 setOperationAction(ISD::VAARG , MVT::Other, Expand);
640 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
643 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
644 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
646 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
647 MVT::i64 : MVT::i32, Custom);
649 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
650 // f32 and f64 use SSE.
651 // Set up the FP register classes.
652 addRegisterClass(MVT::f32, &X86::FR32RegClass);
653 addRegisterClass(MVT::f64, &X86::FR64RegClass);
655 // Use ANDPD to simulate FABS.
656 setOperationAction(ISD::FABS , MVT::f64, Custom);
657 setOperationAction(ISD::FABS , MVT::f32, Custom);
659 // Use XORP to simulate FNEG.
660 setOperationAction(ISD::FNEG , MVT::f64, Custom);
661 setOperationAction(ISD::FNEG , MVT::f32, Custom);
663 // Use ANDPD and ORPD to simulate FCOPYSIGN.
664 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
665 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
667 // Lower this to FGETSIGNx86 plus an AND.
668 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
669 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
671 // We don't support sin/cos/fmod
672 setOperationAction(ISD::FSIN , MVT::f64, Expand);
673 setOperationAction(ISD::FCOS , MVT::f64, Expand);
674 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
675 setOperationAction(ISD::FSIN , MVT::f32, Expand);
676 setOperationAction(ISD::FCOS , MVT::f32, Expand);
677 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
679 // Expand FP immediates into loads from the stack, except for the special
681 addLegalFPImmediate(APFloat(+0.0)); // xorpd
682 addLegalFPImmediate(APFloat(+0.0f)); // xorps
683 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
684 // Use SSE for f32, x87 for f64.
685 // Set up the FP register classes.
686 addRegisterClass(MVT::f32, &X86::FR32RegClass);
687 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
689 // Use ANDPS to simulate FABS.
690 setOperationAction(ISD::FABS , MVT::f32, Custom);
692 // Use XORP to simulate FNEG.
693 setOperationAction(ISD::FNEG , MVT::f32, Custom);
695 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
697 // Use ANDPS and ORPS to simulate FCOPYSIGN.
698 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
699 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
701 // We don't support sin/cos/fmod
702 setOperationAction(ISD::FSIN , MVT::f32, Expand);
703 setOperationAction(ISD::FCOS , MVT::f32, Expand);
704 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
706 // Special cases we handle for FP constants.
707 addLegalFPImmediate(APFloat(+0.0f)); // xorps
708 addLegalFPImmediate(APFloat(+0.0)); // FLD0
709 addLegalFPImmediate(APFloat(+1.0)); // FLD1
710 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
711 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
713 if (!TM.Options.UnsafeFPMath) {
714 setOperationAction(ISD::FSIN , MVT::f64, Expand);
715 setOperationAction(ISD::FCOS , MVT::f64, Expand);
716 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
718 } else if (!TM.Options.UseSoftFloat) {
719 // f32 and f64 in x87.
720 // Set up the FP register classes.
721 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
722 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
724 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
725 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
727 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FSIN , MVT::f32, Expand);
732 setOperationAction(ISD::FCOS , MVT::f64, Expand);
733 setOperationAction(ISD::FCOS , MVT::f32, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
735 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
737 addLegalFPImmediate(APFloat(+0.0)); // FLD0
738 addLegalFPImmediate(APFloat(+1.0)); // FLD1
739 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
740 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
741 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
742 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
743 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
744 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
747 // We don't support FMA.
748 setOperationAction(ISD::FMA, MVT::f64, Expand);
749 setOperationAction(ISD::FMA, MVT::f32, Expand);
751 // Long double always uses X87.
752 if (!TM.Options.UseSoftFloat) {
753 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
754 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
755 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
757 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
758 addLegalFPImmediate(TmpFlt); // FLD0
760 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
763 APFloat TmpFlt2(+1.0);
764 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
766 addLegalFPImmediate(TmpFlt2); // FLD1
767 TmpFlt2.changeSign();
768 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
771 if (!TM.Options.UnsafeFPMath) {
772 setOperationAction(ISD::FSIN , MVT::f80, Expand);
773 setOperationAction(ISD::FCOS , MVT::f80, Expand);
774 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
777 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
778 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
779 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
780 setOperationAction(ISD::FRINT, MVT::f80, Expand);
781 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
782 setOperationAction(ISD::FMA, MVT::f80, Expand);
785 // Always use a library call for pow.
786 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
788 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
790 setOperationAction(ISD::FLOG, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
792 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP, MVT::f80, Expand);
794 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
796 // First set operation action for all vector types to either promote
797 // (for widening) or expand (for scalarization). Then we will selectively
798 // turn on ones that can be effectively codegen'd.
799 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
800 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
801 MVT VT = (MVT::SimpleValueType)i;
802 setOperationAction(ISD::ADD , VT, Expand);
803 setOperationAction(ISD::SUB , VT, Expand);
804 setOperationAction(ISD::FADD, VT, Expand);
805 setOperationAction(ISD::FNEG, VT, Expand);
806 setOperationAction(ISD::FSUB, VT, Expand);
807 setOperationAction(ISD::MUL , VT, Expand);
808 setOperationAction(ISD::FMUL, VT, Expand);
809 setOperationAction(ISD::SDIV, VT, Expand);
810 setOperationAction(ISD::UDIV, VT, Expand);
811 setOperationAction(ISD::FDIV, VT, Expand);
812 setOperationAction(ISD::SREM, VT, Expand);
813 setOperationAction(ISD::UREM, VT, Expand);
814 setOperationAction(ISD::LOAD, VT, Expand);
815 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
816 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
818 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
820 setOperationAction(ISD::FABS, VT, Expand);
821 setOperationAction(ISD::FSIN, VT, Expand);
822 setOperationAction(ISD::FSINCOS, VT, Expand);
823 setOperationAction(ISD::FCOS, VT, Expand);
824 setOperationAction(ISD::FSINCOS, VT, Expand);
825 setOperationAction(ISD::FREM, VT, Expand);
826 setOperationAction(ISD::FMA, VT, Expand);
827 setOperationAction(ISD::FPOWI, VT, Expand);
828 setOperationAction(ISD::FSQRT, VT, Expand);
829 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
830 setOperationAction(ISD::FFLOOR, VT, Expand);
831 setOperationAction(ISD::FCEIL, VT, Expand);
832 setOperationAction(ISD::FTRUNC, VT, Expand);
833 setOperationAction(ISD::FRINT, VT, Expand);
834 setOperationAction(ISD::FNEARBYINT, VT, Expand);
835 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::MULHS, VT, Expand);
837 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
838 setOperationAction(ISD::MULHU, VT, Expand);
839 setOperationAction(ISD::SDIVREM, VT, Expand);
840 setOperationAction(ISD::UDIVREM, VT, Expand);
841 setOperationAction(ISD::FPOW, VT, Expand);
842 setOperationAction(ISD::CTPOP, VT, Expand);
843 setOperationAction(ISD::CTTZ, VT, Expand);
844 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
845 setOperationAction(ISD::CTLZ, VT, Expand);
846 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
847 setOperationAction(ISD::SHL, VT, Expand);
848 setOperationAction(ISD::SRA, VT, Expand);
849 setOperationAction(ISD::SRL, VT, Expand);
850 setOperationAction(ISD::ROTL, VT, Expand);
851 setOperationAction(ISD::ROTR, VT, Expand);
852 setOperationAction(ISD::BSWAP, VT, Expand);
853 setOperationAction(ISD::SETCC, VT, Expand);
854 setOperationAction(ISD::FLOG, VT, Expand);
855 setOperationAction(ISD::FLOG2, VT, Expand);
856 setOperationAction(ISD::FLOG10, VT, Expand);
857 setOperationAction(ISD::FEXP, VT, Expand);
858 setOperationAction(ISD::FEXP2, VT, Expand);
859 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
860 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
861 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
862 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
863 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
864 setOperationAction(ISD::TRUNCATE, VT, Expand);
865 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
866 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
867 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
868 setOperationAction(ISD::VSELECT, VT, Expand);
869 setOperationAction(ISD::SELECT_CC, VT, Expand);
870 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
871 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
872 setTruncStoreAction(VT,
873 (MVT::SimpleValueType)InnerVT, Expand);
874 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
875 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
876 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
879 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
880 // with -msoft-float, disable use of MMX as well.
881 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
882 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
883 // No operations on x86mmx supported, everything uses intrinsics.
886 // MMX-sized vectors (other than x86mmx) are expected to be expanded
887 // into smaller operations.
888 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
889 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
890 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
891 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
892 setOperationAction(ISD::AND, MVT::v8i8, Expand);
893 setOperationAction(ISD::AND, MVT::v4i16, Expand);
894 setOperationAction(ISD::AND, MVT::v2i32, Expand);
895 setOperationAction(ISD::AND, MVT::v1i64, Expand);
896 setOperationAction(ISD::OR, MVT::v8i8, Expand);
897 setOperationAction(ISD::OR, MVT::v4i16, Expand);
898 setOperationAction(ISD::OR, MVT::v2i32, Expand);
899 setOperationAction(ISD::OR, MVT::v1i64, Expand);
900 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
901 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
902 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
903 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
904 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
905 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
906 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
907 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
908 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
909 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
910 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
911 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
912 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
913 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
914 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
915 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
916 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
918 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
919 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
921 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
922 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
923 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
924 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
925 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
926 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
927 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
928 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
929 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
930 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
931 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
932 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
935 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
936 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
938 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
939 // registers cannot be used even for integer operations.
940 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
941 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
942 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
943 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
945 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
946 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
947 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
948 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
949 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
950 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
951 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
952 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
953 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
954 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
955 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
956 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
957 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
958 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
959 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
960 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
961 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
962 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
963 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
964 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
965 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
966 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
968 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
969 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
970 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
971 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
973 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
974 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
976 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
977 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
979 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
980 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
981 MVT VT = (MVT::SimpleValueType)i;
982 // Do not attempt to custom lower non-power-of-2 vectors
983 if (!isPowerOf2_32(VT.getVectorNumElements()))
985 // Do not attempt to custom lower non-128-bit vectors
986 if (!VT.is128BitVector())
988 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
993 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
994 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
995 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
996 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1000 if (Subtarget->is64Bit()) {
1001 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1005 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1006 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1007 MVT VT = (MVT::SimpleValueType)i;
1009 // Do not attempt to promote non-128-bit vectors
1010 if (!VT.is128BitVector())
1013 setOperationAction(ISD::AND, VT, Promote);
1014 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1015 setOperationAction(ISD::OR, VT, Promote);
1016 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1017 setOperationAction(ISD::XOR, VT, Promote);
1018 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1019 setOperationAction(ISD::LOAD, VT, Promote);
1020 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1021 setOperationAction(ISD::SELECT, VT, Promote);
1022 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1025 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1027 // Custom lower v2i64 and v2f64 selects.
1028 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1029 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1030 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1031 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1033 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1034 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1036 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1037 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1038 // As there is no 64-bit GPR available, we need build a special custom
1039 // sequence to convert from v2i32 to v2f32.
1040 if (!Subtarget->is64Bit())
1041 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1043 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1044 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1046 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1048 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1049 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1050 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1053 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1054 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1057 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1059 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1062 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1068 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1070 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1071 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1072 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1073 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1074 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1076 // FIXME: Do we need to handle scalar-to-vector here?
1077 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1079 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1080 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1081 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1082 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1083 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1084 // There is no BLENDI for byte vectors. We don't need to custom lower
1085 // some vselects for now.
1086 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1088 // i8 and i16 vectors are custom , because the source register and source
1089 // source memory operand types are not the same width. f32 vectors are
1090 // custom since the immediate controlling the insert encodes additional
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1094 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1095 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1099 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1100 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1102 // FIXME: these should be Legal but thats only for the case where
1103 // the index is constant. For now custom expand to deal with that.
1104 if (Subtarget->is64Bit()) {
1105 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1106 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1110 if (Subtarget->hasSSE2()) {
1111 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1114 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1115 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1117 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1118 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1120 // In the customized shift lowering, the legal cases in AVX2 will be
1122 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1123 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1125 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1126 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1128 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1131 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1132 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1136 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1137 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1139 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1140 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1141 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1143 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1152 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1153 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1154 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1156 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1165 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1167 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1169 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1170 // even though v8i16 is a legal type.
1171 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1172 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1173 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1175 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1176 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1177 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1179 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1180 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1182 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1184 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1187 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1188 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1190 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1191 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1195 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1196 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1199 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1200 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1202 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1203 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1204 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1205 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1207 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1208 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1209 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1210 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1211 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1212 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1213 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1214 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1215 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1216 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1217 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1218 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1220 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1221 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1222 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1223 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1224 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1225 setOperationAction(ISD::FMA, MVT::f32, Legal);
1226 setOperationAction(ISD::FMA, MVT::f64, Legal);
1229 if (Subtarget->hasInt256()) {
1230 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1231 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1232 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1233 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1235 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1236 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1237 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1238 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1240 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1241 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1242 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1243 // Don't lower v32i8 because there is no 128-bit byte mul
1245 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1247 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1248 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1250 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1251 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1253 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1254 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1255 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1256 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1258 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1259 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1261 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1263 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1264 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1266 // Don't lower v32i8 because there is no 128-bit byte mul
1269 // In the customized shift lowering, the legal cases in AVX2 will be
1271 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1272 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1274 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1275 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1277 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1279 // Custom lower several nodes for 256-bit types.
1280 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1281 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1282 MVT VT = (MVT::SimpleValueType)i;
1284 // Extract subvector is special because the value type
1285 // (result) is 128-bit but the source is 256-bit wide.
1286 if (VT.is128BitVector())
1287 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1289 // Do not attempt to custom lower other non-256-bit vectors
1290 if (!VT.is256BitVector())
1293 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1294 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1295 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1296 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1297 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1298 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1299 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1302 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1303 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1304 MVT VT = (MVT::SimpleValueType)i;
1306 // Do not attempt to promote non-256-bit vectors
1307 if (!VT.is256BitVector())
1310 setOperationAction(ISD::AND, VT, Promote);
1311 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1312 setOperationAction(ISD::OR, VT, Promote);
1313 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1314 setOperationAction(ISD::XOR, VT, Promote);
1315 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1316 setOperationAction(ISD::LOAD, VT, Promote);
1317 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1318 setOperationAction(ISD::SELECT, VT, Promote);
1319 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1323 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1324 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1325 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1326 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1327 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1329 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1330 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1331 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1333 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1334 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1335 setOperationAction(ISD::XOR, MVT::i1, Legal);
1336 setOperationAction(ISD::OR, MVT::i1, Legal);
1337 setOperationAction(ISD::AND, MVT::i1, Legal);
1338 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1342 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1343 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1345 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1350 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1352 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1356 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1357 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1358 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1361 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1365 if (Subtarget->is64Bit()) {
1366 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1367 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1368 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1371 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1373 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1374 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1379 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1380 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1382 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1385 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1386 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1387 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1388 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1389 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1391 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1392 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1393 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1394 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1396 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1397 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1398 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1399 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1400 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1401 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1403 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1404 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1406 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1408 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1409 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1410 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1411 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1412 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1413 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1414 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1415 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1418 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1419 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1421 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1422 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1424 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1426 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1427 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1429 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1430 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1432 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1435 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1436 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1437 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1438 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1439 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1440 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1442 if (Subtarget->hasCDI()) {
1443 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1444 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1447 // Custom lower several nodes.
1448 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1449 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1450 MVT VT = (MVT::SimpleValueType)i;
1452 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453 // Extract subvector is special because the value type
1454 // (result) is 256/128-bit but the source is 512-bit wide.
1455 if (VT.is128BitVector() || VT.is256BitVector())
1456 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1458 if (VT.getVectorElementType() == MVT::i1)
1459 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1461 // Do not attempt to custom lower other non-512-bit vectors
1462 if (!VT.is512BitVector())
1465 if ( EltSize >= 32) {
1466 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1467 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1468 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1469 setOperationAction(ISD::VSELECT, VT, Legal);
1470 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1471 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1472 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1475 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476 MVT VT = (MVT::SimpleValueType)i;
1478 // Do not attempt to promote non-256-bit vectors
1479 if (!VT.is512BitVector())
1482 setOperationAction(ISD::SELECT, VT, Promote);
1483 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1487 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1488 // of this type with custom code.
1489 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1490 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1491 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1495 // We want to custom lower some of our intrinsics.
1496 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1497 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1498 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1499 if (!Subtarget->is64Bit())
1500 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1502 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1503 // handle type legalization for these operations here.
1505 // FIXME: We really should do custom legalization for addition and
1506 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1507 // than generic legalization for 64-bit multiplication-with-overflow, though.
1508 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1509 // Add/Sub/Mul with overflow operations are custom lowered.
1511 setOperationAction(ISD::SADDO, VT, Custom);
1512 setOperationAction(ISD::UADDO, VT, Custom);
1513 setOperationAction(ISD::SSUBO, VT, Custom);
1514 setOperationAction(ISD::USUBO, VT, Custom);
1515 setOperationAction(ISD::SMULO, VT, Custom);
1516 setOperationAction(ISD::UMULO, VT, Custom);
1519 // There are no 8-bit 3-address imul/mul instructions
1520 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1521 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1523 if (!Subtarget->is64Bit()) {
1524 // These libcalls are not available in 32-bit.
1525 setLibcallName(RTLIB::SHL_I128, nullptr);
1526 setLibcallName(RTLIB::SRL_I128, nullptr);
1527 setLibcallName(RTLIB::SRA_I128, nullptr);
1530 // Combine sin / cos into one node or libcall if possible.
1531 if (Subtarget->hasSinCos()) {
1532 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1533 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1534 if (Subtarget->isTargetDarwin()) {
1535 // For MacOSX, we don't want to the normal expansion of a libcall to
1536 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1538 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1539 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1543 if (Subtarget->isTargetWin64()) {
1544 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1545 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1546 setOperationAction(ISD::SREM, MVT::i128, Custom);
1547 setOperationAction(ISD::UREM, MVT::i128, Custom);
1548 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1549 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1552 // We have target-specific dag combine patterns for the following nodes:
1553 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1554 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1555 setTargetDAGCombine(ISD::VSELECT);
1556 setTargetDAGCombine(ISD::SELECT);
1557 setTargetDAGCombine(ISD::SHL);
1558 setTargetDAGCombine(ISD::SRA);
1559 setTargetDAGCombine(ISD::SRL);
1560 setTargetDAGCombine(ISD::OR);
1561 setTargetDAGCombine(ISD::AND);
1562 setTargetDAGCombine(ISD::ADD);
1563 setTargetDAGCombine(ISD::FADD);
1564 setTargetDAGCombine(ISD::FSUB);
1565 setTargetDAGCombine(ISD::FMA);
1566 setTargetDAGCombine(ISD::SUB);
1567 setTargetDAGCombine(ISD::LOAD);
1568 setTargetDAGCombine(ISD::STORE);
1569 setTargetDAGCombine(ISD::ZERO_EXTEND);
1570 setTargetDAGCombine(ISD::ANY_EXTEND);
1571 setTargetDAGCombine(ISD::SIGN_EXTEND);
1572 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1573 setTargetDAGCombine(ISD::TRUNCATE);
1574 setTargetDAGCombine(ISD::SINT_TO_FP);
1575 setTargetDAGCombine(ISD::SETCC);
1576 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1577 setTargetDAGCombine(ISD::BUILD_VECTOR);
1578 if (Subtarget->is64Bit())
1579 setTargetDAGCombine(ISD::MUL);
1580 setTargetDAGCombine(ISD::XOR);
1582 computeRegisterProperties();
1584 // On Darwin, -Os means optimize for size without hurting performance,
1585 // do not reduce the limit.
1586 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1587 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1588 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1589 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1590 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1591 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1592 setPrefLoopAlignment(4); // 2^4 bytes.
1594 // Predictable cmov don't hurt on atom because it's in-order.
1595 PredictableSelectIsExpensive = !Subtarget->isAtom();
1597 setPrefFunctionAlignment(4); // 2^4 bytes.
1600 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1602 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1604 if (Subtarget->hasAVX512())
1605 switch(VT.getVectorNumElements()) {
1606 case 8: return MVT::v8i1;
1607 case 16: return MVT::v16i1;
1610 return VT.changeVectorElementTypeToInteger();
1613 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1614 /// the desired ByVal argument alignment.
1615 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1618 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1619 if (VTy->getBitWidth() == 128)
1621 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1622 unsigned EltAlign = 0;
1623 getMaxByValAlign(ATy->getElementType(), EltAlign);
1624 if (EltAlign > MaxAlign)
1625 MaxAlign = EltAlign;
1626 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1627 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1628 unsigned EltAlign = 0;
1629 getMaxByValAlign(STy->getElementType(i), EltAlign);
1630 if (EltAlign > MaxAlign)
1631 MaxAlign = EltAlign;
1638 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1639 /// function arguments in the caller parameter area. For X86, aggregates
1640 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1641 /// are at 4-byte boundaries.
1642 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1643 if (Subtarget->is64Bit()) {
1644 // Max of 8 and alignment of type.
1645 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1652 if (Subtarget->hasSSE1())
1653 getMaxByValAlign(Ty, Align);
1657 /// getOptimalMemOpType - Returns the target specific optimal type for load
1658 /// and store operations as a result of memset, memcpy, and memmove
1659 /// lowering. If DstAlign is zero that means it's safe to destination
1660 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1661 /// means there isn't a need to check it against alignment requirement,
1662 /// probably because the source does not need to be loaded. If 'IsMemset' is
1663 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1664 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1665 /// source is constant so it does not need to be loaded.
1666 /// It returns EVT::Other if the type should be determined using generic
1667 /// target-independent logic.
1669 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1670 unsigned DstAlign, unsigned SrcAlign,
1671 bool IsMemset, bool ZeroMemset,
1673 MachineFunction &MF) const {
1674 const Function *F = MF.getFunction();
1675 if ((!IsMemset || ZeroMemset) &&
1676 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1677 Attribute::NoImplicitFloat)) {
1679 (Subtarget->isUnalignedMemAccessFast() ||
1680 ((DstAlign == 0 || DstAlign >= 16) &&
1681 (SrcAlign == 0 || SrcAlign >= 16)))) {
1683 if (Subtarget->hasInt256())
1685 if (Subtarget->hasFp256())
1688 if (Subtarget->hasSSE2())
1690 if (Subtarget->hasSSE1())
1692 } else if (!MemcpyStrSrc && Size >= 8 &&
1693 !Subtarget->is64Bit() &&
1694 Subtarget->hasSSE2()) {
1695 // Do not use f64 to lower memcpy if source is string constant. It's
1696 // better to use i32 to avoid the loads.
1700 if (Subtarget->is64Bit() && Size >= 8)
1705 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1707 return X86ScalarSSEf32;
1708 else if (VT == MVT::f64)
1709 return X86ScalarSSEf64;
1714 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1718 *Fast = Subtarget->isUnalignedMemAccessFast();
1722 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1723 /// current function. The returned value is a member of the
1724 /// MachineJumpTableInfo::JTEntryKind enum.
1725 unsigned X86TargetLowering::getJumpTableEncoding() const {
1726 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1728 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1729 Subtarget->isPICStyleGOT())
1730 return MachineJumpTableInfo::EK_Custom32;
1732 // Otherwise, use the normal jump table encoding heuristics.
1733 return TargetLowering::getJumpTableEncoding();
1737 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1738 const MachineBasicBlock *MBB,
1739 unsigned uid,MCContext &Ctx) const{
1740 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1741 Subtarget->isPICStyleGOT());
1742 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1744 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1745 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1748 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1750 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1751 SelectionDAG &DAG) const {
1752 if (!Subtarget->is64Bit())
1753 // This doesn't have SDLoc associated with it, but is not really the
1754 // same as a Register.
1755 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1759 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1760 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1762 const MCExpr *X86TargetLowering::
1763 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1764 MCContext &Ctx) const {
1765 // X86-64 uses RIP relative addressing based on the jump table label.
1766 if (Subtarget->isPICStyleRIPRel())
1767 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1769 // Otherwise, the reference is relative to the PIC base.
1770 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1773 // FIXME: Why this routine is here? Move to RegInfo!
1774 std::pair<const TargetRegisterClass*, uint8_t>
1775 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1776 const TargetRegisterClass *RRC = nullptr;
1778 switch (VT.SimpleTy) {
1780 return TargetLowering::findRepresentativeClass(VT);
1781 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1782 RRC = Subtarget->is64Bit() ?
1783 (const TargetRegisterClass*)&X86::GR64RegClass :
1784 (const TargetRegisterClass*)&X86::GR32RegClass;
1787 RRC = &X86::VR64RegClass;
1789 case MVT::f32: case MVT::f64:
1790 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1791 case MVT::v4f32: case MVT::v2f64:
1792 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1794 RRC = &X86::VR128RegClass;
1797 return std::make_pair(RRC, Cost);
1800 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1801 unsigned &Offset) const {
1802 if (!Subtarget->isTargetLinux())
1805 if (Subtarget->is64Bit()) {
1806 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1808 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1820 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1821 unsigned DestAS) const {
1822 assert(SrcAS != DestAS && "Expected different address spaces!");
1824 return SrcAS < 256 && DestAS < 256;
1827 //===----------------------------------------------------------------------===//
1828 // Return Value Calling Convention Implementation
1829 //===----------------------------------------------------------------------===//
1831 #include "X86GenCallingConv.inc"
1834 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1835 MachineFunction &MF, bool isVarArg,
1836 const SmallVectorImpl<ISD::OutputArg> &Outs,
1837 LLVMContext &Context) const {
1838 SmallVector<CCValAssign, 16> RVLocs;
1839 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1841 return CCInfo.CheckReturn(Outs, RetCC_X86);
1844 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1845 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1850 X86TargetLowering::LowerReturn(SDValue Chain,
1851 CallingConv::ID CallConv, bool isVarArg,
1852 const SmallVectorImpl<ISD::OutputArg> &Outs,
1853 const SmallVectorImpl<SDValue> &OutVals,
1854 SDLoc dl, SelectionDAG &DAG) const {
1855 MachineFunction &MF = DAG.getMachineFunction();
1856 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1858 SmallVector<CCValAssign, 16> RVLocs;
1859 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1860 RVLocs, *DAG.getContext());
1861 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1864 SmallVector<SDValue, 6> RetOps;
1865 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1866 // Operand #1 = Bytes To Pop
1867 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1870 // Copy the result values into the output registers.
1871 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1872 CCValAssign &VA = RVLocs[i];
1873 assert(VA.isRegLoc() && "Can only return in registers!");
1874 SDValue ValToCopy = OutVals[i];
1875 EVT ValVT = ValToCopy.getValueType();
1877 // Promote values to the appropriate types
1878 if (VA.getLocInfo() == CCValAssign::SExt)
1879 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1880 else if (VA.getLocInfo() == CCValAssign::ZExt)
1881 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1882 else if (VA.getLocInfo() == CCValAssign::AExt)
1883 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1884 else if (VA.getLocInfo() == CCValAssign::BCvt)
1885 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1887 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1888 "Unexpected FP-extend for return value.");
1890 // If this is x86-64, and we disabled SSE, we can't return FP values,
1891 // or SSE or MMX vectors.
1892 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1893 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1894 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1895 report_fatal_error("SSE register return with SSE disabled");
1897 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1898 // llvm-gcc has never done it right and no one has noticed, so this
1899 // should be OK for now.
1900 if (ValVT == MVT::f64 &&
1901 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1902 report_fatal_error("SSE2 register return with SSE2 disabled");
1904 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1905 // the RET instruction and handled by the FP Stackifier.
1906 if (VA.getLocReg() == X86::ST0 ||
1907 VA.getLocReg() == X86::ST1) {
1908 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1909 // change the value to the FP stack register class.
1910 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1911 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1912 RetOps.push_back(ValToCopy);
1913 // Don't emit a copytoreg.
1917 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1918 // which is returned in RAX / RDX.
1919 if (Subtarget->is64Bit()) {
1920 if (ValVT == MVT::x86mmx) {
1921 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1922 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1923 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1925 // If we don't have SSE2 available, convert to v4f32 so the generated
1926 // register is legal.
1927 if (!Subtarget->hasSSE2())
1928 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1933 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1934 Flag = Chain.getValue(1);
1935 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1938 // The x86-64 ABIs require that for returning structs by value we copy
1939 // the sret argument into %rax/%eax (depending on ABI) for the return.
1940 // Win32 requires us to put the sret argument to %eax as well.
1941 // We saved the argument into a virtual register in the entry block,
1942 // so now we copy the value out and into %rax/%eax.
1943 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1944 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1945 MachineFunction &MF = DAG.getMachineFunction();
1946 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1947 unsigned Reg = FuncInfo->getSRetReturnReg();
1949 "SRetReturnReg should have been set in LowerFormalArguments().");
1950 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1953 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1954 X86::RAX : X86::EAX;
1955 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1956 Flag = Chain.getValue(1);
1958 // RAX/EAX now acts like a return value.
1959 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1962 RetOps[0] = Chain; // Update chain.
1964 // Add the flag if we have it.
1966 RetOps.push_back(Flag);
1968 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1971 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1972 if (N->getNumValues() != 1)
1974 if (!N->hasNUsesOfValue(1, 0))
1977 SDValue TCChain = Chain;
1978 SDNode *Copy = *N->use_begin();
1979 if (Copy->getOpcode() == ISD::CopyToReg) {
1980 // If the copy has a glue operand, we conservatively assume it isn't safe to
1981 // perform a tail call.
1982 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1984 TCChain = Copy->getOperand(0);
1985 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1988 bool HasRet = false;
1989 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1991 if (UI->getOpcode() != X86ISD::RET_FLAG)
2004 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2005 ISD::NodeType ExtendKind) const {
2007 // TODO: Is this also valid on 32-bit?
2008 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2009 ReturnMVT = MVT::i8;
2011 ReturnMVT = MVT::i32;
2013 MVT MinVT = getRegisterType(ReturnMVT);
2014 return VT.bitsLT(MinVT) ? MinVT : VT;
2017 /// LowerCallResult - Lower the result values of a call into the
2018 /// appropriate copies out of appropriate physical registers.
2021 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2022 CallingConv::ID CallConv, bool isVarArg,
2023 const SmallVectorImpl<ISD::InputArg> &Ins,
2024 SDLoc dl, SelectionDAG &DAG,
2025 SmallVectorImpl<SDValue> &InVals) const {
2027 // Assign locations to each value returned by this call.
2028 SmallVector<CCValAssign, 16> RVLocs;
2029 bool Is64Bit = Subtarget->is64Bit();
2030 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2031 DAG.getTarget(), RVLocs, *DAG.getContext());
2032 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2034 // Copy all of the result registers out of their specified physreg.
2035 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2036 CCValAssign &VA = RVLocs[i];
2037 EVT CopyVT = VA.getValVT();
2039 // If this is x86-64, and we disabled SSE, we can't return FP values
2040 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2041 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2042 report_fatal_error("SSE register return with SSE disabled");
2047 // If this is a call to a function that returns an fp value on the floating
2048 // point stack, we must guarantee the value is popped from the stack, so
2049 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2050 // if the return value is not used. We use the FpPOP_RETVAL instruction
2052 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2053 // If we prefer to use the value in xmm registers, copy it out as f80 and
2054 // use a truncate to move it from fp stack reg to xmm reg.
2055 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2056 SDValue Ops[] = { Chain, InFlag };
2057 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2058 MVT::Other, MVT::Glue, Ops), 1);
2059 Val = Chain.getValue(0);
2061 // Round the f80 to the right size, which also moves it to the appropriate
2063 if (CopyVT != VA.getValVT())
2064 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2065 // This truncation won't change the value.
2066 DAG.getIntPtrConstant(1));
2068 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2069 CopyVT, InFlag).getValue(1);
2070 Val = Chain.getValue(0);
2072 InFlag = Chain.getValue(2);
2073 InVals.push_back(Val);
2079 //===----------------------------------------------------------------------===//
2080 // C & StdCall & Fast Calling Convention implementation
2081 //===----------------------------------------------------------------------===//
2082 // StdCall calling convention seems to be standard for many Windows' API
2083 // routines and around. It differs from C calling convention just a little:
2084 // callee should clean up the stack, not caller. Symbols should be also
2085 // decorated in some fancy way :) It doesn't support any vector arguments.
2086 // For info on fast calling convention see Fast Calling Convention (tail call)
2087 // implementation LowerX86_32FastCCCallTo.
2089 /// CallIsStructReturn - Determines whether a call uses struct return
2091 enum StructReturnType {
2096 static StructReturnType
2097 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2099 return NotStructReturn;
2101 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2102 if (!Flags.isSRet())
2103 return NotStructReturn;
2104 if (Flags.isInReg())
2105 return RegStructReturn;
2106 return StackStructReturn;
2109 /// ArgsAreStructReturn - Determines whether a function uses struct
2110 /// return semantics.
2111 static StructReturnType
2112 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2114 return NotStructReturn;
2116 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2117 if (!Flags.isSRet())
2118 return NotStructReturn;
2119 if (Flags.isInReg())
2120 return RegStructReturn;
2121 return StackStructReturn;
2124 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2125 /// by "Src" to address "Dst" with size and alignment information specified by
2126 /// the specific parameter attribute. The copy will be passed as a byval
2127 /// function parameter.
2129 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2130 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2132 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2134 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2135 /*isVolatile*/false, /*AlwaysInline=*/true,
2136 MachinePointerInfo(), MachinePointerInfo());
2139 /// IsTailCallConvention - Return true if the calling convention is one that
2140 /// supports tail call optimization.
2141 static bool IsTailCallConvention(CallingConv::ID CC) {
2142 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2143 CC == CallingConv::HiPE);
2146 /// \brief Return true if the calling convention is a C calling convention.
2147 static bool IsCCallConvention(CallingConv::ID CC) {
2148 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2149 CC == CallingConv::X86_64_SysV);
2152 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2153 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2157 CallingConv::ID CalleeCC = CS.getCallingConv();
2158 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2164 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2165 /// a tailcall target by changing its ABI.
2166 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2167 bool GuaranteedTailCallOpt) {
2168 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2172 X86TargetLowering::LowerMemArgument(SDValue Chain,
2173 CallingConv::ID CallConv,
2174 const SmallVectorImpl<ISD::InputArg> &Ins,
2175 SDLoc dl, SelectionDAG &DAG,
2176 const CCValAssign &VA,
2177 MachineFrameInfo *MFI,
2179 // Create the nodes corresponding to a load from this parameter slot.
2180 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2181 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2182 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2183 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2186 // If value is passed by pointer we have address passed instead of the value
2188 if (VA.getLocInfo() == CCValAssign::Indirect)
2189 ValVT = VA.getLocVT();
2191 ValVT = VA.getValVT();
2193 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2194 // changed with more analysis.
2195 // In case of tail call optimization mark all arguments mutable. Since they
2196 // could be overwritten by lowering of arguments in case of a tail call.
2197 if (Flags.isByVal()) {
2198 unsigned Bytes = Flags.getByValSize();
2199 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2200 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2201 return DAG.getFrameIndex(FI, getPointerTy());
2203 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2204 VA.getLocMemOffset(), isImmutable);
2205 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2206 return DAG.getLoad(ValVT, dl, Chain, FIN,
2207 MachinePointerInfo::getFixedStack(FI),
2208 false, false, false, 0);
2213 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2214 CallingConv::ID CallConv,
2216 const SmallVectorImpl<ISD::InputArg> &Ins,
2219 SmallVectorImpl<SDValue> &InVals)
2221 MachineFunction &MF = DAG.getMachineFunction();
2222 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2224 const Function* Fn = MF.getFunction();
2225 if (Fn->hasExternalLinkage() &&
2226 Subtarget->isTargetCygMing() &&
2227 Fn->getName() == "main")
2228 FuncInfo->setForceFramePointer(true);
2230 MachineFrameInfo *MFI = MF.getFrameInfo();
2231 bool Is64Bit = Subtarget->is64Bit();
2232 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2234 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2235 "Var args not supported with calling convention fastcc, ghc or hipe");
2237 // Assign locations to all of the incoming arguments.
2238 SmallVector<CCValAssign, 16> ArgLocs;
2239 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2240 ArgLocs, *DAG.getContext());
2242 // Allocate shadow area for Win64
2244 CCInfo.AllocateStack(32, 8);
2246 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2248 unsigned LastVal = ~0U;
2250 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2251 CCValAssign &VA = ArgLocs[i];
2252 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2254 assert(VA.getValNo() != LastVal &&
2255 "Don't support value assigned to multiple locs yet");
2257 LastVal = VA.getValNo();
2259 if (VA.isRegLoc()) {
2260 EVT RegVT = VA.getLocVT();
2261 const TargetRegisterClass *RC;
2262 if (RegVT == MVT::i32)
2263 RC = &X86::GR32RegClass;
2264 else if (Is64Bit && RegVT == MVT::i64)
2265 RC = &X86::GR64RegClass;
2266 else if (RegVT == MVT::f32)
2267 RC = &X86::FR32RegClass;
2268 else if (RegVT == MVT::f64)
2269 RC = &X86::FR64RegClass;
2270 else if (RegVT.is512BitVector())
2271 RC = &X86::VR512RegClass;
2272 else if (RegVT.is256BitVector())
2273 RC = &X86::VR256RegClass;
2274 else if (RegVT.is128BitVector())
2275 RC = &X86::VR128RegClass;
2276 else if (RegVT == MVT::x86mmx)
2277 RC = &X86::VR64RegClass;
2278 else if (RegVT == MVT::i1)
2279 RC = &X86::VK1RegClass;
2280 else if (RegVT == MVT::v8i1)
2281 RC = &X86::VK8RegClass;
2282 else if (RegVT == MVT::v16i1)
2283 RC = &X86::VK16RegClass;
2285 llvm_unreachable("Unknown argument type!");
2287 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2288 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2290 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2291 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2293 if (VA.getLocInfo() == CCValAssign::SExt)
2294 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2295 DAG.getValueType(VA.getValVT()));
2296 else if (VA.getLocInfo() == CCValAssign::ZExt)
2297 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2298 DAG.getValueType(VA.getValVT()));
2299 else if (VA.getLocInfo() == CCValAssign::BCvt)
2300 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2302 if (VA.isExtInLoc()) {
2303 // Handle MMX values passed in XMM regs.
2304 if (RegVT.isVector())
2305 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2307 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2310 assert(VA.isMemLoc());
2311 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2314 // If value is passed via pointer - do a load.
2315 if (VA.getLocInfo() == CCValAssign::Indirect)
2316 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2317 MachinePointerInfo(), false, false, false, 0);
2319 InVals.push_back(ArgValue);
2322 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2323 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2324 // The x86-64 ABIs require that for returning structs by value we copy
2325 // the sret argument into %rax/%eax (depending on ABI) for the return.
2326 // Win32 requires us to put the sret argument to %eax as well.
2327 // Save the argument into a virtual register so that we can access it
2328 // from the return points.
2329 if (Ins[i].Flags.isSRet()) {
2330 unsigned Reg = FuncInfo->getSRetReturnReg();
2332 MVT PtrTy = getPointerTy();
2333 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2334 FuncInfo->setSRetReturnReg(Reg);
2336 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2337 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2343 unsigned StackSize = CCInfo.getNextStackOffset();
2344 // Align stack specially for tail calls.
2345 if (FuncIsMadeTailCallSafe(CallConv,
2346 MF.getTarget().Options.GuaranteedTailCallOpt))
2347 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2349 // If the function takes variable number of arguments, make a frame index for
2350 // the start of the first vararg value... for expansion of llvm.va_start.
2352 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2353 CallConv != CallingConv::X86_ThisCall)) {
2354 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2357 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2359 // FIXME: We should really autogenerate these arrays
2360 static const MCPhysReg GPR64ArgRegsWin64[] = {
2361 X86::RCX, X86::RDX, X86::R8, X86::R9
2363 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2364 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2366 static const MCPhysReg XMMArgRegs64Bit[] = {
2367 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2368 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2370 const MCPhysReg *GPR64ArgRegs;
2371 unsigned NumXMMRegs = 0;
2374 // The XMM registers which might contain var arg parameters are shadowed
2375 // in their paired GPR. So we only need to save the GPR to their home
2377 TotalNumIntRegs = 4;
2378 GPR64ArgRegs = GPR64ArgRegsWin64;
2380 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2381 GPR64ArgRegs = GPR64ArgRegs64Bit;
2383 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2386 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2389 bool NoImplicitFloatOps = Fn->getAttributes().
2390 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2391 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2392 "SSE register cannot be used when SSE is disabled!");
2393 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2394 NoImplicitFloatOps) &&
2395 "SSE register cannot be used when SSE is disabled!");
2396 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397 !Subtarget->hasSSE1())
2398 // Kernel mode asks for SSE to be disabled, so don't push them
2400 TotalNumXMMRegs = 0;
2403 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2404 // Get to the caller-allocated home save location. Add 8 to account
2405 // for the return address.
2406 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2407 FuncInfo->setRegSaveFrameIndex(
2408 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2409 // Fixup to set vararg frame on shadow area (4 x i64).
2411 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2413 // For X86-64, if there are vararg parameters that are passed via
2414 // registers, then we must store them to their spots on the stack so
2415 // they may be loaded by deferencing the result of va_next.
2416 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2417 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2418 FuncInfo->setRegSaveFrameIndex(
2419 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2423 // Store the integer parameter registers.
2424 SmallVector<SDValue, 8> MemOps;
2425 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2427 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2428 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2429 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2430 DAG.getIntPtrConstant(Offset));
2431 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2432 &X86::GR64RegClass);
2433 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2435 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2436 MachinePointerInfo::getFixedStack(
2437 FuncInfo->getRegSaveFrameIndex(), Offset),
2439 MemOps.push_back(Store);
2443 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2444 // Now store the XMM (fp + vector) parameter registers.
2445 SmallVector<SDValue, 11> SaveXMMOps;
2446 SaveXMMOps.push_back(Chain);
2448 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2449 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2450 SaveXMMOps.push_back(ALVal);
2452 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2453 FuncInfo->getRegSaveFrameIndex()));
2454 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2455 FuncInfo->getVarArgsFPOffset()));
2457 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2458 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2459 &X86::VR128RegClass);
2460 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2461 SaveXMMOps.push_back(Val);
2463 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2464 MVT::Other, SaveXMMOps));
2467 if (!MemOps.empty())
2468 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2472 // Some CCs need callee pop.
2473 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2474 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2475 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2477 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2478 // If this is an sret function, the return should pop the hidden pointer.
2479 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2480 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2481 argsAreStructReturn(Ins) == StackStructReturn)
2482 FuncInfo->setBytesToPopOnReturn(4);
2486 // RegSaveFrameIndex is X86-64 only.
2487 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2488 if (CallConv == CallingConv::X86_FastCall ||
2489 CallConv == CallingConv::X86_ThisCall)
2490 // fastcc functions can't have varargs.
2491 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2494 FuncInfo->setArgumentStackSize(StackSize);
2500 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2501 SDValue StackPtr, SDValue Arg,
2502 SDLoc dl, SelectionDAG &DAG,
2503 const CCValAssign &VA,
2504 ISD::ArgFlagsTy Flags) const {
2505 unsigned LocMemOffset = VA.getLocMemOffset();
2506 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2507 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2508 if (Flags.isByVal())
2509 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2511 return DAG.getStore(Chain, dl, Arg, PtrOff,
2512 MachinePointerInfo::getStack(LocMemOffset),
2516 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2517 /// optimization is performed and it is required.
2519 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2520 SDValue &OutRetAddr, SDValue Chain,
2521 bool IsTailCall, bool Is64Bit,
2522 int FPDiff, SDLoc dl) const {
2523 // Adjust the Return address stack slot.
2524 EVT VT = getPointerTy();
2525 OutRetAddr = getReturnAddressFrameIndex(DAG);
2527 // Load the "old" Return address.
2528 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2529 false, false, false, 0);
2530 return SDValue(OutRetAddr.getNode(), 1);
2533 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2534 /// optimization is performed and it is required (FPDiff!=0).
2535 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2536 SDValue Chain, SDValue RetAddrFrIdx,
2537 EVT PtrVT, unsigned SlotSize,
2538 int FPDiff, SDLoc dl) {
2539 // Store the return address to the appropriate stack slot.
2540 if (!FPDiff) return Chain;
2541 // Calculate the new stack slot for the return address.
2542 int NewReturnAddrFI =
2543 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2545 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2546 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2547 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2553 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2554 SmallVectorImpl<SDValue> &InVals) const {
2555 SelectionDAG &DAG = CLI.DAG;
2557 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2558 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2559 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2560 SDValue Chain = CLI.Chain;
2561 SDValue Callee = CLI.Callee;
2562 CallingConv::ID CallConv = CLI.CallConv;
2563 bool &isTailCall = CLI.IsTailCall;
2564 bool isVarArg = CLI.IsVarArg;
2566 MachineFunction &MF = DAG.getMachineFunction();
2567 bool Is64Bit = Subtarget->is64Bit();
2568 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2569 StructReturnType SR = callIsStructReturn(Outs);
2570 bool IsSibcall = false;
2572 if (MF.getTarget().Options.DisableTailCalls)
2575 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2577 // Force this to be a tail call. The verifier rules are enough to ensure
2578 // that we can lower this successfully without moving the return address
2581 } else if (isTailCall) {
2582 // Check if it's really possible to do a tail call.
2583 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2584 isVarArg, SR != NotStructReturn,
2585 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2586 Outs, OutVals, Ins, DAG);
2588 // Sibcalls are automatically detected tailcalls which do not require
2590 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2597 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2598 "Var args not supported with calling convention fastcc, ghc or hipe");
2600 // Analyze operands of the call, assigning locations to each operand.
2601 SmallVector<CCValAssign, 16> ArgLocs;
2602 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2603 ArgLocs, *DAG.getContext());
2605 // Allocate shadow area for Win64
2607 CCInfo.AllocateStack(32, 8);
2609 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2611 // Get a count of how many bytes are to be pushed on the stack.
2612 unsigned NumBytes = CCInfo.getNextStackOffset();
2614 // This is a sibcall. The memory operands are available in caller's
2615 // own caller's stack.
2617 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2618 IsTailCallConvention(CallConv))
2619 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2622 if (isTailCall && !IsSibcall && !IsMustTail) {
2623 // Lower arguments at fp - stackoffset + fpdiff.
2624 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2625 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2627 FPDiff = NumBytesCallerPushed - NumBytes;
2629 // Set the delta of movement of the returnaddr stackslot.
2630 // But only set if delta is greater than previous delta.
2631 if (FPDiff < X86Info->getTCReturnAddrDelta())
2632 X86Info->setTCReturnAddrDelta(FPDiff);
2635 unsigned NumBytesToPush = NumBytes;
2636 unsigned NumBytesToPop = NumBytes;
2638 // If we have an inalloca argument, all stack space has already been allocated
2639 // for us and be right at the top of the stack. We don't support multiple
2640 // arguments passed in memory when using inalloca.
2641 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2643 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2644 "an inalloca argument must be the only memory argument");
2648 Chain = DAG.getCALLSEQ_START(
2649 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2651 SDValue RetAddrFrIdx;
2652 // Load return address for tail calls.
2653 if (isTailCall && FPDiff)
2654 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2655 Is64Bit, FPDiff, dl);
2657 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2658 SmallVector<SDValue, 8> MemOpChains;
2661 // Walk the register/memloc assignments, inserting copies/loads. In the case
2662 // of tail call optimization arguments are handle later.
2663 const X86RegisterInfo *RegInfo =
2664 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2665 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2666 // Skip inalloca arguments, they have already been written.
2667 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2668 if (Flags.isInAlloca())
2671 CCValAssign &VA = ArgLocs[i];
2672 EVT RegVT = VA.getLocVT();
2673 SDValue Arg = OutVals[i];
2674 bool isByVal = Flags.isByVal();
2676 // Promote the value if needed.
2677 switch (VA.getLocInfo()) {
2678 default: llvm_unreachable("Unknown loc info!");
2679 case CCValAssign::Full: break;
2680 case CCValAssign::SExt:
2681 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2683 case CCValAssign::ZExt:
2684 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2686 case CCValAssign::AExt:
2687 if (RegVT.is128BitVector()) {
2688 // Special case: passing MMX values in XMM registers.
2689 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2690 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2691 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2693 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2695 case CCValAssign::BCvt:
2696 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2698 case CCValAssign::Indirect: {
2699 // Store the argument.
2700 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2701 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2702 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2703 MachinePointerInfo::getFixedStack(FI),
2710 if (VA.isRegLoc()) {
2711 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2712 if (isVarArg && IsWin64) {
2713 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2714 // shadow reg if callee is a varargs function.
2715 unsigned ShadowReg = 0;
2716 switch (VA.getLocReg()) {
2717 case X86::XMM0: ShadowReg = X86::RCX; break;
2718 case X86::XMM1: ShadowReg = X86::RDX; break;
2719 case X86::XMM2: ShadowReg = X86::R8; break;
2720 case X86::XMM3: ShadowReg = X86::R9; break;
2723 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2725 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2726 assert(VA.isMemLoc());
2727 if (!StackPtr.getNode())
2728 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2730 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2731 dl, DAG, VA, Flags));
2735 if (!MemOpChains.empty())
2736 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2738 if (Subtarget->isPICStyleGOT()) {
2739 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2742 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2743 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2745 // If we are tail calling and generating PIC/GOT style code load the
2746 // address of the callee into ECX. The value in ecx is used as target of
2747 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2748 // for tail calls on PIC/GOT architectures. Normally we would just put the
2749 // address of GOT into ebx and then call target@PLT. But for tail calls
2750 // ebx would be restored (since ebx is callee saved) before jumping to the
2753 // Note: The actual moving to ECX is done further down.
2754 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2755 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2756 !G->getGlobal()->hasProtectedVisibility())
2757 Callee = LowerGlobalAddress(Callee, DAG);
2758 else if (isa<ExternalSymbolSDNode>(Callee))
2759 Callee = LowerExternalSymbol(Callee, DAG);
2763 if (Is64Bit && isVarArg && !IsWin64) {
2764 // From AMD64 ABI document:
2765 // For calls that may call functions that use varargs or stdargs
2766 // (prototype-less calls or calls to functions containing ellipsis (...) in
2767 // the declaration) %al is used as hidden argument to specify the number
2768 // of SSE registers used. The contents of %al do not need to match exactly
2769 // the number of registers, but must be an ubound on the number of SSE
2770 // registers used and is in the range 0 - 8 inclusive.
2772 // Count the number of XMM registers allocated.
2773 static const MCPhysReg XMMArgRegs[] = {
2774 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2775 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2777 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2778 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2779 && "SSE registers cannot be used when SSE is disabled");
2781 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2782 DAG.getConstant(NumXMMRegs, MVT::i8)));
2785 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2786 // don't need this because the eligibility check rejects calls that require
2787 // shuffling arguments passed in memory.
2788 if (!IsSibcall && isTailCall) {
2789 // Force all the incoming stack arguments to be loaded from the stack
2790 // before any new outgoing arguments are stored to the stack, because the
2791 // outgoing stack slots may alias the incoming argument stack slots, and
2792 // the alias isn't otherwise explicit. This is slightly more conservative
2793 // than necessary, because it means that each store effectively depends
2794 // on every argument instead of just those arguments it would clobber.
2795 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2797 SmallVector<SDValue, 8> MemOpChains2;
2800 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2801 CCValAssign &VA = ArgLocs[i];
2804 assert(VA.isMemLoc());
2805 SDValue Arg = OutVals[i];
2806 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2807 // Skip inalloca arguments. They don't require any work.
2808 if (Flags.isInAlloca())
2810 // Create frame index.
2811 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2812 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2813 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2814 FIN = DAG.getFrameIndex(FI, getPointerTy());
2816 if (Flags.isByVal()) {
2817 // Copy relative to framepointer.
2818 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2819 if (!StackPtr.getNode())
2820 StackPtr = DAG.getCopyFromReg(Chain, dl,
2821 RegInfo->getStackRegister(),
2823 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2825 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2829 // Store relative to framepointer.
2830 MemOpChains2.push_back(
2831 DAG.getStore(ArgChain, dl, Arg, FIN,
2832 MachinePointerInfo::getFixedStack(FI),
2837 if (!MemOpChains2.empty())
2838 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2840 // Store the return address to the appropriate stack slot.
2841 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2842 getPointerTy(), RegInfo->getSlotSize(),
2846 // Build a sequence of copy-to-reg nodes chained together with token chain
2847 // and flag operands which copy the outgoing args into registers.
2849 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2850 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2851 RegsToPass[i].second, InFlag);
2852 InFlag = Chain.getValue(1);
2855 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2856 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2857 // In the 64-bit large code model, we have to make all calls
2858 // through a register, since the call instruction's 32-bit
2859 // pc-relative offset may not be large enough to hold the whole
2861 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2862 // If the callee is a GlobalAddress node (quite common, every direct call
2863 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2866 // We should use extra load for direct calls to dllimported functions in
2868 const GlobalValue *GV = G->getGlobal();
2869 if (!GV->hasDLLImportStorageClass()) {
2870 unsigned char OpFlags = 0;
2871 bool ExtraLoad = false;
2872 unsigned WrapperKind = ISD::DELETED_NODE;
2874 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2875 // external symbols most go through the PLT in PIC mode. If the symbol
2876 // has hidden or protected visibility, or if it is static or local, then
2877 // we don't need to use the PLT - we can directly call it.
2878 if (Subtarget->isTargetELF() &&
2879 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2880 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2881 OpFlags = X86II::MO_PLT;
2882 } else if (Subtarget->isPICStyleStubAny() &&
2883 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2884 (!Subtarget->getTargetTriple().isMacOSX() ||
2885 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886 // PC-relative references to external symbols should go through $stub,
2887 // unless we're building with the leopard linker or later, which
2888 // automatically synthesizes these stubs.
2889 OpFlags = X86II::MO_DARWIN_STUB;
2890 } else if (Subtarget->isPICStyleRIPRel() &&
2891 isa<Function>(GV) &&
2892 cast<Function>(GV)->getAttributes().
2893 hasAttribute(AttributeSet::FunctionIndex,
2894 Attribute::NonLazyBind)) {
2895 // If the function is marked as non-lazy, generate an indirect call
2896 // which loads from the GOT directly. This avoids runtime overhead
2897 // at the cost of eager binding (and one extra byte of encoding).
2898 OpFlags = X86II::MO_GOTPCREL;
2899 WrapperKind = X86ISD::WrapperRIP;
2903 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2904 G->getOffset(), OpFlags);
2906 // Add a wrapper if needed.
2907 if (WrapperKind != ISD::DELETED_NODE)
2908 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2909 // Add extra indirection if needed.
2911 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2912 MachinePointerInfo::getGOT(),
2913 false, false, false, 0);
2915 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2916 unsigned char OpFlags = 0;
2918 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2919 // external symbols should go through the PLT.
2920 if (Subtarget->isTargetELF() &&
2921 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2922 OpFlags = X86II::MO_PLT;
2923 } else if (Subtarget->isPICStyleStubAny() &&
2924 (!Subtarget->getTargetTriple().isMacOSX() ||
2925 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2926 // PC-relative references to external symbols should go through $stub,
2927 // unless we're building with the leopard linker or later, which
2928 // automatically synthesizes these stubs.
2929 OpFlags = X86II::MO_DARWIN_STUB;
2932 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2936 // Returns a chain & a flag for retval copy to use.
2937 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2938 SmallVector<SDValue, 8> Ops;
2940 if (!IsSibcall && isTailCall) {
2941 Chain = DAG.getCALLSEQ_END(Chain,
2942 DAG.getIntPtrConstant(NumBytesToPop, true),
2943 DAG.getIntPtrConstant(0, true), InFlag, dl);
2944 InFlag = Chain.getValue(1);
2947 Ops.push_back(Chain);
2948 Ops.push_back(Callee);
2951 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2953 // Add argument registers to the end of the list so that they are known live
2955 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2956 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2957 RegsToPass[i].second.getValueType()));
2959 // Add a register mask operand representing the call-preserved registers.
2960 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2961 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2962 assert(Mask && "Missing call preserved mask for calling convention");
2963 Ops.push_back(DAG.getRegisterMask(Mask));
2965 if (InFlag.getNode())
2966 Ops.push_back(InFlag);
2970 //// If this is the first return lowered for this function, add the regs
2971 //// to the liveout set for the function.
2972 // This isn't right, although it's probably harmless on x86; liveouts
2973 // should be computed from returns not tail calls. Consider a void
2974 // function making a tail call to a function returning int.
2975 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2978 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2979 InFlag = Chain.getValue(1);
2981 // Create the CALLSEQ_END node.
2982 unsigned NumBytesForCalleeToPop;
2983 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2984 DAG.getTarget().Options.GuaranteedTailCallOpt))
2985 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2986 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2987 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2988 SR == StackStructReturn)
2989 // If this is a call to a struct-return function, the callee
2990 // pops the hidden struct pointer, so we have to push it back.
2991 // This is common for Darwin/X86, Linux & Mingw32 targets.
2992 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2993 NumBytesForCalleeToPop = 4;
2995 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2997 // Returns a flag for retval copy to use.
2999 Chain = DAG.getCALLSEQ_END(Chain,
3000 DAG.getIntPtrConstant(NumBytesToPop, true),
3001 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3004 InFlag = Chain.getValue(1);
3007 // Handle result values, copying them out of physregs into vregs that we
3009 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3010 Ins, dl, DAG, InVals);
3013 //===----------------------------------------------------------------------===//
3014 // Fast Calling Convention (tail call) implementation
3015 //===----------------------------------------------------------------------===//
3017 // Like std call, callee cleans arguments, convention except that ECX is
3018 // reserved for storing the tail called function address. Only 2 registers are
3019 // free for argument passing (inreg). Tail call optimization is performed
3021 // * tailcallopt is enabled
3022 // * caller/callee are fastcc
3023 // On X86_64 architecture with GOT-style position independent code only local
3024 // (within module) calls are supported at the moment.
3025 // To keep the stack aligned according to platform abi the function
3026 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3027 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3028 // If a tail called function callee has more arguments than the caller the
3029 // caller needs to make sure that there is room to move the RETADDR to. This is
3030 // achieved by reserving an area the size of the argument delta right after the
3031 // original REtADDR, but before the saved framepointer or the spilled registers
3032 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3044 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3045 /// for a 16 byte align requirement.
3047 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3048 SelectionDAG& DAG) const {
3049 MachineFunction &MF = DAG.getMachineFunction();
3050 const TargetMachine &TM = MF.getTarget();
3051 const X86RegisterInfo *RegInfo =
3052 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3053 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3054 unsigned StackAlignment = TFI.getStackAlignment();
3055 uint64_t AlignMask = StackAlignment - 1;
3056 int64_t Offset = StackSize;
3057 unsigned SlotSize = RegInfo->getSlotSize();
3058 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3059 // Number smaller than 12 so just add the difference.
3060 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3062 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3063 Offset = ((~AlignMask) & Offset) + StackAlignment +
3064 (StackAlignment-SlotSize);
3069 /// MatchingStackOffset - Return true if the given stack call argument is
3070 /// already available in the same position (relatively) of the caller's
3071 /// incoming argument stack.
3073 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3074 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3075 const X86InstrInfo *TII) {
3076 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3078 if (Arg.getOpcode() == ISD::CopyFromReg) {
3079 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3080 if (!TargetRegisterInfo::isVirtualRegister(VR))
3082 MachineInstr *Def = MRI->getVRegDef(VR);
3085 if (!Flags.isByVal()) {
3086 if (!TII->isLoadFromStackSlot(Def, FI))
3089 unsigned Opcode = Def->getOpcode();
3090 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3091 Def->getOperand(1).isFI()) {
3092 FI = Def->getOperand(1).getIndex();
3093 Bytes = Flags.getByValSize();
3097 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3098 if (Flags.isByVal())
3099 // ByVal argument is passed in as a pointer but it's now being
3100 // dereferenced. e.g.
3101 // define @foo(%struct.X* %A) {
3102 // tail call @bar(%struct.X* byval %A)
3105 SDValue Ptr = Ld->getBasePtr();
3106 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3109 FI = FINode->getIndex();
3110 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3111 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3112 FI = FINode->getIndex();
3113 Bytes = Flags.getByValSize();
3117 assert(FI != INT_MAX);
3118 if (!MFI->isFixedObjectIndex(FI))
3120 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3123 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3124 /// for tail call optimization. Targets which want to do tail call
3125 /// optimization should implement this function.
3127 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3128 CallingConv::ID CalleeCC,
3130 bool isCalleeStructRet,
3131 bool isCallerStructRet,
3133 const SmallVectorImpl<ISD::OutputArg> &Outs,
3134 const SmallVectorImpl<SDValue> &OutVals,
3135 const SmallVectorImpl<ISD::InputArg> &Ins,
3136 SelectionDAG &DAG) const {
3137 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3140 // If -tailcallopt is specified, make fastcc functions tail-callable.
3141 const MachineFunction &MF = DAG.getMachineFunction();
3142 const Function *CallerF = MF.getFunction();
3144 // If the function return type is x86_fp80 and the callee return type is not,
3145 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3146 // perform a tailcall optimization here.
3147 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3150 CallingConv::ID CallerCC = CallerF->getCallingConv();
3151 bool CCMatch = CallerCC == CalleeCC;
3152 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3153 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3155 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3156 if (IsTailCallConvention(CalleeCC) && CCMatch)
3161 // Look for obvious safe cases to perform tail call optimization that do not
3162 // require ABI changes. This is what gcc calls sibcall.
3164 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3165 // emit a special epilogue.
3166 const X86RegisterInfo *RegInfo =
3167 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3168 if (RegInfo->needsStackRealignment(MF))
3171 // Also avoid sibcall optimization if either caller or callee uses struct
3172 // return semantics.
3173 if (isCalleeStructRet || isCallerStructRet)
3176 // An stdcall/thiscall caller is expected to clean up its arguments; the
3177 // callee isn't going to do that.
3178 // FIXME: this is more restrictive than needed. We could produce a tailcall
3179 // when the stack adjustment matches. For example, with a thiscall that takes
3180 // only one argument.
3181 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3182 CallerCC == CallingConv::X86_ThisCall))
3185 // Do not sibcall optimize vararg calls unless all arguments are passed via
3187 if (isVarArg && !Outs.empty()) {
3189 // Optimizing for varargs on Win64 is unlikely to be safe without
3190 // additional testing.
3191 if (IsCalleeWin64 || IsCallerWin64)
3194 SmallVector<CCValAssign, 16> ArgLocs;
3195 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3196 DAG.getTarget(), ArgLocs, *DAG.getContext());
3198 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3199 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3200 if (!ArgLocs[i].isRegLoc())
3204 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3205 // stack. Therefore, if it's not used by the call it is not safe to optimize
3206 // this into a sibcall.
3207 bool Unused = false;
3208 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3215 SmallVector<CCValAssign, 16> RVLocs;
3216 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3217 DAG.getTarget(), RVLocs, *DAG.getContext());
3218 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3219 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3220 CCValAssign &VA = RVLocs[i];
3221 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3226 // If the calling conventions do not match, then we'd better make sure the
3227 // results are returned in the same way as what the caller expects.
3229 SmallVector<CCValAssign, 16> RVLocs1;
3230 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3231 DAG.getTarget(), RVLocs1, *DAG.getContext());
3232 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3234 SmallVector<CCValAssign, 16> RVLocs2;
3235 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3236 DAG.getTarget(), RVLocs2, *DAG.getContext());
3237 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3239 if (RVLocs1.size() != RVLocs2.size())
3241 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3242 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3244 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3246 if (RVLocs1[i].isRegLoc()) {
3247 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3250 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3256 // If the callee takes no arguments then go on to check the results of the
3258 if (!Outs.empty()) {
3259 // Check if stack adjustment is needed. For now, do not do this if any
3260 // argument is passed on the stack.
3261 SmallVector<CCValAssign, 16> ArgLocs;
3262 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3263 DAG.getTarget(), ArgLocs, *DAG.getContext());
3265 // Allocate shadow area for Win64
3267 CCInfo.AllocateStack(32, 8);
3269 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3270 if (CCInfo.getNextStackOffset()) {
3271 MachineFunction &MF = DAG.getMachineFunction();
3272 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3275 // Check if the arguments are already laid out in the right way as
3276 // the caller's fixed stack objects.
3277 MachineFrameInfo *MFI = MF.getFrameInfo();
3278 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3279 const X86InstrInfo *TII =
3280 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3281 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3282 CCValAssign &VA = ArgLocs[i];
3283 SDValue Arg = OutVals[i];
3284 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3285 if (VA.getLocInfo() == CCValAssign::Indirect)
3287 if (!VA.isRegLoc()) {
3288 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3295 // If the tailcall address may be in a register, then make sure it's
3296 // possible to register allocate for it. In 32-bit, the call address can
3297 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3298 // callee-saved registers are restored. These happen to be the same
3299 // registers used to pass 'inreg' arguments so watch out for those.
3300 if (!Subtarget->is64Bit() &&
3301 ((!isa<GlobalAddressSDNode>(Callee) &&
3302 !isa<ExternalSymbolSDNode>(Callee)) ||
3303 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3304 unsigned NumInRegs = 0;
3305 // In PIC we need an extra register to formulate the address computation
3307 unsigned MaxInRegs =
3308 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3310 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3311 CCValAssign &VA = ArgLocs[i];
3314 unsigned Reg = VA.getLocReg();
3317 case X86::EAX: case X86::EDX: case X86::ECX:
3318 if (++NumInRegs == MaxInRegs)
3330 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3331 const TargetLibraryInfo *libInfo) const {
3332 return X86::createFastISel(funcInfo, libInfo);
3335 //===----------------------------------------------------------------------===//
3336 // Other Lowering Hooks
3337 //===----------------------------------------------------------------------===//
3339 static bool MayFoldLoad(SDValue Op) {
3340 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3343 static bool MayFoldIntoStore(SDValue Op) {
3344 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3347 static bool isTargetShuffle(unsigned Opcode) {
3349 default: return false;
3350 case X86ISD::PSHUFD:
3351 case X86ISD::PSHUFHW:
3352 case X86ISD::PSHUFLW:
3354 case X86ISD::PALIGNR:
3355 case X86ISD::MOVLHPS:
3356 case X86ISD::MOVLHPD:
3357 case X86ISD::MOVHLPS:
3358 case X86ISD::MOVLPS:
3359 case X86ISD::MOVLPD:
3360 case X86ISD::MOVSHDUP:
3361 case X86ISD::MOVSLDUP:
3362 case X86ISD::MOVDDUP:
3365 case X86ISD::UNPCKL:
3366 case X86ISD::UNPCKH:
3367 case X86ISD::VPERMILP:
3368 case X86ISD::VPERM2X128:
3369 case X86ISD::VPERMI:
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375 SDValue V1, SelectionDAG &DAG) {
3377 default: llvm_unreachable("Unknown x86 shuffle node");
3378 case X86ISD::MOVSHDUP:
3379 case X86ISD::MOVSLDUP:
3380 case X86ISD::MOVDDUP:
3381 return DAG.getNode(Opc, dl, VT, V1);
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386 SDValue V1, unsigned TargetMask,
3387 SelectionDAG &DAG) {
3389 default: llvm_unreachable("Unknown x86 shuffle node");
3390 case X86ISD::PSHUFD:
3391 case X86ISD::PSHUFHW:
3392 case X86ISD::PSHUFLW:
3393 case X86ISD::VPERMILP:
3394 case X86ISD::VPERMI:
3395 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3399 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3400 SDValue V1, SDValue V2, unsigned TargetMask,
3401 SelectionDAG &DAG) {
3403 default: llvm_unreachable("Unknown x86 shuffle node");
3404 case X86ISD::PALIGNR:
3406 case X86ISD::VPERM2X128:
3407 return DAG.getNode(Opc, dl, VT, V1, V2,
3408 DAG.getConstant(TargetMask, MVT::i8));
3412 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3413 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3415 default: llvm_unreachable("Unknown x86 shuffle node");
3416 case X86ISD::MOVLHPS:
3417 case X86ISD::MOVLHPD:
3418 case X86ISD::MOVHLPS:
3419 case X86ISD::MOVLPS:
3420 case X86ISD::MOVLPD:
3423 case X86ISD::UNPCKL:
3424 case X86ISD::UNPCKH:
3425 return DAG.getNode(Opc, dl, VT, V1, V2);
3429 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3430 MachineFunction &MF = DAG.getMachineFunction();
3431 const X86RegisterInfo *RegInfo =
3432 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3433 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3434 int ReturnAddrIndex = FuncInfo->getRAIndex();
3436 if (ReturnAddrIndex == 0) {
3437 // Set up a frame object for the return address.
3438 unsigned SlotSize = RegInfo->getSlotSize();
3439 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3442 FuncInfo->setRAIndex(ReturnAddrIndex);
3445 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3448 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3449 bool hasSymbolicDisplacement) {
3450 // Offset should fit into 32 bit immediate field.
3451 if (!isInt<32>(Offset))
3454 // If we don't have a symbolic displacement - we don't have any extra
3456 if (!hasSymbolicDisplacement)
3459 // FIXME: Some tweaks might be needed for medium code model.
3460 if (M != CodeModel::Small && M != CodeModel::Kernel)
3463 // For small code model we assume that latest object is 16MB before end of 31
3464 // bits boundary. We may also accept pretty large negative constants knowing
3465 // that all objects are in the positive half of address space.
3466 if (M == CodeModel::Small && Offset < 16*1024*1024)
3469 // For kernel code model we know that all object resist in the negative half
3470 // of 32bits address space. We may not accept negative offsets, since they may
3471 // be just off and we may accept pretty large positive ones.
3472 if (M == CodeModel::Kernel && Offset > 0)
3478 /// isCalleePop - Determines whether the callee is required to pop its
3479 /// own arguments. Callee pop is necessary to support tail calls.
3480 bool X86::isCalleePop(CallingConv::ID CallingConv,
3481 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3485 switch (CallingConv) {
3488 case CallingConv::X86_StdCall:
3490 case CallingConv::X86_FastCall:
3492 case CallingConv::X86_ThisCall:
3494 case CallingConv::Fast:
3496 case CallingConv::GHC:
3498 case CallingConv::HiPE:
3503 /// \brief Return true if the condition is an unsigned comparison operation.
3504 static bool isX86CCUnsigned(unsigned X86CC) {
3506 default: llvm_unreachable("Invalid integer condition!");
3507 case X86::COND_E: return true;
3508 case X86::COND_G: return false;
3509 case X86::COND_GE: return false;
3510 case X86::COND_L: return false;
3511 case X86::COND_LE: return false;
3512 case X86::COND_NE: return true;
3513 case X86::COND_B: return true;
3514 case X86::COND_A: return true;
3515 case X86::COND_BE: return true;
3516 case X86::COND_AE: return true;
3518 llvm_unreachable("covered switch fell through?!");
3521 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3522 /// specific condition code, returning the condition code and the LHS/RHS of the
3523 /// comparison to make.
3524 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3525 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3527 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3528 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3529 // X > -1 -> X == 0, jump !sign.
3530 RHS = DAG.getConstant(0, RHS.getValueType());
3531 return X86::COND_NS;
3533 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3534 // X < 0 -> X == 0, jump on sign.
3537 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3539 RHS = DAG.getConstant(0, RHS.getValueType());
3540 return X86::COND_LE;
3544 switch (SetCCOpcode) {
3545 default: llvm_unreachable("Invalid integer condition!");
3546 case ISD::SETEQ: return X86::COND_E;
3547 case ISD::SETGT: return X86::COND_G;
3548 case ISD::SETGE: return X86::COND_GE;
3549 case ISD::SETLT: return X86::COND_L;
3550 case ISD::SETLE: return X86::COND_LE;
3551 case ISD::SETNE: return X86::COND_NE;
3552 case ISD::SETULT: return X86::COND_B;
3553 case ISD::SETUGT: return X86::COND_A;
3554 case ISD::SETULE: return X86::COND_BE;
3555 case ISD::SETUGE: return X86::COND_AE;
3559 // First determine if it is required or is profitable to flip the operands.
3561 // If LHS is a foldable load, but RHS is not, flip the condition.
3562 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3563 !ISD::isNON_EXTLoad(RHS.getNode())) {
3564 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3565 std::swap(LHS, RHS);
3568 switch (SetCCOpcode) {
3574 std::swap(LHS, RHS);
3578 // On a floating point condition, the flags are set as follows:
3580 // 0 | 0 | 0 | X > Y
3581 // 0 | 0 | 1 | X < Y
3582 // 1 | 0 | 0 | X == Y
3583 // 1 | 1 | 1 | unordered
3584 switch (SetCCOpcode) {
3585 default: llvm_unreachable("Condcode should be pre-legalized away");
3587 case ISD::SETEQ: return X86::COND_E;
3588 case ISD::SETOLT: // flipped
3590 case ISD::SETGT: return X86::COND_A;
3591 case ISD::SETOLE: // flipped
3593 case ISD::SETGE: return X86::COND_AE;
3594 case ISD::SETUGT: // flipped
3596 case ISD::SETLT: return X86::COND_B;
3597 case ISD::SETUGE: // flipped
3599 case ISD::SETLE: return X86::COND_BE;
3601 case ISD::SETNE: return X86::COND_NE;
3602 case ISD::SETUO: return X86::COND_P;
3603 case ISD::SETO: return X86::COND_NP;
3605 case ISD::SETUNE: return X86::COND_INVALID;
3609 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3610 /// code. Current x86 isa includes the following FP cmov instructions:
3611 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3612 static bool hasFPCMov(unsigned X86CC) {
3628 /// isFPImmLegal - Returns true if the target can instruction select the
3629 /// specified FP immediate natively. If false, the legalizer will
3630 /// materialize the FP immediate as a load from a constant pool.
3631 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3632 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3633 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3639 /// \brief Returns true if it is beneficial to convert a load of a constant
3640 /// to just the constant itself.
3641 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3643 assert(Ty->isIntegerTy());
3645 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3646 if (BitSize == 0 || BitSize > 64)
3651 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3652 /// the specified range (L, H].
3653 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3654 return (Val < 0) || (Val >= Low && Val < Hi);
3657 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3658 /// specified value.
3659 static bool isUndefOrEqual(int Val, int CmpVal) {
3660 return (Val < 0 || Val == CmpVal);
3663 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3664 /// from position Pos and ending in Pos+Size, falls within the specified
3665 /// sequential range (L, L+Pos]. or is undef.
3666 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3667 unsigned Pos, unsigned Size, int Low) {
3668 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3669 if (!isUndefOrEqual(Mask[i], Low))
3674 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3676 /// the second operand.
3677 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3678 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3679 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3680 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3681 return (Mask[0] < 2 && Mask[1] < 2);
3685 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3686 /// is suitable for input to PSHUFHW.
3687 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3688 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3691 // Lower quadword copied in order or undef.
3692 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3695 // Upper quadword shuffled.
3696 for (unsigned i = 4; i != 8; ++i)
3697 if (!isUndefOrInRange(Mask[i], 4, 8))
3700 if (VT == MVT::v16i16) {
3701 // Lower quadword copied in order or undef.
3702 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3705 // Upper quadword shuffled.
3706 for (unsigned i = 12; i != 16; ++i)
3707 if (!isUndefOrInRange(Mask[i], 12, 16))
3714 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3715 /// is suitable for input to PSHUFLW.
3716 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3717 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3720 // Upper quadword copied in order.
3721 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3724 // Lower quadword shuffled.
3725 for (unsigned i = 0; i != 4; ++i)
3726 if (!isUndefOrInRange(Mask[i], 0, 4))
3729 if (VT == MVT::v16i16) {
3730 // Upper quadword copied in order.
3731 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3734 // Lower quadword shuffled.
3735 for (unsigned i = 8; i != 12; ++i)
3736 if (!isUndefOrInRange(Mask[i], 8, 12))
3743 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3744 /// is suitable for input to PALIGNR.
3745 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3746 const X86Subtarget *Subtarget) {
3747 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3748 (VT.is256BitVector() && !Subtarget->hasInt256()))
3751 unsigned NumElts = VT.getVectorNumElements();
3752 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3753 unsigned NumLaneElts = NumElts/NumLanes;
3755 // Do not handle 64-bit element shuffles with palignr.
3756 if (NumLaneElts == 2)
3759 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3761 for (i = 0; i != NumLaneElts; ++i) {
3766 // Lane is all undef, go to next lane
3767 if (i == NumLaneElts)
3770 int Start = Mask[i+l];
3772 // Make sure its in this lane in one of the sources
3773 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3774 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3777 // If not lane 0, then we must match lane 0
3778 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3781 // Correct second source to be contiguous with first source
3782 if (Start >= (int)NumElts)
3783 Start -= NumElts - NumLaneElts;
3785 // Make sure we're shifting in the right direction.
3786 if (Start <= (int)(i+l))
3791 // Check the rest of the elements to see if they are consecutive.
3792 for (++i; i != NumLaneElts; ++i) {
3793 int Idx = Mask[i+l];
3795 // Make sure its in this lane
3796 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3797 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3800 // If not lane 0, then we must match lane 0
3801 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3804 if (Idx >= (int)NumElts)
3805 Idx -= NumElts - NumLaneElts;
3807 if (!isUndefOrEqual(Idx, Start+i))
3816 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3817 /// the two vector operands have swapped position.
3818 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3819 unsigned NumElems) {
3820 for (unsigned i = 0; i != NumElems; ++i) {
3824 else if (idx < (int)NumElems)
3825 Mask[i] = idx + NumElems;
3827 Mask[i] = idx - NumElems;
3831 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3832 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3833 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3834 /// reverse of what x86 shuffles want.
3835 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3837 unsigned NumElems = VT.getVectorNumElements();
3838 unsigned NumLanes = VT.getSizeInBits()/128;
3839 unsigned NumLaneElems = NumElems/NumLanes;
3841 if (NumLaneElems != 2 && NumLaneElems != 4)
3844 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3845 bool symetricMaskRequired =
3846 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3848 // VSHUFPSY divides the resulting vector into 4 chunks.
3849 // The sources are also splitted into 4 chunks, and each destination
3850 // chunk must come from a different source chunk.
3852 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3853 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3855 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3856 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3858 // VSHUFPDY divides the resulting vector into 4 chunks.
3859 // The sources are also splitted into 4 chunks, and each destination
3860 // chunk must come from a different source chunk.
3862 // SRC1 => X3 X2 X1 X0
3863 // SRC2 => Y3 Y2 Y1 Y0
3865 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3867 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3868 unsigned HalfLaneElems = NumLaneElems/2;
3869 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3870 for (unsigned i = 0; i != NumLaneElems; ++i) {
3871 int Idx = Mask[i+l];
3872 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3873 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3875 // For VSHUFPSY, the mask of the second half must be the same as the
3876 // first but with the appropriate offsets. This works in the same way as
3877 // VPERMILPS works with masks.
3878 if (!symetricMaskRequired || Idx < 0)
3880 if (MaskVal[i] < 0) {
3881 MaskVal[i] = Idx - l;
3884 if ((signed)(Idx - l) != MaskVal[i])
3892 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3894 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3895 if (!VT.is128BitVector())
3898 unsigned NumElems = VT.getVectorNumElements();
3903 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3904 return isUndefOrEqual(Mask[0], 6) &&
3905 isUndefOrEqual(Mask[1], 7) &&
3906 isUndefOrEqual(Mask[2], 2) &&
3907 isUndefOrEqual(Mask[3], 3);
3910 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3911 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3913 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3914 if (!VT.is128BitVector())
3917 unsigned NumElems = VT.getVectorNumElements();
3922 return isUndefOrEqual(Mask[0], 2) &&
3923 isUndefOrEqual(Mask[1], 3) &&
3924 isUndefOrEqual(Mask[2], 2) &&
3925 isUndefOrEqual(Mask[3], 3);
3928 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3930 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3931 if (!VT.is128BitVector())
3934 unsigned NumElems = VT.getVectorNumElements();
3936 if (NumElems != 2 && NumElems != 4)
3939 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3940 if (!isUndefOrEqual(Mask[i], i + NumElems))
3943 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3944 if (!isUndefOrEqual(Mask[i], i))
3950 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3951 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3952 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3953 if (!VT.is128BitVector())
3956 unsigned NumElems = VT.getVectorNumElements();
3958 if (NumElems != 2 && NumElems != 4)
3961 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3962 if (!isUndefOrEqual(Mask[i], i))
3965 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3966 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3972 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3973 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3974 /// i. e: If all but one element come from the same vector.
3975 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3976 // TODO: Deal with AVX's VINSERTPS
3977 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3980 unsigned CorrectPosV1 = 0;
3981 unsigned CorrectPosV2 = 0;
3982 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3983 if (Mask[i] == -1) {
3991 else if (Mask[i] == i + 4)
3995 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3996 // We have 3 elements (undefs count as elements from any vector) from one
3997 // vector, and one from another.
4004 // Some special combinations that can be optimized.
4007 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4008 SelectionDAG &DAG) {
4009 MVT VT = SVOp->getSimpleValueType(0);
4012 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4015 ArrayRef<int> Mask = SVOp->getMask();
4017 // These are the special masks that may be optimized.
4018 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4019 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4020 bool MatchEvenMask = true;
4021 bool MatchOddMask = true;
4022 for (int i=0; i<8; ++i) {
4023 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4024 MatchEvenMask = false;
4025 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4026 MatchOddMask = false;
4029 if (!MatchEvenMask && !MatchOddMask)
4032 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4034 SDValue Op0 = SVOp->getOperand(0);
4035 SDValue Op1 = SVOp->getOperand(1);
4037 if (MatchEvenMask) {
4038 // Shift the second operand right to 32 bits.
4039 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4040 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4042 // Shift the first operand left to 32 bits.
4043 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4044 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4046 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4047 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4050 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4052 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4053 bool HasInt256, bool V2IsSplat = false) {
4055 assert(VT.getSizeInBits() >= 128 &&
4056 "Unsupported vector type for unpckl");
4058 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4060 unsigned NumOf256BitLanes;
4061 unsigned NumElts = VT.getVectorNumElements();
4062 if (VT.is256BitVector()) {
4063 if (NumElts != 4 && NumElts != 8 &&
4064 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4067 NumOf256BitLanes = 1;
4068 } else if (VT.is512BitVector()) {
4069 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4070 "Unsupported vector type for unpckh");
4072 NumOf256BitLanes = 2;
4075 NumOf256BitLanes = 1;
4078 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4079 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4081 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4082 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4083 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4084 int BitI = Mask[l256*NumEltsInStride+l+i];
4085 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4086 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4088 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4090 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4098 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4099 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4100 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4101 bool HasInt256, bool V2IsSplat = false) {
4102 assert(VT.getSizeInBits() >= 128 &&
4103 "Unsupported vector type for unpckh");
4105 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4107 unsigned NumOf256BitLanes;
4108 unsigned NumElts = VT.getVectorNumElements();
4109 if (VT.is256BitVector()) {
4110 if (NumElts != 4 && NumElts != 8 &&
4111 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4114 NumOf256BitLanes = 1;
4115 } else if (VT.is512BitVector()) {
4116 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4117 "Unsupported vector type for unpckh");
4119 NumOf256BitLanes = 2;
4122 NumOf256BitLanes = 1;
4125 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4126 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4128 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4129 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4130 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4131 int BitI = Mask[l256*NumEltsInStride+l+i];
4132 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4133 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4135 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4137 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4145 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4146 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4148 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4149 unsigned NumElts = VT.getVectorNumElements();
4150 bool Is256BitVec = VT.is256BitVector();
4152 if (VT.is512BitVector())
4154 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4155 "Unsupported vector type for unpckh");
4157 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4158 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4161 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4162 // FIXME: Need a better way to get rid of this, there's no latency difference
4163 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4164 // the former later. We should also remove the "_undef" special mask.
4165 if (NumElts == 4 && Is256BitVec)
4168 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4169 // independently on 128-bit lanes.
4170 unsigned NumLanes = VT.getSizeInBits()/128;
4171 unsigned NumLaneElts = NumElts/NumLanes;
4173 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4174 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4175 int BitI = Mask[l+i];
4176 int BitI1 = Mask[l+i+1];
4178 if (!isUndefOrEqual(BitI, j))
4180 if (!isUndefOrEqual(BitI1, j))
4188 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4189 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4191 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4192 unsigned NumElts = VT.getVectorNumElements();
4194 if (VT.is512BitVector())
4197 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4198 "Unsupported vector type for unpckh");
4200 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4201 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4204 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4205 // independently on 128-bit lanes.
4206 unsigned NumLanes = VT.getSizeInBits()/128;
4207 unsigned NumLaneElts = NumElts/NumLanes;
4209 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4210 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4211 int BitI = Mask[l+i];
4212 int BitI1 = Mask[l+i+1];
4213 if (!isUndefOrEqual(BitI, j))
4215 if (!isUndefOrEqual(BitI1, j))
4222 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4223 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4224 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4225 if (!VT.is512BitVector())
4228 unsigned NumElts = VT.getVectorNumElements();
4229 unsigned HalfSize = NumElts/2;
4230 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4231 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4236 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4237 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4245 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4246 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4247 /// MOVSD, and MOVD, i.e. setting the lowest element.
4248 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4249 if (VT.getVectorElementType().getSizeInBits() < 32)
4251 if (!VT.is128BitVector())
4254 unsigned NumElts = VT.getVectorNumElements();
4256 if (!isUndefOrEqual(Mask[0], NumElts))
4259 for (unsigned i = 1; i != NumElts; ++i)
4260 if (!isUndefOrEqual(Mask[i], i))
4266 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4267 /// as permutations between 128-bit chunks or halves. As an example: this
4269 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4270 /// The first half comes from the second half of V1 and the second half from the
4271 /// the second half of V2.
4272 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4273 if (!HasFp256 || !VT.is256BitVector())
4276 // The shuffle result is divided into half A and half B. In total the two
4277 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4278 // B must come from C, D, E or F.
4279 unsigned HalfSize = VT.getVectorNumElements()/2;
4280 bool MatchA = false, MatchB = false;
4282 // Check if A comes from one of C, D, E, F.
4283 for (unsigned Half = 0; Half != 4; ++Half) {
4284 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4290 // Check if B comes from one of C, D, E, F.
4291 for (unsigned Half = 0; Half != 4; ++Half) {
4292 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4298 return MatchA && MatchB;
4301 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4302 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4303 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4304 MVT VT = SVOp->getSimpleValueType(0);
4306 unsigned HalfSize = VT.getVectorNumElements()/2;
4308 unsigned FstHalf = 0, SndHalf = 0;
4309 for (unsigned i = 0; i < HalfSize; ++i) {
4310 if (SVOp->getMaskElt(i) > 0) {
4311 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4315 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4316 if (SVOp->getMaskElt(i) > 0) {
4317 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4322 return (FstHalf | (SndHalf << 4));
4325 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4326 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4327 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4331 unsigned NumElts = VT.getVectorNumElements();
4333 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4334 for (unsigned i = 0; i != NumElts; ++i) {
4337 Imm8 |= Mask[i] << (i*2);
4342 unsigned LaneSize = 4;
4343 SmallVector<int, 4> MaskVal(LaneSize, -1);
4345 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4346 for (unsigned i = 0; i != LaneSize; ++i) {
4347 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4351 if (MaskVal[i] < 0) {
4352 MaskVal[i] = Mask[i+l] - l;
4353 Imm8 |= MaskVal[i] << (i*2);
4356 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4363 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4364 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4365 /// Note that VPERMIL mask matching is different depending whether theunderlying
4366 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4367 /// to the same elements of the low, but to the higher half of the source.
4368 /// In VPERMILPD the two lanes could be shuffled independently of each other
4369 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4370 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4371 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4372 if (VT.getSizeInBits() < 256 || EltSize < 32)
4374 bool symetricMaskRequired = (EltSize == 32);
4375 unsigned NumElts = VT.getVectorNumElements();
4377 unsigned NumLanes = VT.getSizeInBits()/128;
4378 unsigned LaneSize = NumElts/NumLanes;
4379 // 2 or 4 elements in one lane
4381 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4382 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4383 for (unsigned i = 0; i != LaneSize; ++i) {
4384 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4386 if (symetricMaskRequired) {
4387 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4388 ExpectedMaskVal[i] = Mask[i+l] - l;
4391 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4399 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4400 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4401 /// element of vector 2 and the other elements to come from vector 1 in order.
4402 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4403 bool V2IsSplat = false, bool V2IsUndef = false) {
4404 if (!VT.is128BitVector())
4407 unsigned NumOps = VT.getVectorNumElements();
4408 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4411 if (!isUndefOrEqual(Mask[0], 0))
4414 for (unsigned i = 1; i != NumOps; ++i)
4415 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4416 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4417 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4423 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4424 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4425 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4426 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4427 const X86Subtarget *Subtarget) {
4428 if (!Subtarget->hasSSE3())
4431 unsigned NumElems = VT.getVectorNumElements();
4433 if ((VT.is128BitVector() && NumElems != 4) ||
4434 (VT.is256BitVector() && NumElems != 8) ||
4435 (VT.is512BitVector() && NumElems != 16))
4438 // "i+1" is the value the indexed mask element must have
4439 for (unsigned i = 0; i != NumElems; i += 2)
4440 if (!isUndefOrEqual(Mask[i], i+1) ||
4441 !isUndefOrEqual(Mask[i+1], i+1))
4447 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4448 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4449 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4450 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4451 const X86Subtarget *Subtarget) {
4452 if (!Subtarget->hasSSE3())
4455 unsigned NumElems = VT.getVectorNumElements();
4457 if ((VT.is128BitVector() && NumElems != 4) ||
4458 (VT.is256BitVector() && NumElems != 8) ||
4459 (VT.is512BitVector() && NumElems != 16))
4462 // "i" is the value the indexed mask element must have
4463 for (unsigned i = 0; i != NumElems; i += 2)
4464 if (!isUndefOrEqual(Mask[i], i) ||
4465 !isUndefOrEqual(Mask[i+1], i))
4471 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4472 /// specifies a shuffle of elements that is suitable for input to 256-bit
4473 /// version of MOVDDUP.
4474 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4475 if (!HasFp256 || !VT.is256BitVector())
4478 unsigned NumElts = VT.getVectorNumElements();
4482 for (unsigned i = 0; i != NumElts/2; ++i)
4483 if (!isUndefOrEqual(Mask[i], 0))
4485 for (unsigned i = NumElts/2; i != NumElts; ++i)
4486 if (!isUndefOrEqual(Mask[i], NumElts/2))
4491 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4492 /// specifies a shuffle of elements that is suitable for input to 128-bit
4493 /// version of MOVDDUP.
4494 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4495 if (!VT.is128BitVector())
4498 unsigned e = VT.getVectorNumElements() / 2;
4499 for (unsigned i = 0; i != e; ++i)
4500 if (!isUndefOrEqual(Mask[i], i))
4502 for (unsigned i = 0; i != e; ++i)
4503 if (!isUndefOrEqual(Mask[e+i], i))
4508 /// isVEXTRACTIndex - Return true if the specified
4509 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4510 /// suitable for instruction that extract 128 or 256 bit vectors
4511 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4512 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4513 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4516 // The index should be aligned on a vecWidth-bit boundary.
4518 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4520 MVT VT = N->getSimpleValueType(0);
4521 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4522 bool Result = (Index * ElSize) % vecWidth == 0;
4527 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4528 /// operand specifies a subvector insert that is suitable for input to
4529 /// insertion of 128 or 256-bit subvectors
4530 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4531 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4532 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4534 // The index should be aligned on a vecWidth-bit boundary.
4536 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4538 MVT VT = N->getSimpleValueType(0);
4539 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4540 bool Result = (Index * ElSize) % vecWidth == 0;
4545 bool X86::isVINSERT128Index(SDNode *N) {
4546 return isVINSERTIndex(N, 128);
4549 bool X86::isVINSERT256Index(SDNode *N) {
4550 return isVINSERTIndex(N, 256);
4553 bool X86::isVEXTRACT128Index(SDNode *N) {
4554 return isVEXTRACTIndex(N, 128);
4557 bool X86::isVEXTRACT256Index(SDNode *N) {
4558 return isVEXTRACTIndex(N, 256);
4561 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4562 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4563 /// Handles 128-bit and 256-bit.
4564 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4565 MVT VT = N->getSimpleValueType(0);
4567 assert((VT.getSizeInBits() >= 128) &&
4568 "Unsupported vector type for PSHUF/SHUFP");
4570 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4571 // independently on 128-bit lanes.
4572 unsigned NumElts = VT.getVectorNumElements();
4573 unsigned NumLanes = VT.getSizeInBits()/128;
4574 unsigned NumLaneElts = NumElts/NumLanes;
4576 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4577 "Only supports 2, 4 or 8 elements per lane");
4579 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4581 for (unsigned i = 0; i != NumElts; ++i) {
4582 int Elt = N->getMaskElt(i);
4583 if (Elt < 0) continue;
4584 Elt &= NumLaneElts - 1;
4585 unsigned ShAmt = (i << Shift) % 8;
4586 Mask |= Elt << ShAmt;
4592 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4593 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4594 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4595 MVT VT = N->getSimpleValueType(0);
4597 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4598 "Unsupported vector type for PSHUFHW");
4600 unsigned NumElts = VT.getVectorNumElements();
4603 for (unsigned l = 0; l != NumElts; l += 8) {
4604 // 8 nodes per lane, but we only care about the last 4.
4605 for (unsigned i = 0; i < 4; ++i) {
4606 int Elt = N->getMaskElt(l+i+4);
4607 if (Elt < 0) continue;
4608 Elt &= 0x3; // only 2-bits.
4609 Mask |= Elt << (i * 2);
4616 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4617 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4618 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4619 MVT VT = N->getSimpleValueType(0);
4621 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4622 "Unsupported vector type for PSHUFHW");
4624 unsigned NumElts = VT.getVectorNumElements();
4627 for (unsigned l = 0; l != NumElts; l += 8) {
4628 // 8 nodes per lane, but we only care about the first 4.
4629 for (unsigned i = 0; i < 4; ++i) {
4630 int Elt = N->getMaskElt(l+i);
4631 if (Elt < 0) continue;
4632 Elt &= 0x3; // only 2-bits
4633 Mask |= Elt << (i * 2);
4640 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4641 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4642 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4643 MVT VT = SVOp->getSimpleValueType(0);
4644 unsigned EltSize = VT.is512BitVector() ? 1 :
4645 VT.getVectorElementType().getSizeInBits() >> 3;
4647 unsigned NumElts = VT.getVectorNumElements();
4648 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4649 unsigned NumLaneElts = NumElts/NumLanes;
4653 for (i = 0; i != NumElts; ++i) {
4654 Val = SVOp->getMaskElt(i);
4658 if (Val >= (int)NumElts)
4659 Val -= NumElts - NumLaneElts;
4661 assert(Val - i > 0 && "PALIGNR imm should be positive");
4662 return (Val - i) * EltSize;
4665 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4666 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4667 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4668 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4671 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4673 MVT VecVT = N->getOperand(0).getSimpleValueType();
4674 MVT ElVT = VecVT.getVectorElementType();
4676 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4677 return Index / NumElemsPerChunk;
4680 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4681 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4682 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4683 llvm_unreachable("Illegal insert subvector for VINSERT");
4686 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4688 MVT VecVT = N->getSimpleValueType(0);
4689 MVT ElVT = VecVT.getVectorElementType();
4691 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4692 return Index / NumElemsPerChunk;
4695 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4696 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4697 /// and VINSERTI128 instructions.
4698 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4699 return getExtractVEXTRACTImmediate(N, 128);
4702 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4703 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4704 /// and VINSERTI64x4 instructions.
4705 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4706 return getExtractVEXTRACTImmediate(N, 256);
4709 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4710 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4711 /// and VINSERTI128 instructions.
4712 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4713 return getInsertVINSERTImmediate(N, 128);
4716 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4717 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4718 /// and VINSERTI64x4 instructions.
4719 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4720 return getInsertVINSERTImmediate(N, 256);
4723 /// isZero - Returns true if Elt is a constant integer zero
4724 static bool isZero(SDValue V) {
4725 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4726 return C && C->isNullValue();
4729 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4731 bool X86::isZeroNode(SDValue Elt) {
4734 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4735 return CFP->getValueAPF().isPosZero();
4739 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4740 /// their permute mask.
4741 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4742 SelectionDAG &DAG) {
4743 MVT VT = SVOp->getSimpleValueType(0);
4744 unsigned NumElems = VT.getVectorNumElements();
4745 SmallVector<int, 8> MaskVec;
4747 for (unsigned i = 0; i != NumElems; ++i) {
4748 int Idx = SVOp->getMaskElt(i);
4750 if (Idx < (int)NumElems)
4755 MaskVec.push_back(Idx);
4757 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4758 SVOp->getOperand(0), &MaskVec[0]);
4761 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4762 /// match movhlps. The lower half elements should come from upper half of
4763 /// V1 (and in order), and the upper half elements should come from the upper
4764 /// half of V2 (and in order).
4765 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4766 if (!VT.is128BitVector())
4768 if (VT.getVectorNumElements() != 4)
4770 for (unsigned i = 0, e = 2; i != e; ++i)
4771 if (!isUndefOrEqual(Mask[i], i+2))
4773 for (unsigned i = 2; i != 4; ++i)
4774 if (!isUndefOrEqual(Mask[i], i+4))
4779 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4780 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4782 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4783 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4785 N = N->getOperand(0).getNode();
4786 if (!ISD::isNON_EXTLoad(N))
4789 *LD = cast<LoadSDNode>(N);
4793 // Test whether the given value is a vector value which will be legalized
4795 static bool WillBeConstantPoolLoad(SDNode *N) {
4796 if (N->getOpcode() != ISD::BUILD_VECTOR)
4799 // Check for any non-constant elements.
4800 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4801 switch (N->getOperand(i).getNode()->getOpcode()) {
4803 case ISD::ConstantFP:
4810 // Vectors of all-zeros and all-ones are materialized with special
4811 // instructions rather than being loaded.
4812 return !ISD::isBuildVectorAllZeros(N) &&
4813 !ISD::isBuildVectorAllOnes(N);
4816 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4817 /// match movlp{s|d}. The lower half elements should come from lower half of
4818 /// V1 (and in order), and the upper half elements should come from the upper
4819 /// half of V2 (and in order). And since V1 will become the source of the
4820 /// MOVLP, it must be either a vector load or a scalar load to vector.
4821 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4822 ArrayRef<int> Mask, MVT VT) {
4823 if (!VT.is128BitVector())
4826 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4828 // Is V2 is a vector load, don't do this transformation. We will try to use
4829 // load folding shufps op.
4830 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4833 unsigned NumElems = VT.getVectorNumElements();
4835 if (NumElems != 2 && NumElems != 4)
4837 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4838 if (!isUndefOrEqual(Mask[i], i))
4840 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4841 if (!isUndefOrEqual(Mask[i], i+NumElems))
4846 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4848 static bool isSplatVector(SDNode *N) {
4849 if (N->getOpcode() != ISD::BUILD_VECTOR)
4852 SDValue SplatValue = N->getOperand(0);
4853 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4854 if (N->getOperand(i) != SplatValue)
4859 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4860 /// to an zero vector.
4861 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4862 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4863 SDValue V1 = N->getOperand(0);
4864 SDValue V2 = N->getOperand(1);
4865 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4866 for (unsigned i = 0; i != NumElems; ++i) {
4867 int Idx = N->getMaskElt(i);
4868 if (Idx >= (int)NumElems) {
4869 unsigned Opc = V2.getOpcode();
4870 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4872 if (Opc != ISD::BUILD_VECTOR ||
4873 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4875 } else if (Idx >= 0) {
4876 unsigned Opc = V1.getOpcode();
4877 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4879 if (Opc != ISD::BUILD_VECTOR ||
4880 !X86::isZeroNode(V1.getOperand(Idx)))
4887 /// getZeroVector - Returns a vector of specified type with all zero elements.
4889 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4890 SelectionDAG &DAG, SDLoc dl) {
4891 assert(VT.isVector() && "Expected a vector type");
4893 // Always build SSE zero vectors as <4 x i32> bitcasted
4894 // to their dest type. This ensures they get CSE'd.
4896 if (VT.is128BitVector()) { // SSE
4897 if (Subtarget->hasSSE2()) { // SSE2
4898 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4899 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4901 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4902 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4904 } else if (VT.is256BitVector()) { // AVX
4905 if (Subtarget->hasInt256()) { // AVX2
4906 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4907 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4908 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4910 // 256-bit logic and arithmetic instructions in AVX are all
4911 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4912 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4913 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4916 } else if (VT.is512BitVector()) { // AVX-512
4917 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4918 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4919 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4921 } else if (VT.getScalarType() == MVT::i1) {
4922 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4923 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4924 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4925 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4927 llvm_unreachable("Unexpected vector type");
4929 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4932 /// getOnesVector - Returns a vector of specified type with all bits set.
4933 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4934 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4935 /// Then bitcast to their original type, ensuring they get CSE'd.
4936 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4938 assert(VT.isVector() && "Expected a vector type");
4940 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4942 if (VT.is256BitVector()) {
4943 if (HasInt256) { // AVX2
4944 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4945 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4947 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4948 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4950 } else if (VT.is128BitVector()) {
4951 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4953 llvm_unreachable("Unexpected vector type");
4955 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4958 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4959 /// that point to V2 points to its first element.
4960 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4961 for (unsigned i = 0; i != NumElems; ++i) {
4962 if (Mask[i] > (int)NumElems) {
4968 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4969 /// operation of specified width.
4970 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4972 unsigned NumElems = VT.getVectorNumElements();
4973 SmallVector<int, 8> Mask;
4974 Mask.push_back(NumElems);
4975 for (unsigned i = 1; i != NumElems; ++i)
4977 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4980 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4981 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4983 unsigned NumElems = VT.getVectorNumElements();
4984 SmallVector<int, 8> Mask;
4985 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4987 Mask.push_back(i + NumElems);
4989 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4992 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4993 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4995 unsigned NumElems = VT.getVectorNumElements();
4996 SmallVector<int, 8> Mask;
4997 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4998 Mask.push_back(i + Half);
4999 Mask.push_back(i + NumElems + Half);
5001 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5004 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5005 // a generic shuffle instruction because the target has no such instructions.
5006 // Generate shuffles which repeat i16 and i8 several times until they can be
5007 // represented by v4f32 and then be manipulated by target suported shuffles.
5008 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5009 MVT VT = V.getSimpleValueType();
5010 int NumElems = VT.getVectorNumElements();
5013 while (NumElems > 4) {
5014 if (EltNo < NumElems/2) {
5015 V = getUnpackl(DAG, dl, VT, V, V);
5017 V = getUnpackh(DAG, dl, VT, V, V);
5018 EltNo -= NumElems/2;
5025 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5026 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5027 MVT VT = V.getSimpleValueType();
5030 if (VT.is128BitVector()) {
5031 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5032 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5033 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5035 } else if (VT.is256BitVector()) {
5036 // To use VPERMILPS to splat scalars, the second half of indicies must
5037 // refer to the higher part, which is a duplication of the lower one,
5038 // because VPERMILPS can only handle in-lane permutations.
5039 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5040 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5042 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5043 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5046 llvm_unreachable("Vector size not supported");
5048 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5051 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5052 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5053 MVT SrcVT = SV->getSimpleValueType(0);
5054 SDValue V1 = SV->getOperand(0);
5057 int EltNo = SV->getSplatIndex();
5058 int NumElems = SrcVT.getVectorNumElements();
5059 bool Is256BitVec = SrcVT.is256BitVector();
5061 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5062 "Unknown how to promote splat for type");
5064 // Extract the 128-bit part containing the splat element and update
5065 // the splat element index when it refers to the higher register.
5067 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5068 if (EltNo >= NumElems/2)
5069 EltNo -= NumElems/2;
5072 // All i16 and i8 vector types can't be used directly by a generic shuffle
5073 // instruction because the target has no such instruction. Generate shuffles
5074 // which repeat i16 and i8 several times until they fit in i32, and then can
5075 // be manipulated by target suported shuffles.
5076 MVT EltVT = SrcVT.getVectorElementType();
5077 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5078 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5080 // Recreate the 256-bit vector and place the same 128-bit vector
5081 // into the low and high part. This is necessary because we want
5082 // to use VPERM* to shuffle the vectors
5084 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5087 return getLegalSplat(DAG, V1, EltNo);
5090 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5091 /// vector of zero or undef vector. This produces a shuffle where the low
5092 /// element of V2 is swizzled into the zero/undef vector, landing at element
5093 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5094 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5096 const X86Subtarget *Subtarget,
5097 SelectionDAG &DAG) {
5098 MVT VT = V2.getSimpleValueType();
5100 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5101 unsigned NumElems = VT.getVectorNumElements();
5102 SmallVector<int, 16> MaskVec;
5103 for (unsigned i = 0; i != NumElems; ++i)
5104 // If this is the insertion idx, put the low elt of V2 here.
5105 MaskVec.push_back(i == Idx ? NumElems : i);
5106 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5109 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5110 /// target specific opcode. Returns true if the Mask could be calculated.
5111 /// Sets IsUnary to true if only uses one source.
5112 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5113 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5114 unsigned NumElems = VT.getVectorNumElements();
5118 switch(N->getOpcode()) {
5120 ImmN = N->getOperand(N->getNumOperands()-1);
5121 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123 case X86ISD::UNPCKH:
5124 DecodeUNPCKHMask(VT, Mask);
5126 case X86ISD::UNPCKL:
5127 DecodeUNPCKLMask(VT, Mask);
5129 case X86ISD::MOVHLPS:
5130 DecodeMOVHLPSMask(NumElems, Mask);
5132 case X86ISD::MOVLHPS:
5133 DecodeMOVLHPSMask(NumElems, Mask);
5135 case X86ISD::PALIGNR:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139 case X86ISD::PSHUFD:
5140 case X86ISD::VPERMILP:
5141 ImmN = N->getOperand(N->getNumOperands()-1);
5142 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145 case X86ISD::PSHUFHW:
5146 ImmN = N->getOperand(N->getNumOperands()-1);
5147 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5150 case X86ISD::PSHUFLW:
5151 ImmN = N->getOperand(N->getNumOperands()-1);
5152 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5155 case X86ISD::VPERMI:
5156 ImmN = N->getOperand(N->getNumOperands()-1);
5157 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5161 case X86ISD::MOVSD: {
5162 // The index 0 always comes from the first element of the second source,
5163 // this is why MOVSS and MOVSD are used in the first place. The other
5164 // elements come from the other positions of the first source vector
5165 Mask.push_back(NumElems);
5166 for (unsigned i = 1; i != NumElems; ++i) {
5171 case X86ISD::VPERM2X128:
5172 ImmN = N->getOperand(N->getNumOperands()-1);
5173 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5174 if (Mask.empty()) return false;
5176 case X86ISD::MOVDDUP:
5177 case X86ISD::MOVLHPD:
5178 case X86ISD::MOVLPD:
5179 case X86ISD::MOVLPS:
5180 case X86ISD::MOVSHDUP:
5181 case X86ISD::MOVSLDUP:
5182 // Not yet implemented
5184 default: llvm_unreachable("unknown target shuffle node");
5190 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5191 /// element of the result of the vector shuffle.
5192 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5195 return SDValue(); // Limit search depth.
5197 SDValue V = SDValue(N, 0);
5198 EVT VT = V.getValueType();
5199 unsigned Opcode = V.getOpcode();
5201 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5202 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5203 int Elt = SV->getMaskElt(Index);
5206 return DAG.getUNDEF(VT.getVectorElementType());
5208 unsigned NumElems = VT.getVectorNumElements();
5209 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5210 : SV->getOperand(1);
5211 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5214 // Recurse into target specific vector shuffles to find scalars.
5215 if (isTargetShuffle(Opcode)) {
5216 MVT ShufVT = V.getSimpleValueType();
5217 unsigned NumElems = ShufVT.getVectorNumElements();
5218 SmallVector<int, 16> ShuffleMask;
5221 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5224 int Elt = ShuffleMask[Index];
5226 return DAG.getUNDEF(ShufVT.getVectorElementType());
5228 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5230 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5234 // Actual nodes that may contain scalar elements
5235 if (Opcode == ISD::BITCAST) {
5236 V = V.getOperand(0);
5237 EVT SrcVT = V.getValueType();
5238 unsigned NumElems = VT.getVectorNumElements();
5240 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5244 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5245 return (Index == 0) ? V.getOperand(0)
5246 : DAG.getUNDEF(VT.getVectorElementType());
5248 if (V.getOpcode() == ISD::BUILD_VECTOR)
5249 return V.getOperand(Index);
5254 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5255 /// shuffle operation which come from a consecutively from a zero. The
5256 /// search can start in two different directions, from left or right.
5257 /// We count undefs as zeros until PreferredNum is reached.
5258 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5259 unsigned NumElems, bool ZerosFromLeft,
5261 unsigned PreferredNum = -1U) {
5262 unsigned NumZeros = 0;
5263 for (unsigned i = 0; i != NumElems; ++i) {
5264 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5265 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5269 if (X86::isZeroNode(Elt))
5271 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5272 NumZeros = std::min(NumZeros + 1, PreferredNum);
5280 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5281 /// correspond consecutively to elements from one of the vector operands,
5282 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5284 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5285 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5286 unsigned NumElems, unsigned &OpNum) {
5287 bool SeenV1 = false;
5288 bool SeenV2 = false;
5290 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5291 int Idx = SVOp->getMaskElt(i);
5292 // Ignore undef indicies
5296 if (Idx < (int)NumElems)
5301 // Only accept consecutive elements from the same vector
5302 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5306 OpNum = SeenV1 ? 0 : 1;
5310 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5311 /// logical left shift of a vector.
5312 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5313 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5315 SVOp->getSimpleValueType(0).getVectorNumElements();
5316 unsigned NumZeros = getNumOfConsecutiveZeros(
5317 SVOp, NumElems, false /* check zeros from right */, DAG,
5318 SVOp->getMaskElt(0));
5324 // Considering the elements in the mask that are not consecutive zeros,
5325 // check if they consecutively come from only one of the source vectors.
5327 // V1 = {X, A, B, C} 0
5329 // vector_shuffle V1, V2 <1, 2, 3, X>
5331 if (!isShuffleMaskConsecutive(SVOp,
5332 0, // Mask Start Index
5333 NumElems-NumZeros, // Mask End Index(exclusive)
5334 NumZeros, // Where to start looking in the src vector
5335 NumElems, // Number of elements in vector
5336 OpSrc)) // Which source operand ?
5341 ShVal = SVOp->getOperand(OpSrc);
5345 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5346 /// logical left shift of a vector.
5347 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5348 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5350 SVOp->getSimpleValueType(0).getVectorNumElements();
5351 unsigned NumZeros = getNumOfConsecutiveZeros(
5352 SVOp, NumElems, true /* check zeros from left */, DAG,
5353 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5359 // Considering the elements in the mask that are not consecutive zeros,
5360 // check if they consecutively come from only one of the source vectors.
5362 // 0 { A, B, X, X } = V2
5364 // vector_shuffle V1, V2 <X, X, 4, 5>
5366 if (!isShuffleMaskConsecutive(SVOp,
5367 NumZeros, // Mask Start Index
5368 NumElems, // Mask End Index(exclusive)
5369 0, // Where to start looking in the src vector
5370 NumElems, // Number of elements in vector
5371 OpSrc)) // Which source operand ?
5376 ShVal = SVOp->getOperand(OpSrc);
5380 /// isVectorShift - Returns true if the shuffle can be implemented as a
5381 /// logical left or right shift of a vector.
5382 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5383 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5384 // Although the logic below support any bitwidth size, there are no
5385 // shift instructions which handle more than 128-bit vectors.
5386 if (!SVOp->getSimpleValueType(0).is128BitVector())
5389 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5390 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5396 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5398 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5399 unsigned NumNonZero, unsigned NumZero,
5401 const X86Subtarget* Subtarget,
5402 const TargetLowering &TLI) {
5409 for (unsigned i = 0; i < 16; ++i) {
5410 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5411 if (ThisIsNonZero && First) {
5413 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5415 V = DAG.getUNDEF(MVT::v8i16);
5420 SDValue ThisElt, LastElt;
5421 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5422 if (LastIsNonZero) {
5423 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5424 MVT::i16, Op.getOperand(i-1));
5426 if (ThisIsNonZero) {
5427 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5428 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5429 ThisElt, DAG.getConstant(8, MVT::i8));
5431 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5435 if (ThisElt.getNode())
5436 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5437 DAG.getIntPtrConstant(i/2));
5441 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5444 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5446 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5447 unsigned NumNonZero, unsigned NumZero,
5449 const X86Subtarget* Subtarget,
5450 const TargetLowering &TLI) {
5457 for (unsigned i = 0; i < 8; ++i) {
5458 bool isNonZero = (NonZeros & (1 << i)) != 0;
5462 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5464 V = DAG.getUNDEF(MVT::v8i16);
5467 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5468 MVT::v8i16, V, Op.getOperand(i),
5469 DAG.getIntPtrConstant(i));
5476 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5477 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5478 unsigned NonZeros, unsigned NumNonZero,
5479 unsigned NumZero, SelectionDAG &DAG,
5480 const X86Subtarget *Subtarget,
5481 const TargetLowering &TLI) {
5482 // We know there's at least one non-zero element
5483 unsigned FirstNonZeroIdx = 0;
5484 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5485 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5486 X86::isZeroNode(FirstNonZero)) {
5488 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5492 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5495 SDValue V = FirstNonZero.getOperand(0);
5496 MVT VVT = V.getSimpleValueType();
5497 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5500 unsigned FirstNonZeroDst =
5501 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5502 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5503 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5504 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5506 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5507 SDValue Elem = Op.getOperand(Idx);
5508 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5511 // TODO: What else can be here? Deal with it.
5512 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5515 // TODO: Some optimizations are still possible here
5516 // ex: Getting one element from a vector, and the rest from another.
5517 if (Elem.getOperand(0) != V)
5520 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5523 else if (IncorrectIdx == -1U) {
5527 // There was already one element with an incorrect index.
5528 // We can't optimize this case to an insertps.
5532 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5534 EVT VT = Op.getSimpleValueType();
5535 unsigned ElementMoveMask = 0;
5536 if (IncorrectIdx == -1U)
5537 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5539 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5541 SDValue InsertpsMask =
5542 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5543 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5549 /// getVShift - Return a vector logical shift node.
5551 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5552 unsigned NumBits, SelectionDAG &DAG,
5553 const TargetLowering &TLI, SDLoc dl) {
5554 assert(VT.is128BitVector() && "Unknown type for VShift");
5555 EVT ShVT = MVT::v2i64;
5556 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5557 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5558 return DAG.getNode(ISD::BITCAST, dl, VT,
5559 DAG.getNode(Opc, dl, ShVT, SrcOp,
5560 DAG.getConstant(NumBits,
5561 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5565 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5567 // Check if the scalar load can be widened into a vector load. And if
5568 // the address is "base + cst" see if the cst can be "absorbed" into
5569 // the shuffle mask.
5570 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5571 SDValue Ptr = LD->getBasePtr();
5572 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5574 EVT PVT = LD->getValueType(0);
5575 if (PVT != MVT::i32 && PVT != MVT::f32)
5580 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5581 FI = FINode->getIndex();
5583 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5584 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5585 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5586 Offset = Ptr.getConstantOperandVal(1);
5587 Ptr = Ptr.getOperand(0);
5592 // FIXME: 256-bit vector instructions don't require a strict alignment,
5593 // improve this code to support it better.
5594 unsigned RequiredAlign = VT.getSizeInBits()/8;
5595 SDValue Chain = LD->getChain();
5596 // Make sure the stack object alignment is at least 16 or 32.
5597 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5598 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5599 if (MFI->isFixedObjectIndex(FI)) {
5600 // Can't change the alignment. FIXME: It's possible to compute
5601 // the exact stack offset and reference FI + adjust offset instead.
5602 // If someone *really* cares about this. That's the way to implement it.
5605 MFI->setObjectAlignment(FI, RequiredAlign);
5609 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5610 // Ptr + (Offset & ~15).
5613 if ((Offset % RequiredAlign) & 3)
5615 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5617 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5618 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5620 int EltNo = (Offset - StartOffset) >> 2;
5621 unsigned NumElems = VT.getVectorNumElements();
5623 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5624 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5625 LD->getPointerInfo().getWithOffset(StartOffset),
5626 false, false, false, 0);
5628 SmallVector<int, 8> Mask;
5629 for (unsigned i = 0; i != NumElems; ++i)
5630 Mask.push_back(EltNo);
5632 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5638 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5639 /// vector of type 'VT', see if the elements can be replaced by a single large
5640 /// load which has the same value as a build_vector whose operands are 'elts'.
5642 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5644 /// FIXME: we'd also like to handle the case where the last elements are zero
5645 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5646 /// There's even a handy isZeroNode for that purpose.
5647 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5648 SDLoc &DL, SelectionDAG &DAG,
5649 bool isAfterLegalize) {
5650 EVT EltVT = VT.getVectorElementType();
5651 unsigned NumElems = Elts.size();
5653 LoadSDNode *LDBase = nullptr;
5654 unsigned LastLoadedElt = -1U;
5656 // For each element in the initializer, see if we've found a load or an undef.
5657 // If we don't find an initial load element, or later load elements are
5658 // non-consecutive, bail out.
5659 for (unsigned i = 0; i < NumElems; ++i) {
5660 SDValue Elt = Elts[i];
5662 if (!Elt.getNode() ||
5663 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5666 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5668 LDBase = cast<LoadSDNode>(Elt.getNode());
5672 if (Elt.getOpcode() == ISD::UNDEF)
5675 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5676 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5681 // If we have found an entire vector of loads and undefs, then return a large
5682 // load of the entire vector width starting at the base pointer. If we found
5683 // consecutive loads for the low half, generate a vzext_load node.
5684 if (LastLoadedElt == NumElems - 1) {
5686 if (isAfterLegalize &&
5687 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5690 SDValue NewLd = SDValue();
5692 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5693 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5694 LDBase->getPointerInfo(),
5695 LDBase->isVolatile(), LDBase->isNonTemporal(),
5696 LDBase->isInvariant(), 0);
5697 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5698 LDBase->getPointerInfo(),
5699 LDBase->isVolatile(), LDBase->isNonTemporal(),
5700 LDBase->isInvariant(), LDBase->getAlignment());
5702 if (LDBase->hasAnyUseOfValue(1)) {
5703 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5705 SDValue(NewLd.getNode(), 1));
5706 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5707 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5708 SDValue(NewLd.getNode(), 1));
5713 if (NumElems == 4 && LastLoadedElt == 1 &&
5714 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5715 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5716 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5718 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5719 LDBase->getPointerInfo(),
5720 LDBase->getAlignment(),
5721 false/*isVolatile*/, true/*ReadMem*/,
5724 // Make sure the newly-created LOAD is in the same position as LDBase in
5725 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5726 // update uses of LDBase's output chain to use the TokenFactor.
5727 if (LDBase->hasAnyUseOfValue(1)) {
5728 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5729 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5730 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5731 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5732 SDValue(ResNode.getNode(), 1));
5735 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5740 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5741 /// to generate a splat value for the following cases:
5742 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5743 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5744 /// a scalar load, or a constant.
5745 /// The VBROADCAST node is returned when a pattern is found,
5746 /// or SDValue() otherwise.
5747 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5748 SelectionDAG &DAG) {
5749 if (!Subtarget->hasFp256())
5752 MVT VT = Op.getSimpleValueType();
5755 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5756 "Unsupported vector type for broadcast.");
5761 switch (Op.getOpcode()) {
5763 // Unknown pattern found.
5766 case ISD::BUILD_VECTOR: {
5767 // The BUILD_VECTOR node must be a splat.
5768 if (!isSplatVector(Op.getNode()))
5771 Ld = Op.getOperand(0);
5772 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5773 Ld.getOpcode() == ISD::ConstantFP);
5775 // The suspected load node has several users. Make sure that all
5776 // of its users are from the BUILD_VECTOR node.
5777 // Constants may have multiple users.
5778 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5783 case ISD::VECTOR_SHUFFLE: {
5784 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5786 // Shuffles must have a splat mask where the first element is
5788 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5791 SDValue Sc = Op.getOperand(0);
5792 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5793 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5795 if (!Subtarget->hasInt256())
5798 // Use the register form of the broadcast instruction available on AVX2.
5799 if (VT.getSizeInBits() >= 256)
5800 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5801 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5804 Ld = Sc.getOperand(0);
5805 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5806 Ld.getOpcode() == ISD::ConstantFP);
5808 // The scalar_to_vector node and the suspected
5809 // load node must have exactly one user.
5810 // Constants may have multiple users.
5812 // AVX-512 has register version of the broadcast
5813 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5814 Ld.getValueType().getSizeInBits() >= 32;
5815 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5822 bool IsGE256 = (VT.getSizeInBits() >= 256);
5824 // Handle the broadcasting a single constant scalar from the constant pool
5825 // into a vector. On Sandybridge it is still better to load a constant vector
5826 // from the constant pool and not to broadcast it from a scalar.
5827 if (ConstSplatVal && Subtarget->hasInt256()) {
5828 EVT CVT = Ld.getValueType();
5829 assert(!CVT.isVector() && "Must not broadcast a vector type");
5830 unsigned ScalarSize = CVT.getSizeInBits();
5832 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5833 const Constant *C = nullptr;
5834 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5835 C = CI->getConstantIntValue();
5836 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5837 C = CF->getConstantFPValue();
5839 assert(C && "Invalid constant type");
5841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5842 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5843 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5844 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5845 MachinePointerInfo::getConstantPool(),
5846 false, false, false, Alignment);
5848 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5853 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5855 // Handle AVX2 in-register broadcasts.
5856 if (!IsLoad && Subtarget->hasInt256() &&
5857 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5858 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5860 // The scalar source must be a normal load.
5864 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5865 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5867 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5868 // double since there is no vbroadcastsd xmm
5869 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5870 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5871 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5874 // Unsupported broadcast.
5878 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5879 /// underlying vector and index.
5881 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5883 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5885 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5886 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5889 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5891 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5893 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5894 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5897 // In this case the vector is the extract_subvector expression and the index
5898 // is 2, as specified by the shuffle.
5899 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5900 SDValue ShuffleVec = SVOp->getOperand(0);
5901 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5902 assert(ShuffleVecVT.getVectorElementType() ==
5903 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5905 int ShuffleIdx = SVOp->getMaskElt(Idx);
5906 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5907 ExtractedFromVec = ShuffleVec;
5913 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5914 MVT VT = Op.getSimpleValueType();
5916 // Skip if insert_vec_elt is not supported.
5917 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5918 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5922 unsigned NumElems = Op.getNumOperands();
5926 SmallVector<unsigned, 4> InsertIndices;
5927 SmallVector<int, 8> Mask(NumElems, -1);
5929 for (unsigned i = 0; i != NumElems; ++i) {
5930 unsigned Opc = Op.getOperand(i).getOpcode();
5932 if (Opc == ISD::UNDEF)
5935 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5936 // Quit if more than 1 elements need inserting.
5937 if (InsertIndices.size() > 1)
5940 InsertIndices.push_back(i);
5944 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5945 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5946 // Quit if non-constant index.
5947 if (!isa<ConstantSDNode>(ExtIdx))
5949 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5951 // Quit if extracted from vector of different type.
5952 if (ExtractedFromVec.getValueType() != VT)
5955 if (!VecIn1.getNode())
5956 VecIn1 = ExtractedFromVec;
5957 else if (VecIn1 != ExtractedFromVec) {
5958 if (!VecIn2.getNode())
5959 VecIn2 = ExtractedFromVec;
5960 else if (VecIn2 != ExtractedFromVec)
5961 // Quit if more than 2 vectors to shuffle
5965 if (ExtractedFromVec == VecIn1)
5967 else if (ExtractedFromVec == VecIn2)
5968 Mask[i] = Idx + NumElems;
5971 if (!VecIn1.getNode())
5974 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5975 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5976 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5977 unsigned Idx = InsertIndices[i];
5978 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5979 DAG.getIntPtrConstant(Idx));
5985 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5987 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5989 MVT VT = Op.getSimpleValueType();
5990 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5991 "Unexpected type in LowerBUILD_VECTORvXi1!");
5994 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5995 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5996 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5997 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6000 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6001 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6002 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6006 bool AllContants = true;
6007 uint64_t Immediate = 0;
6008 int NonConstIdx = -1;
6009 bool IsSplat = true;
6010 unsigned NumNonConsts = 0;
6011 unsigned NumConsts = 0;
6012 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6013 SDValue In = Op.getOperand(idx);
6014 if (In.getOpcode() == ISD::UNDEF)
6016 if (!isa<ConstantSDNode>(In)) {
6017 AllContants = false;
6023 if (cast<ConstantSDNode>(In)->getZExtValue())
6024 Immediate |= (1ULL << idx);
6026 if (In != Op.getOperand(0))
6031 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6032 DAG.getConstant(Immediate, MVT::i16));
6033 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6034 DAG.getIntPtrConstant(0));
6037 if (NumNonConsts == 1 && NonConstIdx != 0) {
6040 SDValue VecAsImm = DAG.getConstant(Immediate,
6041 MVT::getIntegerVT(VT.getSizeInBits()));
6042 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6045 DstVec = DAG.getUNDEF(VT);
6046 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6047 Op.getOperand(NonConstIdx),
6048 DAG.getIntPtrConstant(NonConstIdx));
6050 if (!IsSplat && (NonConstIdx != 0))
6051 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6052 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6055 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6056 DAG.getConstant(-1, SelectVT),
6057 DAG.getConstant(0, SelectVT));
6059 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6060 DAG.getConstant((Immediate | 1), SelectVT),
6061 DAG.getConstant(Immediate, SelectVT));
6062 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6065 /// \brief Return true if \p N implements a horizontal binop and return the
6066 /// operands for the horizontal binop into V0 and V1.
6068 /// This is a helper function of PerformBUILD_VECTORCombine.
6069 /// This function checks that the build_vector \p N in input implements a
6070 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6071 /// operation to match.
6072 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6073 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6074 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6077 /// This function only analyzes elements of \p N whose indices are
6078 /// in range [BaseIdx, LastIdx).
6079 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6080 unsigned BaseIdx, unsigned LastIdx,
6081 SDValue &V0, SDValue &V1) {
6082 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6083 assert(N->getValueType(0).isVector() &&
6084 N->getValueType(0).getVectorNumElements() >= LastIdx &&
6085 "Invalid Vector in input!");
6087 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6088 bool CanFold = true;
6089 unsigned ExpectedVExtractIdx = BaseIdx;
6090 unsigned NumElts = LastIdx - BaseIdx;
6092 // Check if N implements a horizontal binop.
6093 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6094 SDValue Op = N->getOperand(i + BaseIdx);
6095 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6100 SDValue Op0 = Op.getOperand(0);
6101 SDValue Op1 = Op.getOperand(1);
6103 // Try to match the following pattern:
6104 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6105 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6106 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6107 Op0.getOperand(0) == Op1.getOperand(0) &&
6108 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6109 isa<ConstantSDNode>(Op1.getOperand(1)));
6113 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6114 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6117 V0 = Op0.getOperand(0);
6118 else if (i * 2 == NumElts) {
6119 V1 = Op0.getOperand(0);
6120 ExpectedVExtractIdx = BaseIdx;
6123 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6124 if (I0 == ExpectedVExtractIdx)
6125 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6126 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6127 // Try to match the following dag sequence:
6128 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6129 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6133 ExpectedVExtractIdx += 2;
6139 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6140 /// a concat_vector.
6142 /// This is a helper function of PerformBUILD_VECTORCombine.
6143 /// This function expects two 256-bit vectors called V0 and V1.
6144 /// At first, each vector is split into two separate 128-bit vectors.
6145 /// Then, the resulting 128-bit vectors are used to implement two
6146 /// horizontal binary operations.
6148 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6150 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6151 /// the two new horizontal binop.
6152 /// When Mode is set, the first horizontal binop dag node would take as input
6153 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6154 /// horizontal binop dag node would take as input the lower 128-bit of V1
6155 /// and the upper 128-bit of V1.
6157 /// HADD V0_LO, V0_HI
6158 /// HADD V1_LO, V1_HI
6160 /// Otherwise, the first horizontal binop dag node takes as input the lower
6161 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6162 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6164 /// HADD V0_LO, V1_LO
6165 /// HADD V0_HI, V1_HI
6166 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6167 SDLoc DL, SelectionDAG &DAG,
6168 unsigned X86Opcode, bool Mode) {
6169 EVT VT = V0.getValueType();
6170 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6171 "Invalid nodes in input!");
6173 unsigned NumElts = VT.getVectorNumElements();
6174 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6175 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6176 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6177 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6178 EVT NewVT = V0_LO.getValueType();
6182 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6183 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6185 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6186 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_HI, V1_HI);
6189 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6192 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6193 const X86Subtarget *Subtarget) {
6195 EVT VT = N->getValueType(0);
6196 unsigned NumElts = VT.getVectorNumElements();
6197 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6198 SDValue InVec0, InVec1;
6200 // Try to match horizontal ADD/SUB.
6201 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6202 // Try to match an SSE3 float HADD/HSUB.
6203 if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts, InVec0, InVec1))
6204 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6206 if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts, InVec0, InVec1))
6207 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6208 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6209 // Try to match an SSSE3 integer HADD/HSUB.
6210 if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts, InVec0, InVec1))
6211 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6213 if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts, InVec0, InVec1))
6214 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6217 if (!Subtarget->hasAVX())
6220 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6221 // Try to match an AVX horizontal add/sub of packed single/double
6222 // precision floating point values from 256-bit vectors.
6223 SDValue InVec2, InVec3;
6224 if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts/2, InVec0, InVec1) &&
6225 isHorizontalBinOp(BV, ISD::FADD, NumElts/2, NumElts, InVec2, InVec3) &&
6226 InVec0.getNode() == InVec2.getNode() &&
6227 InVec1.getNode() == InVec3.getNode())
6228 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6230 if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts/2, InVec0, InVec1) &&
6231 isHorizontalBinOp(BV, ISD::FSUB, NumElts/2, NumElts, InVec2, InVec3) &&
6232 InVec0.getNode() == InVec2.getNode() &&
6233 InVec1.getNode() == InVec3.getNode())
6234 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6235 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6236 // Try to match an AVX2 horizontal add/sub of signed integers.
6237 SDValue InVec2, InVec3;
6239 bool CanFold = true;
6241 if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts/2, InVec0, InVec1) &&
6242 isHorizontalBinOp(BV, ISD::ADD, NumElts/2, NumElts, InVec2, InVec3) &&
6243 InVec0.getNode() == InVec2.getNode() &&
6244 InVec1.getNode() == InVec3.getNode())
6245 X86Opcode = X86ISD::HADD;
6246 else if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts/2, InVec0, InVec1) &&
6247 isHorizontalBinOp(BV, ISD::SUB, NumElts/2, NumElts, InVec2, InVec3) &&
6248 InVec0.getNode() == InVec2.getNode() &&
6249 InVec1.getNode() == InVec3.getNode())
6250 X86Opcode = X86ISD::HSUB;
6255 // Fold this build_vector into a single horizontal add/sub.
6256 // Do this only if the target has AVX2.
6257 if (Subtarget->hasAVX2())
6258 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6260 // Convert this build_vector into a pair of horizontal binop followed by
6262 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false);
6266 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6267 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6269 if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts, InVec0, InVec1))
6270 X86Opcode = X86ISD::HADD;
6271 else if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts, InVec0, InVec1))
6272 X86Opcode = X86ISD::HSUB;
6273 else if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts, InVec0, InVec1))
6274 X86Opcode = X86ISD::FHADD;
6275 else if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts, InVec0, InVec1))
6276 X86Opcode = X86ISD::FHSUB;
6280 // Convert this build_vector into two horizontal add/sub followed by
6282 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true);
6289 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6292 MVT VT = Op.getSimpleValueType();
6293 MVT ExtVT = VT.getVectorElementType();
6294 unsigned NumElems = Op.getNumOperands();
6296 // Generate vectors for predicate vectors.
6297 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6298 return LowerBUILD_VECTORvXi1(Op, DAG);
6300 // Vectors containing all zeros can be matched by pxor and xorps later
6301 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6302 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6303 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6304 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6307 return getZeroVector(VT, Subtarget, DAG, dl);
6310 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6311 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6312 // vpcmpeqd on 256-bit vectors.
6313 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6314 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6317 if (!VT.is512BitVector())
6318 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6321 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6322 if (Broadcast.getNode())
6325 unsigned EVTBits = ExtVT.getSizeInBits();
6327 unsigned NumZero = 0;
6328 unsigned NumNonZero = 0;
6329 unsigned NonZeros = 0;
6330 bool IsAllConstants = true;
6331 SmallSet<SDValue, 8> Values;
6332 for (unsigned i = 0; i < NumElems; ++i) {
6333 SDValue Elt = Op.getOperand(i);
6334 if (Elt.getOpcode() == ISD::UNDEF)
6337 if (Elt.getOpcode() != ISD::Constant &&
6338 Elt.getOpcode() != ISD::ConstantFP)
6339 IsAllConstants = false;
6340 if (X86::isZeroNode(Elt))
6343 NonZeros |= (1 << i);
6348 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6349 if (NumNonZero == 0)
6350 return DAG.getUNDEF(VT);
6352 // Special case for single non-zero, non-undef, element.
6353 if (NumNonZero == 1) {
6354 unsigned Idx = countTrailingZeros(NonZeros);
6355 SDValue Item = Op.getOperand(Idx);
6357 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6358 // the value are obviously zero, truncate the value to i32 and do the
6359 // insertion that way. Only do this if the value is non-constant or if the
6360 // value is a constant being inserted into element 0. It is cheaper to do
6361 // a constant pool load than it is to do a movd + shuffle.
6362 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6363 (!IsAllConstants || Idx == 0)) {
6364 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6366 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6367 EVT VecVT = MVT::v4i32;
6368 unsigned VecElts = 4;
6370 // Truncate the value (which may itself be a constant) to i32, and
6371 // convert it to a vector with movd (S2V+shuffle to zero extend).
6372 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6373 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6374 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6376 // Now we have our 32-bit value zero extended in the low element of
6377 // a vector. If Idx != 0, swizzle it into place.
6379 SmallVector<int, 4> Mask;
6380 Mask.push_back(Idx);
6381 for (unsigned i = 1; i != VecElts; ++i)
6383 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6386 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6390 // If we have a constant or non-constant insertion into the low element of
6391 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6392 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6393 // depending on what the source datatype is.
6396 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6398 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6399 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6400 if (VT.is256BitVector() || VT.is512BitVector()) {
6401 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6402 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6403 Item, DAG.getIntPtrConstant(0));
6405 assert(VT.is128BitVector() && "Expected an SSE value type!");
6406 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6407 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6408 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6411 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6412 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6413 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6414 if (VT.is256BitVector()) {
6415 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6416 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6418 assert(VT.is128BitVector() && "Expected an SSE value type!");
6419 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6421 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6425 // Is it a vector logical left shift?
6426 if (NumElems == 2 && Idx == 1 &&
6427 X86::isZeroNode(Op.getOperand(0)) &&
6428 !X86::isZeroNode(Op.getOperand(1))) {
6429 unsigned NumBits = VT.getSizeInBits();
6430 return getVShift(true, VT,
6431 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6432 VT, Op.getOperand(1)),
6433 NumBits/2, DAG, *this, dl);
6436 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6439 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6440 // is a non-constant being inserted into an element other than the low one,
6441 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6442 // movd/movss) to move this into the low element, then shuffle it into
6444 if (EVTBits == 32) {
6445 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6447 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6448 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6449 SmallVector<int, 8> MaskVec;
6450 for (unsigned i = 0; i != NumElems; ++i)
6451 MaskVec.push_back(i == Idx ? 0 : 1);
6452 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6456 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6457 if (Values.size() == 1) {
6458 if (EVTBits == 32) {
6459 // Instead of a shuffle like this:
6460 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6461 // Check if it's possible to issue this instead.
6462 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6463 unsigned Idx = countTrailingZeros(NonZeros);
6464 SDValue Item = Op.getOperand(Idx);
6465 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6466 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6471 // A vector full of immediates; various special cases are already
6472 // handled, so this is best done with a single constant-pool load.
6476 // For AVX-length vectors, build the individual 128-bit pieces and use
6477 // shuffles to put them in place.
6478 if (VT.is256BitVector() || VT.is512BitVector()) {
6479 SmallVector<SDValue, 64> V;
6480 for (unsigned i = 0; i != NumElems; ++i)
6481 V.push_back(Op.getOperand(i));
6483 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6485 // Build both the lower and upper subvector.
6486 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6487 makeArrayRef(&V[0], NumElems/2));
6488 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6489 makeArrayRef(&V[NumElems / 2], NumElems/2));
6491 // Recreate the wider vector with the lower and upper part.
6492 if (VT.is256BitVector())
6493 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6494 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6497 // Let legalizer expand 2-wide build_vectors.
6498 if (EVTBits == 64) {
6499 if (NumNonZero == 1) {
6500 // One half is zero or undef.
6501 unsigned Idx = countTrailingZeros(NonZeros);
6502 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6503 Op.getOperand(Idx));
6504 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6509 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6510 if (EVTBits == 8 && NumElems == 16) {
6511 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6513 if (V.getNode()) return V;
6516 if (EVTBits == 16 && NumElems == 8) {
6517 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6519 if (V.getNode()) return V;
6522 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6523 if (EVTBits == 32 && NumElems == 4) {
6524 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6525 NumZero, DAG, Subtarget, *this);
6530 // If element VT is == 32 bits, turn it into a number of shuffles.
6531 SmallVector<SDValue, 8> V(NumElems);
6532 if (NumElems == 4 && NumZero > 0) {
6533 for (unsigned i = 0; i < 4; ++i) {
6534 bool isZero = !(NonZeros & (1 << i));
6536 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6538 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6541 for (unsigned i = 0; i < 2; ++i) {
6542 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6545 V[i] = V[i*2]; // Must be a zero vector.
6548 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6551 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6554 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6559 bool Reverse1 = (NonZeros & 0x3) == 2;
6560 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6564 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6565 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6567 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6570 if (Values.size() > 1 && VT.is128BitVector()) {
6571 // Check for a build vector of consecutive loads.
6572 for (unsigned i = 0; i < NumElems; ++i)
6573 V[i] = Op.getOperand(i);
6575 // Check for elements which are consecutive loads.
6576 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6580 // Check for a build vector from mostly shuffle plus few inserting.
6581 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6585 // For SSE 4.1, use insertps to put the high elements into the low element.
6586 if (getSubtarget()->hasSSE41()) {
6588 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6589 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6591 Result = DAG.getUNDEF(VT);
6593 for (unsigned i = 1; i < NumElems; ++i) {
6594 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6595 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6596 Op.getOperand(i), DAG.getIntPtrConstant(i));
6601 // Otherwise, expand into a number of unpckl*, start by extending each of
6602 // our (non-undef) elements to the full vector width with the element in the
6603 // bottom slot of the vector (which generates no code for SSE).
6604 for (unsigned i = 0; i < NumElems; ++i) {
6605 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6606 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6608 V[i] = DAG.getUNDEF(VT);
6611 // Next, we iteratively mix elements, e.g. for v4f32:
6612 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6613 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6614 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6615 unsigned EltStride = NumElems >> 1;
6616 while (EltStride != 0) {
6617 for (unsigned i = 0; i < EltStride; ++i) {
6618 // If V[i+EltStride] is undef and this is the first round of mixing,
6619 // then it is safe to just drop this shuffle: V[i] is already in the
6620 // right place, the one element (since it's the first round) being
6621 // inserted as undef can be dropped. This isn't safe for successive
6622 // rounds because they will permute elements within both vectors.
6623 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6624 EltStride == NumElems/2)
6627 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6636 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6637 // to create 256-bit vectors from two other 128-bit ones.
6638 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6640 MVT ResVT = Op.getSimpleValueType();
6642 assert((ResVT.is256BitVector() ||
6643 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6645 SDValue V1 = Op.getOperand(0);
6646 SDValue V2 = Op.getOperand(1);
6647 unsigned NumElems = ResVT.getVectorNumElements();
6648 if(ResVT.is256BitVector())
6649 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6651 if (Op.getNumOperands() == 4) {
6652 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6653 ResVT.getVectorNumElements()/2);
6654 SDValue V3 = Op.getOperand(2);
6655 SDValue V4 = Op.getOperand(3);
6656 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6657 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6659 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6662 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6663 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6664 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6665 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6666 Op.getNumOperands() == 4)));
6668 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6669 // from two other 128-bit ones.
6671 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6672 return LowerAVXCONCAT_VECTORS(Op, DAG);
6675 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6676 bool hasInt256, unsigned *MaskOut = nullptr) {
6677 MVT EltVT = VT.getVectorElementType();
6679 // There is no blend with immediate in AVX-512.
6680 if (VT.is512BitVector())
6683 if (!hasSSE41 || EltVT == MVT::i8)
6685 if (!hasInt256 && VT == MVT::v16i16)
6688 unsigned MaskValue = 0;
6689 unsigned NumElems = VT.getVectorNumElements();
6690 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6691 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6692 unsigned NumElemsInLane = NumElems / NumLanes;
6694 // Blend for v16i16 should be symetric for the both lanes.
6695 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6697 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6698 int EltIdx = MaskVals[i];
6700 if ((EltIdx < 0 || EltIdx == (int)i) &&
6701 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6704 if (((unsigned)EltIdx == (i + NumElems)) &&
6705 (SndLaneEltIdx < 0 ||
6706 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6707 MaskValue |= (1 << i);
6713 *MaskOut = MaskValue;
6717 // Try to lower a shuffle node into a simple blend instruction.
6718 // This function assumes isBlendMask returns true for this
6719 // SuffleVectorSDNode
6720 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6722 const X86Subtarget *Subtarget,
6723 SelectionDAG &DAG) {
6724 MVT VT = SVOp->getSimpleValueType(0);
6725 MVT EltVT = VT.getVectorElementType();
6726 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6727 Subtarget->hasInt256() && "Trying to lower a "
6728 "VECTOR_SHUFFLE to a Blend but "
6729 "with the wrong mask"));
6730 SDValue V1 = SVOp->getOperand(0);
6731 SDValue V2 = SVOp->getOperand(1);
6733 unsigned NumElems = VT.getVectorNumElements();
6735 // Convert i32 vectors to floating point if it is not AVX2.
6736 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6738 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6739 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6741 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6742 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6745 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6746 DAG.getConstant(MaskValue, MVT::i32));
6747 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6750 /// In vector type \p VT, return true if the element at index \p InputIdx
6751 /// falls on a different 128-bit lane than \p OutputIdx.
6752 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6753 unsigned OutputIdx) {
6754 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6755 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6758 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6759 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6760 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6761 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6763 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6764 SelectionDAG &DAG) {
6765 MVT VT = V1.getSimpleValueType();
6766 assert(VT.is128BitVector() || VT.is256BitVector());
6768 MVT EltVT = VT.getVectorElementType();
6769 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6770 unsigned NumElts = VT.getVectorNumElements();
6772 SmallVector<SDValue, 32> PshufbMask;
6773 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6774 int InputIdx = MaskVals[OutputIdx];
6775 unsigned InputByteIdx;
6777 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6778 InputByteIdx = 0x80;
6780 // Cross lane is not allowed.
6781 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6783 InputByteIdx = InputIdx * EltSizeInBytes;
6784 // Index is an byte offset within the 128-bit lane.
6785 InputByteIdx &= 0xf;
6788 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6789 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6790 if (InputByteIdx != 0x80)
6795 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6797 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6798 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6799 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6802 // v8i16 shuffles - Prefer shuffles in the following order:
6803 // 1. [all] pshuflw, pshufhw, optional move
6804 // 2. [ssse3] 1 x pshufb
6805 // 3. [ssse3] 2 x pshufb + 1 x por
6806 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6808 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6809 SelectionDAG &DAG) {
6810 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6811 SDValue V1 = SVOp->getOperand(0);
6812 SDValue V2 = SVOp->getOperand(1);
6814 SmallVector<int, 8> MaskVals;
6816 // Determine if more than 1 of the words in each of the low and high quadwords
6817 // of the result come from the same quadword of one of the two inputs. Undef
6818 // mask values count as coming from any quadword, for better codegen.
6820 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6821 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6822 unsigned LoQuad[] = { 0, 0, 0, 0 };
6823 unsigned HiQuad[] = { 0, 0, 0, 0 };
6824 // Indices of quads used.
6825 std::bitset<4> InputQuads;
6826 for (unsigned i = 0; i < 8; ++i) {
6827 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6828 int EltIdx = SVOp->getMaskElt(i);
6829 MaskVals.push_back(EltIdx);
6838 InputQuads.set(EltIdx / 4);
6841 int BestLoQuad = -1;
6842 unsigned MaxQuad = 1;
6843 for (unsigned i = 0; i < 4; ++i) {
6844 if (LoQuad[i] > MaxQuad) {
6846 MaxQuad = LoQuad[i];
6850 int BestHiQuad = -1;
6852 for (unsigned i = 0; i < 4; ++i) {
6853 if (HiQuad[i] > MaxQuad) {
6855 MaxQuad = HiQuad[i];
6859 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6860 // of the two input vectors, shuffle them into one input vector so only a
6861 // single pshufb instruction is necessary. If there are more than 2 input
6862 // quads, disable the next transformation since it does not help SSSE3.
6863 bool V1Used = InputQuads[0] || InputQuads[1];
6864 bool V2Used = InputQuads[2] || InputQuads[3];
6865 if (Subtarget->hasSSSE3()) {
6866 if (InputQuads.count() == 2 && V1Used && V2Used) {
6867 BestLoQuad = InputQuads[0] ? 0 : 1;
6868 BestHiQuad = InputQuads[2] ? 2 : 3;
6870 if (InputQuads.count() > 2) {
6876 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6877 // the shuffle mask. If a quad is scored as -1, that means that it contains
6878 // words from all 4 input quadwords.
6880 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6882 BestLoQuad < 0 ? 0 : BestLoQuad,
6883 BestHiQuad < 0 ? 1 : BestHiQuad
6885 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6886 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6887 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6888 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6890 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6891 // source words for the shuffle, to aid later transformations.
6892 bool AllWordsInNewV = true;
6893 bool InOrder[2] = { true, true };
6894 for (unsigned i = 0; i != 8; ++i) {
6895 int idx = MaskVals[i];
6897 InOrder[i/4] = false;
6898 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6900 AllWordsInNewV = false;
6904 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6905 if (AllWordsInNewV) {
6906 for (int i = 0; i != 8; ++i) {
6907 int idx = MaskVals[i];
6910 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6911 if ((idx != i) && idx < 4)
6913 if ((idx != i) && idx > 3)
6922 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6923 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6924 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6925 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6926 unsigned TargetMask = 0;
6927 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6928 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6929 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6930 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6931 getShufflePSHUFLWImmediate(SVOp);
6932 V1 = NewV.getOperand(0);
6933 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6937 // Promote splats to a larger type which usually leads to more efficient code.
6938 // FIXME: Is this true if pshufb is available?
6939 if (SVOp->isSplat())
6940 return PromoteSplat(SVOp, DAG);
6942 // If we have SSSE3, and all words of the result are from 1 input vector,
6943 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6944 // is present, fall back to case 4.
6945 if (Subtarget->hasSSSE3()) {
6946 SmallVector<SDValue,16> pshufbMask;
6948 // If we have elements from both input vectors, set the high bit of the
6949 // shuffle mask element to zero out elements that come from V2 in the V1
6950 // mask, and elements that come from V1 in the V2 mask, so that the two
6951 // results can be OR'd together.
6952 bool TwoInputs = V1Used && V2Used;
6953 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6955 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6957 // Calculate the shuffle mask for the second input, shuffle it, and
6958 // OR it with the first shuffled input.
6959 CommuteVectorShuffleMask(MaskVals, 8);
6960 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6961 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6962 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6965 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6966 // and update MaskVals with new element order.
6967 std::bitset<8> InOrder;
6968 if (BestLoQuad >= 0) {
6969 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6970 for (int i = 0; i != 4; ++i) {
6971 int idx = MaskVals[i];
6974 } else if ((idx / 4) == BestLoQuad) {
6979 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6982 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6983 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6984 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6986 getShufflePSHUFLWImmediate(SVOp), DAG);
6990 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6991 // and update MaskVals with the new element order.
6992 if (BestHiQuad >= 0) {
6993 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6994 for (unsigned i = 4; i != 8; ++i) {
6995 int idx = MaskVals[i];
6998 } else if ((idx / 4) == BestHiQuad) {
6999 MaskV[i] = (idx & 3) + 4;
7003 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7006 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7007 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7008 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7010 getShufflePSHUFHWImmediate(SVOp), DAG);
7014 // In case BestHi & BestLo were both -1, which means each quadword has a word
7015 // from each of the four input quadwords, calculate the InOrder bitvector now
7016 // before falling through to the insert/extract cleanup.
7017 if (BestLoQuad == -1 && BestHiQuad == -1) {
7019 for (int i = 0; i != 8; ++i)
7020 if (MaskVals[i] < 0 || MaskVals[i] == i)
7024 // The other elements are put in the right place using pextrw and pinsrw.
7025 for (unsigned i = 0; i != 8; ++i) {
7028 int EltIdx = MaskVals[i];
7031 SDValue ExtOp = (EltIdx < 8) ?
7032 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7033 DAG.getIntPtrConstant(EltIdx)) :
7034 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7035 DAG.getIntPtrConstant(EltIdx - 8));
7036 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7037 DAG.getIntPtrConstant(i));
7042 /// \brief v16i16 shuffles
7044 /// FIXME: We only support generation of a single pshufb currently. We can
7045 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7046 /// well (e.g 2 x pshufb + 1 x por).
7048 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7049 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7050 SDValue V1 = SVOp->getOperand(0);
7051 SDValue V2 = SVOp->getOperand(1);
7054 if (V2.getOpcode() != ISD::UNDEF)
7057 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7058 return getPSHUFB(MaskVals, V1, dl, DAG);
7061 // v16i8 shuffles - Prefer shuffles in the following order:
7062 // 1. [ssse3] 1 x pshufb
7063 // 2. [ssse3] 2 x pshufb + 1 x por
7064 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
7065 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7066 const X86Subtarget* Subtarget,
7067 SelectionDAG &DAG) {
7068 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7069 SDValue V1 = SVOp->getOperand(0);
7070 SDValue V2 = SVOp->getOperand(1);
7072 ArrayRef<int> MaskVals = SVOp->getMask();
7074 // Promote splats to a larger type which usually leads to more efficient code.
7075 // FIXME: Is this true if pshufb is available?
7076 if (SVOp->isSplat())
7077 return PromoteSplat(SVOp, DAG);
7079 // If we have SSSE3, case 1 is generated when all result bytes come from
7080 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
7081 // present, fall back to case 3.
7083 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7084 if (Subtarget->hasSSSE3()) {
7085 SmallVector<SDValue,16> pshufbMask;
7087 // If all result elements are from one input vector, then only translate
7088 // undef mask values to 0x80 (zero out result) in the pshufb mask.
7090 // Otherwise, we have elements from both input vectors, and must zero out
7091 // elements that come from V2 in the first mask, and V1 in the second mask
7092 // so that we can OR them together.
7093 for (unsigned i = 0; i != 16; ++i) {
7094 int EltIdx = MaskVals[i];
7095 if (EltIdx < 0 || EltIdx >= 16)
7097 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7099 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7100 DAG.getNode(ISD::BUILD_VECTOR, dl,
7101 MVT::v16i8, pshufbMask));
7103 // As PSHUFB will zero elements with negative indices, it's safe to ignore
7104 // the 2nd operand if it's undefined or zero.
7105 if (V2.getOpcode() == ISD::UNDEF ||
7106 ISD::isBuildVectorAllZeros(V2.getNode()))
7109 // Calculate the shuffle mask for the second input, shuffle it, and
7110 // OR it with the first shuffled input.
7112 for (unsigned i = 0; i != 16; ++i) {
7113 int EltIdx = MaskVals[i];
7114 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7115 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7117 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7118 DAG.getNode(ISD::BUILD_VECTOR, dl,
7119 MVT::v16i8, pshufbMask));
7120 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7123 // No SSSE3 - Calculate in place words and then fix all out of place words
7124 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
7125 // the 16 different words that comprise the two doublequadword input vectors.
7126 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7127 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7129 for (int i = 0; i != 8; ++i) {
7130 int Elt0 = MaskVals[i*2];
7131 int Elt1 = MaskVals[i*2+1];
7133 // This word of the result is all undef, skip it.
7134 if (Elt0 < 0 && Elt1 < 0)
7137 // This word of the result is already in the correct place, skip it.
7138 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7141 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7142 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7145 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7146 // using a single extract together, load it and store it.
7147 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7148 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7149 DAG.getIntPtrConstant(Elt1 / 2));
7150 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7151 DAG.getIntPtrConstant(i));
7155 // If Elt1 is defined, extract it from the appropriate source. If the
7156 // source byte is not also odd, shift the extracted word left 8 bits
7157 // otherwise clear the bottom 8 bits if we need to do an or.
7159 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7160 DAG.getIntPtrConstant(Elt1 / 2));
7161 if ((Elt1 & 1) == 0)
7162 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7164 TLI.getShiftAmountTy(InsElt.getValueType())));
7166 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7167 DAG.getConstant(0xFF00, MVT::i16));
7169 // If Elt0 is defined, extract it from the appropriate source. If the
7170 // source byte is not also even, shift the extracted word right 8 bits. If
7171 // Elt1 was also defined, OR the extracted values together before
7172 // inserting them in the result.
7174 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7175 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7176 if ((Elt0 & 1) != 0)
7177 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7179 TLI.getShiftAmountTy(InsElt0.getValueType())));
7181 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7182 DAG.getConstant(0x00FF, MVT::i16));
7183 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7186 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7187 DAG.getIntPtrConstant(i));
7189 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7192 // v32i8 shuffles - Translate to VPSHUFB if possible.
7194 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7195 const X86Subtarget *Subtarget,
7196 SelectionDAG &DAG) {
7197 MVT VT = SVOp->getSimpleValueType(0);
7198 SDValue V1 = SVOp->getOperand(0);
7199 SDValue V2 = SVOp->getOperand(1);
7201 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7203 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7204 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7205 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7207 // VPSHUFB may be generated if
7208 // (1) one of input vector is undefined or zeroinitializer.
7209 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7210 // And (2) the mask indexes don't cross the 128-bit lane.
7211 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7212 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7215 if (V1IsAllZero && !V2IsAllZero) {
7216 CommuteVectorShuffleMask(MaskVals, 32);
7219 return getPSHUFB(MaskVals, V1, dl, DAG);
7222 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7223 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7224 /// done when every pair / quad of shuffle mask elements point to elements in
7225 /// the right sequence. e.g.
7226 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7228 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7229 SelectionDAG &DAG) {
7230 MVT VT = SVOp->getSimpleValueType(0);
7232 unsigned NumElems = VT.getVectorNumElements();
7235 switch (VT.SimpleTy) {
7236 default: llvm_unreachable("Unexpected!");
7239 return SDValue(SVOp, 0);
7240 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7241 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7242 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7243 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7244 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7245 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7248 SmallVector<int, 8> MaskVec;
7249 for (unsigned i = 0; i != NumElems; i += Scale) {
7251 for (unsigned j = 0; j != Scale; ++j) {
7252 int EltIdx = SVOp->getMaskElt(i+j);
7256 StartIdx = (EltIdx / Scale);
7257 if (EltIdx != (int)(StartIdx*Scale + j))
7260 MaskVec.push_back(StartIdx);
7263 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7264 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7265 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7268 /// getVZextMovL - Return a zero-extending vector move low node.
7270 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7271 SDValue SrcOp, SelectionDAG &DAG,
7272 const X86Subtarget *Subtarget, SDLoc dl) {
7273 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7274 LoadSDNode *LD = nullptr;
7275 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7276 LD = dyn_cast<LoadSDNode>(SrcOp);
7278 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7280 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7281 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7282 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7283 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7284 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7286 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7287 return DAG.getNode(ISD::BITCAST, dl, VT,
7288 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7289 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7297 return DAG.getNode(ISD::BITCAST, dl, VT,
7298 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7299 DAG.getNode(ISD::BITCAST, dl,
7303 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7304 /// which could not be matched by any known target speficic shuffle
7306 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7308 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7309 if (NewOp.getNode())
7312 MVT VT = SVOp->getSimpleValueType(0);
7314 unsigned NumElems = VT.getVectorNumElements();
7315 unsigned NumLaneElems = NumElems / 2;
7318 MVT EltVT = VT.getVectorElementType();
7319 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7322 SmallVector<int, 16> Mask;
7323 for (unsigned l = 0; l < 2; ++l) {
7324 // Build a shuffle mask for the output, discovering on the fly which
7325 // input vectors to use as shuffle operands (recorded in InputUsed).
7326 // If building a suitable shuffle vector proves too hard, then bail
7327 // out with UseBuildVector set.
7328 bool UseBuildVector = false;
7329 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7330 unsigned LaneStart = l * NumLaneElems;
7331 for (unsigned i = 0; i != NumLaneElems; ++i) {
7332 // The mask element. This indexes into the input.
7333 int Idx = SVOp->getMaskElt(i+LaneStart);
7335 // the mask element does not index into any input vector.
7340 // The input vector this mask element indexes into.
7341 int Input = Idx / NumLaneElems;
7343 // Turn the index into an offset from the start of the input vector.
7344 Idx -= Input * NumLaneElems;
7346 // Find or create a shuffle vector operand to hold this input.
7348 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7349 if (InputUsed[OpNo] == Input)
7350 // This input vector is already an operand.
7352 if (InputUsed[OpNo] < 0) {
7353 // Create a new operand for this input vector.
7354 InputUsed[OpNo] = Input;
7359 if (OpNo >= array_lengthof(InputUsed)) {
7360 // More than two input vectors used! Give up on trying to create a
7361 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7362 UseBuildVector = true;
7366 // Add the mask index for the new shuffle vector.
7367 Mask.push_back(Idx + OpNo * NumLaneElems);
7370 if (UseBuildVector) {
7371 SmallVector<SDValue, 16> SVOps;
7372 for (unsigned i = 0; i != NumLaneElems; ++i) {
7373 // The mask element. This indexes into the input.
7374 int Idx = SVOp->getMaskElt(i+LaneStart);
7376 SVOps.push_back(DAG.getUNDEF(EltVT));
7380 // The input vector this mask element indexes into.
7381 int Input = Idx / NumElems;
7383 // Turn the index into an offset from the start of the input vector.
7384 Idx -= Input * NumElems;
7386 // Extract the vector element by hand.
7387 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7388 SVOp->getOperand(Input),
7389 DAG.getIntPtrConstant(Idx)));
7392 // Construct the output using a BUILD_VECTOR.
7393 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7394 } else if (InputUsed[0] < 0) {
7395 // No input vectors were used! The result is undefined.
7396 Output[l] = DAG.getUNDEF(NVT);
7398 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7399 (InputUsed[0] % 2) * NumLaneElems,
7401 // If only one input was used, use an undefined vector for the other.
7402 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7403 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7404 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7405 // At least one input vector was used. Create a new shuffle vector.
7406 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7412 // Concatenate the result back
7413 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7416 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7417 /// 4 elements, and match them with several different shuffle types.
7419 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7420 SDValue V1 = SVOp->getOperand(0);
7421 SDValue V2 = SVOp->getOperand(1);
7423 MVT VT = SVOp->getSimpleValueType(0);
7425 assert(VT.is128BitVector() && "Unsupported vector size");
7427 std::pair<int, int> Locs[4];
7428 int Mask1[] = { -1, -1, -1, -1 };
7429 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7433 for (unsigned i = 0; i != 4; ++i) {
7434 int Idx = PermMask[i];
7436 Locs[i] = std::make_pair(-1, -1);
7438 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7440 Locs[i] = std::make_pair(0, NumLo);
7444 Locs[i] = std::make_pair(1, NumHi);
7446 Mask1[2+NumHi] = Idx;
7452 if (NumLo <= 2 && NumHi <= 2) {
7453 // If no more than two elements come from either vector. This can be
7454 // implemented with two shuffles. First shuffle gather the elements.
7455 // The second shuffle, which takes the first shuffle as both of its
7456 // vector operands, put the elements into the right order.
7457 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7459 int Mask2[] = { -1, -1, -1, -1 };
7461 for (unsigned i = 0; i != 4; ++i)
7462 if (Locs[i].first != -1) {
7463 unsigned Idx = (i < 2) ? 0 : 4;
7464 Idx += Locs[i].first * 2 + Locs[i].second;
7468 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7471 if (NumLo == 3 || NumHi == 3) {
7472 // Otherwise, we must have three elements from one vector, call it X, and
7473 // one element from the other, call it Y. First, use a shufps to build an
7474 // intermediate vector with the one element from Y and the element from X
7475 // that will be in the same half in the final destination (the indexes don't
7476 // matter). Then, use a shufps to build the final vector, taking the half
7477 // containing the element from Y from the intermediate, and the other half
7480 // Normalize it so the 3 elements come from V1.
7481 CommuteVectorShuffleMask(PermMask, 4);
7485 // Find the element from V2.
7487 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7488 int Val = PermMask[HiIndex];
7495 Mask1[0] = PermMask[HiIndex];
7497 Mask1[2] = PermMask[HiIndex^1];
7499 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7502 Mask1[0] = PermMask[0];
7503 Mask1[1] = PermMask[1];
7504 Mask1[2] = HiIndex & 1 ? 6 : 4;
7505 Mask1[3] = HiIndex & 1 ? 4 : 6;
7506 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7509 Mask1[0] = HiIndex & 1 ? 2 : 0;
7510 Mask1[1] = HiIndex & 1 ? 0 : 2;
7511 Mask1[2] = PermMask[2];
7512 Mask1[3] = PermMask[3];
7517 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7520 // Break it into (shuffle shuffle_hi, shuffle_lo).
7521 int LoMask[] = { -1, -1, -1, -1 };
7522 int HiMask[] = { -1, -1, -1, -1 };
7524 int *MaskPtr = LoMask;
7525 unsigned MaskIdx = 0;
7528 for (unsigned i = 0; i != 4; ++i) {
7535 int Idx = PermMask[i];
7537 Locs[i] = std::make_pair(-1, -1);
7538 } else if (Idx < 4) {
7539 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7540 MaskPtr[LoIdx] = Idx;
7543 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7544 MaskPtr[HiIdx] = Idx;
7549 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7550 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7551 int MaskOps[] = { -1, -1, -1, -1 };
7552 for (unsigned i = 0; i != 4; ++i)
7553 if (Locs[i].first != -1)
7554 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7555 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7558 static bool MayFoldVectorLoad(SDValue V) {
7559 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7560 V = V.getOperand(0);
7562 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7563 V = V.getOperand(0);
7564 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7565 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7566 // BUILD_VECTOR (load), undef
7567 V = V.getOperand(0);
7569 return MayFoldLoad(V);
7573 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7574 MVT VT = Op.getSimpleValueType();
7576 // Canonizalize to v2f64.
7577 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7578 return DAG.getNode(ISD::BITCAST, dl, VT,
7579 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7584 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7586 SDValue V1 = Op.getOperand(0);
7587 SDValue V2 = Op.getOperand(1);
7588 MVT VT = Op.getSimpleValueType();
7590 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7592 if (HasSSE2 && VT == MVT::v2f64)
7593 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7595 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7596 return DAG.getNode(ISD::BITCAST, dl, VT,
7597 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7598 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7599 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7603 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7604 SDValue V1 = Op.getOperand(0);
7605 SDValue V2 = Op.getOperand(1);
7606 MVT VT = Op.getSimpleValueType();
7608 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7609 "unsupported shuffle type");
7611 if (V2.getOpcode() == ISD::UNDEF)
7615 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7619 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7620 SDValue V1 = Op.getOperand(0);
7621 SDValue V2 = Op.getOperand(1);
7622 MVT VT = Op.getSimpleValueType();
7623 unsigned NumElems = VT.getVectorNumElements();
7625 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7626 // operand of these instructions is only memory, so check if there's a
7627 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7629 bool CanFoldLoad = false;
7631 // Trivial case, when V2 comes from a load.
7632 if (MayFoldVectorLoad(V2))
7635 // When V1 is a load, it can be folded later into a store in isel, example:
7636 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7638 // (MOVLPSmr addr:$src1, VR128:$src2)
7639 // So, recognize this potential and also use MOVLPS or MOVLPD
7640 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7643 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7645 if (HasSSE2 && NumElems == 2)
7646 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7649 // If we don't care about the second element, proceed to use movss.
7650 if (SVOp->getMaskElt(1) != -1)
7651 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7654 // movl and movlp will both match v2i64, but v2i64 is never matched by
7655 // movl earlier because we make it strict to avoid messing with the movlp load
7656 // folding logic (see the code above getMOVLP call). Match it here then,
7657 // this is horrible, but will stay like this until we move all shuffle
7658 // matching to x86 specific nodes. Note that for the 1st condition all
7659 // types are matched with movsd.
7661 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7662 // as to remove this logic from here, as much as possible
7663 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7664 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7665 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7668 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7670 // Invert the operand order and use SHUFPS to match it.
7671 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7672 getShuffleSHUFImmediate(SVOp), DAG);
7675 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7676 SelectionDAG &DAG) {
7678 MVT VT = Load->getSimpleValueType(0);
7679 MVT EVT = VT.getVectorElementType();
7680 SDValue Addr = Load->getOperand(1);
7681 SDValue NewAddr = DAG.getNode(
7682 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7683 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7686 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7687 DAG.getMachineFunction().getMachineMemOperand(
7688 Load->getMemOperand(), 0, EVT.getStoreSize()));
7692 // It is only safe to call this function if isINSERTPSMask is true for
7693 // this shufflevector mask.
7694 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7695 SelectionDAG &DAG) {
7696 // Generate an insertps instruction when inserting an f32 from memory onto a
7697 // v4f32 or when copying a member from one v4f32 to another.
7698 // We also use it for transferring i32 from one register to another,
7699 // since it simply copies the same bits.
7700 // If we're transferring an i32 from memory to a specific element in a
7701 // register, we output a generic DAG that will match the PINSRD
7703 MVT VT = SVOp->getSimpleValueType(0);
7704 MVT EVT = VT.getVectorElementType();
7705 SDValue V1 = SVOp->getOperand(0);
7706 SDValue V2 = SVOp->getOperand(1);
7707 auto Mask = SVOp->getMask();
7708 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7709 "unsupported vector type for insertps/pinsrd");
7711 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7712 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7713 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7721 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7724 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7725 "More than one element from V1 and from V2, or no elements from one "
7726 "of the vectors. This case should not have returned true from "
7731 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7734 if (MayFoldLoad(From)) {
7735 // Trivial case, when From comes from a load and is only used by the
7736 // shuffle. Make it use insertps from the vector that we need from that
7739 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7740 if (!NewLoad.getNode())
7743 if (EVT == MVT::f32) {
7744 // Create this as a scalar to vector to match the instruction pattern.
7745 SDValue LoadScalarToVector =
7746 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7747 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7748 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7750 } else { // EVT == MVT::i32
7751 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7752 // instruction, to match the PINSRD instruction, which loads an i32 to a
7753 // certain vector element.
7754 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7755 DAG.getConstant(DestIndex, MVT::i32));
7759 // Vector-element-to-vector
7760 unsigned SrcIndex = Mask[DestIndex] % 4;
7761 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7762 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7765 // Reduce a vector shuffle to zext.
7766 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7767 SelectionDAG &DAG) {
7768 // PMOVZX is only available from SSE41.
7769 if (!Subtarget->hasSSE41())
7772 MVT VT = Op.getSimpleValueType();
7774 // Only AVX2 support 256-bit vector integer extending.
7775 if (!Subtarget->hasInt256() && VT.is256BitVector())
7778 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7780 SDValue V1 = Op.getOperand(0);
7781 SDValue V2 = Op.getOperand(1);
7782 unsigned NumElems = VT.getVectorNumElements();
7784 // Extending is an unary operation and the element type of the source vector
7785 // won't be equal to or larger than i64.
7786 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7787 VT.getVectorElementType() == MVT::i64)
7790 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7791 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7792 while ((1U << Shift) < NumElems) {
7793 if (SVOp->getMaskElt(1U << Shift) == 1)
7796 // The maximal ratio is 8, i.e. from i8 to i64.
7801 // Check the shuffle mask.
7802 unsigned Mask = (1U << Shift) - 1;
7803 for (unsigned i = 0; i != NumElems; ++i) {
7804 int EltIdx = SVOp->getMaskElt(i);
7805 if ((i & Mask) != 0 && EltIdx != -1)
7807 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7811 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7812 MVT NeVT = MVT::getIntegerVT(NBits);
7813 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7815 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7818 // Simplify the operand as it's prepared to be fed into shuffle.
7819 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7820 if (V1.getOpcode() == ISD::BITCAST &&
7821 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7822 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7823 V1.getOperand(0).getOperand(0)
7824 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7825 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7826 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7827 ConstantSDNode *CIdx =
7828 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7829 // If it's foldable, i.e. normal load with single use, we will let code
7830 // selection to fold it. Otherwise, we will short the conversion sequence.
7831 if (CIdx && CIdx->getZExtValue() == 0 &&
7832 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7833 MVT FullVT = V.getSimpleValueType();
7834 MVT V1VT = V1.getSimpleValueType();
7835 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7836 // The "ext_vec_elt" node is wider than the result node.
7837 // In this case we should extract subvector from V.
7838 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7839 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7840 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7841 FullVT.getVectorNumElements()/Ratio);
7842 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7843 DAG.getIntPtrConstant(0));
7845 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7849 return DAG.getNode(ISD::BITCAST, DL, VT,
7850 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7853 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7854 SelectionDAG &DAG) {
7855 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7856 MVT VT = Op.getSimpleValueType();
7858 SDValue V1 = Op.getOperand(0);
7859 SDValue V2 = Op.getOperand(1);
7861 if (isZeroShuffle(SVOp))
7862 return getZeroVector(VT, Subtarget, DAG, dl);
7864 // Handle splat operations
7865 if (SVOp->isSplat()) {
7866 // Use vbroadcast whenever the splat comes from a foldable load
7867 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7868 if (Broadcast.getNode())
7872 // Check integer expanding shuffles.
7873 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7874 if (NewOp.getNode())
7877 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7879 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7881 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7882 if (NewOp.getNode())
7883 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7884 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7885 // FIXME: Figure out a cleaner way to do this.
7886 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7887 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7888 if (NewOp.getNode()) {
7889 MVT NewVT = NewOp.getSimpleValueType();
7890 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7891 NewVT, true, false))
7892 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7895 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7896 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7897 if (NewOp.getNode()) {
7898 MVT NewVT = NewOp.getSimpleValueType();
7899 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7900 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7909 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7910 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7911 SDValue V1 = Op.getOperand(0);
7912 SDValue V2 = Op.getOperand(1);
7913 MVT VT = Op.getSimpleValueType();
7915 unsigned NumElems = VT.getVectorNumElements();
7916 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7917 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7918 bool V1IsSplat = false;
7919 bool V2IsSplat = false;
7920 bool HasSSE2 = Subtarget->hasSSE2();
7921 bool HasFp256 = Subtarget->hasFp256();
7922 bool HasInt256 = Subtarget->hasInt256();
7923 MachineFunction &MF = DAG.getMachineFunction();
7924 bool OptForSize = MF.getFunction()->getAttributes().
7925 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7927 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7929 if (V1IsUndef && V2IsUndef)
7930 return DAG.getUNDEF(VT);
7932 // When we create a shuffle node we put the UNDEF node to second operand,
7933 // but in some cases the first operand may be transformed to UNDEF.
7934 // In this case we should just commute the node.
7936 return CommuteVectorShuffle(SVOp, DAG);
7938 // Vector shuffle lowering takes 3 steps:
7940 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7941 // narrowing and commutation of operands should be handled.
7942 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7944 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7945 // so the shuffle can be broken into other shuffles and the legalizer can
7946 // try the lowering again.
7948 // The general idea is that no vector_shuffle operation should be left to
7949 // be matched during isel, all of them must be converted to a target specific
7952 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7953 // narrowing and commutation of operands should be handled. The actual code
7954 // doesn't include all of those, work in progress...
7955 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7956 if (NewOp.getNode())
7959 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7961 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7962 // unpckh_undef). Only use pshufd if speed is more important than size.
7963 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7964 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7965 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7966 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7968 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7969 V2IsUndef && MayFoldVectorLoad(V1))
7970 return getMOVDDup(Op, dl, V1, DAG);
7972 if (isMOVHLPS_v_undef_Mask(M, VT))
7973 return getMOVHighToLow(Op, dl, DAG);
7975 // Use to match splats
7976 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7977 (VT == MVT::v2f64 || VT == MVT::v2i64))
7978 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7980 if (isPSHUFDMask(M, VT)) {
7981 // The actual implementation will match the mask in the if above and then
7982 // during isel it can match several different instructions, not only pshufd
7983 // as its name says, sad but true, emulate the behavior for now...
7984 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7985 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7987 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7989 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7990 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7992 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7993 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7996 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
8000 if (isPALIGNRMask(M, VT, Subtarget))
8001 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
8002 getShufflePALIGNRImmediate(SVOp),
8005 // Check if this can be converted into a logical shift.
8006 bool isLeft = false;
8009 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8010 if (isShift && ShVal.hasOneUse()) {
8011 // If the shifted value has multiple uses, it may be cheaper to use
8012 // v_set0 + movlhps or movhlps, etc.
8013 MVT EltVT = VT.getVectorElementType();
8014 ShAmt *= EltVT.getSizeInBits();
8015 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8018 if (isMOVLMask(M, VT)) {
8019 if (ISD::isBuildVectorAllZeros(V1.getNode()))
8020 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8021 if (!isMOVLPMask(M, VT)) {
8022 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8023 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8025 if (VT == MVT::v4i32 || VT == MVT::v4f32)
8026 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8030 // FIXME: fold these into legal mask.
8031 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8032 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8034 if (isMOVHLPSMask(M, VT))
8035 return getMOVHighToLow(Op, dl, DAG);
8037 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8038 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8040 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8041 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8043 if (isMOVLPMask(M, VT))
8044 return getMOVLP(Op, dl, DAG, HasSSE2);
8046 if (ShouldXformToMOVHLPS(M, VT) ||
8047 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8048 return CommuteVectorShuffle(SVOp, DAG);
8051 // No better options. Use a vshldq / vsrldq.
8052 MVT EltVT = VT.getVectorElementType();
8053 ShAmt *= EltVT.getSizeInBits();
8054 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8057 bool Commuted = false;
8058 // FIXME: This should also accept a bitcast of a splat? Be careful, not
8059 // 1,1,1,1 -> v8i16 though.
8060 V1IsSplat = isSplatVector(V1.getNode());
8061 V2IsSplat = isSplatVector(V2.getNode());
8063 // Canonicalize the splat or undef, if present, to be on the RHS.
8064 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8065 CommuteVectorShuffleMask(M, NumElems);
8067 std::swap(V1IsSplat, V2IsSplat);
8071 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8072 // Shuffling low element of v1 into undef, just return v1.
8075 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8076 // the instruction selector will not match, so get a canonical MOVL with
8077 // swapped operands to undo the commute.
8078 return getMOVL(DAG, dl, VT, V2, V1);
8081 if (isUNPCKLMask(M, VT, HasInt256))
8082 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8084 if (isUNPCKHMask(M, VT, HasInt256))
8085 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8088 // Normalize mask so all entries that point to V2 points to its first
8089 // element then try to match unpck{h|l} again. If match, return a
8090 // new vector_shuffle with the corrected mask.p
8091 SmallVector<int, 8> NewMask(M.begin(), M.end());
8092 NormalizeMask(NewMask, NumElems);
8093 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8094 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8095 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8096 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8100 // Commute is back and try unpck* again.
8101 // FIXME: this seems wrong.
8102 CommuteVectorShuffleMask(M, NumElems);
8104 std::swap(V1IsSplat, V2IsSplat);
8106 if (isUNPCKLMask(M, VT, HasInt256))
8107 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8109 if (isUNPCKHMask(M, VT, HasInt256))
8110 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8113 // Normalize the node to match x86 shuffle ops if needed
8114 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8115 return CommuteVectorShuffle(SVOp, DAG);
8117 // The checks below are all present in isShuffleMaskLegal, but they are
8118 // inlined here right now to enable us to directly emit target specific
8119 // nodes, and remove one by one until they don't return Op anymore.
8121 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8122 SVOp->getSplatIndex() == 0 && V2IsUndef) {
8123 if (VT == MVT::v2f64 || VT == MVT::v2i64)
8124 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8127 if (isPSHUFHWMask(M, VT, HasInt256))
8128 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8129 getShufflePSHUFHWImmediate(SVOp),
8132 if (isPSHUFLWMask(M, VT, HasInt256))
8133 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8134 getShufflePSHUFLWImmediate(SVOp),
8137 if (isSHUFPMask(M, VT))
8138 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8139 getShuffleSHUFImmediate(SVOp), DAG);
8141 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8142 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8143 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8144 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8146 //===--------------------------------------------------------------------===//
8147 // Generate target specific nodes for 128 or 256-bit shuffles only
8148 // supported in the AVX instruction set.
8151 // Handle VMOVDDUPY permutations
8152 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8153 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8155 // Handle VPERMILPS/D* permutations
8156 if (isVPERMILPMask(M, VT)) {
8157 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8158 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8159 getShuffleSHUFImmediate(SVOp), DAG);
8160 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8161 getShuffleSHUFImmediate(SVOp), DAG);
8165 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8166 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8167 Idx*(NumElems/2), DAG, dl);
8169 // Handle VPERM2F128/VPERM2I128 permutations
8170 if (isVPERM2X128Mask(M, VT, HasFp256))
8171 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8172 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8175 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8177 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8179 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8180 return getINSERTPS(SVOp, dl, DAG);
8183 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8184 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8186 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8187 VT.is512BitVector()) {
8188 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8189 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8190 SmallVector<SDValue, 16> permclMask;
8191 for (unsigned i = 0; i != NumElems; ++i) {
8192 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8195 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8197 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8198 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8199 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8200 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8201 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8204 //===--------------------------------------------------------------------===//
8205 // Since no target specific shuffle was selected for this generic one,
8206 // lower it into other known shuffles. FIXME: this isn't true yet, but
8207 // this is the plan.
8210 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8211 if (VT == MVT::v8i16) {
8212 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8213 if (NewOp.getNode())
8217 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8218 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8219 if (NewOp.getNode())
8223 if (VT == MVT::v16i8) {
8224 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8225 if (NewOp.getNode())
8229 if (VT == MVT::v32i8) {
8230 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8231 if (NewOp.getNode())
8235 // Handle all 128-bit wide vectors with 4 elements, and match them with
8236 // several different shuffle types.
8237 if (NumElems == 4 && VT.is128BitVector())
8238 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8240 // Handle general 256-bit shuffles
8241 if (VT.is256BitVector())
8242 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8247 // This function assumes its argument is a BUILD_VECTOR of constants or
8248 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8250 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8251 unsigned &MaskValue) {
8253 unsigned NumElems = BuildVector->getNumOperands();
8254 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8255 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8256 unsigned NumElemsInLane = NumElems / NumLanes;
8258 // Blend for v16i16 should be symetric for the both lanes.
8259 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8260 SDValue EltCond = BuildVector->getOperand(i);
8261 SDValue SndLaneEltCond =
8262 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8264 int Lane1Cond = -1, Lane2Cond = -1;
8265 if (isa<ConstantSDNode>(EltCond))
8266 Lane1Cond = !isZero(EltCond);
8267 if (isa<ConstantSDNode>(SndLaneEltCond))
8268 Lane2Cond = !isZero(SndLaneEltCond);
8270 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8271 // Lane1Cond != 0, means we want the first argument.
8272 // Lane1Cond == 0, means we want the second argument.
8273 // The encoding of this argument is 0 for the first argument, 1
8274 // for the second. Therefore, invert the condition.
8275 MaskValue |= !Lane1Cond << i;
8276 else if (Lane1Cond < 0)
8277 MaskValue |= !Lane2Cond << i;
8284 // Try to lower a vselect node into a simple blend instruction.
8285 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8286 SelectionDAG &DAG) {
8287 SDValue Cond = Op.getOperand(0);
8288 SDValue LHS = Op.getOperand(1);
8289 SDValue RHS = Op.getOperand(2);
8291 MVT VT = Op.getSimpleValueType();
8292 MVT EltVT = VT.getVectorElementType();
8293 unsigned NumElems = VT.getVectorNumElements();
8295 // There is no blend with immediate in AVX-512.
8296 if (VT.is512BitVector())
8299 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8301 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8304 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8307 // Check the mask for BLEND and build the value.
8308 unsigned MaskValue = 0;
8309 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8312 // Convert i32 vectors to floating point if it is not AVX2.
8313 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8315 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8316 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8318 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8319 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8322 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8323 DAG.getConstant(MaskValue, MVT::i32));
8324 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8327 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8328 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8329 if (BlendOp.getNode())
8332 // Some types for vselect were previously set to Expand, not Legal or
8333 // Custom. Return an empty SDValue so we fall-through to Expand, after
8334 // the Custom lowering phase.
8335 MVT VT = Op.getSimpleValueType();
8336 switch (VT.SimpleTy) {
8344 // We couldn't create a "Blend with immediate" node.
8345 // This node should still be legal, but we'll have to emit a blendv*
8350 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8351 MVT VT = Op.getSimpleValueType();
8354 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8357 if (VT.getSizeInBits() == 8) {
8358 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8359 Op.getOperand(0), Op.getOperand(1));
8360 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8361 DAG.getValueType(VT));
8362 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8365 if (VT.getSizeInBits() == 16) {
8366 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8367 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8369 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8370 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8371 DAG.getNode(ISD::BITCAST, dl,
8375 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8376 Op.getOperand(0), Op.getOperand(1));
8377 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8378 DAG.getValueType(VT));
8379 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8382 if (VT == MVT::f32) {
8383 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8384 // the result back to FR32 register. It's only worth matching if the
8385 // result has a single use which is a store or a bitcast to i32. And in
8386 // the case of a store, it's not worth it if the index is a constant 0,
8387 // because a MOVSSmr can be used instead, which is smaller and faster.
8388 if (!Op.hasOneUse())
8390 SDNode *User = *Op.getNode()->use_begin();
8391 if ((User->getOpcode() != ISD::STORE ||
8392 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8393 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8394 (User->getOpcode() != ISD::BITCAST ||
8395 User->getValueType(0) != MVT::i32))
8397 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8398 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8401 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8404 if (VT == MVT::i32 || VT == MVT::i64) {
8405 // ExtractPS/pextrq works with constant index.
8406 if (isa<ConstantSDNode>(Op.getOperand(1)))
8412 /// Extract one bit from mask vector, like v16i1 or v8i1.
8413 /// AVX-512 feature.
8415 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8416 SDValue Vec = Op.getOperand(0);
8418 MVT VecVT = Vec.getSimpleValueType();
8419 SDValue Idx = Op.getOperand(1);
8420 MVT EltVT = Op.getSimpleValueType();
8422 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8424 // variable index can't be handled in mask registers,
8425 // extend vector to VR512
8426 if (!isa<ConstantSDNode>(Idx)) {
8427 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8428 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8429 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8430 ExtVT.getVectorElementType(), Ext, Idx);
8431 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8434 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8435 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8436 unsigned MaxSift = rc->getSize()*8 - 1;
8437 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8438 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8439 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8440 DAG.getConstant(MaxSift, MVT::i8));
8441 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8442 DAG.getIntPtrConstant(0));
8446 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8447 SelectionDAG &DAG) const {
8449 SDValue Vec = Op.getOperand(0);
8450 MVT VecVT = Vec.getSimpleValueType();
8451 SDValue Idx = Op.getOperand(1);
8453 if (Op.getSimpleValueType() == MVT::i1)
8454 return ExtractBitFromMaskVector(Op, DAG);
8456 if (!isa<ConstantSDNode>(Idx)) {
8457 if (VecVT.is512BitVector() ||
8458 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8459 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8462 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8463 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8464 MaskEltVT.getSizeInBits());
8466 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8467 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8468 getZeroVector(MaskVT, Subtarget, DAG, dl),
8469 Idx, DAG.getConstant(0, getPointerTy()));
8470 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8471 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8472 Perm, DAG.getConstant(0, getPointerTy()));
8477 // If this is a 256-bit vector result, first extract the 128-bit vector and
8478 // then extract the element from the 128-bit vector.
8479 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8481 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8482 // Get the 128-bit vector.
8483 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8484 MVT EltVT = VecVT.getVectorElementType();
8486 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8488 //if (IdxVal >= NumElems/2)
8489 // IdxVal -= NumElems/2;
8490 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8491 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8492 DAG.getConstant(IdxVal, MVT::i32));
8495 assert(VecVT.is128BitVector() && "Unexpected vector length");
8497 if (Subtarget->hasSSE41()) {
8498 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8503 MVT VT = Op.getSimpleValueType();
8504 // TODO: handle v16i8.
8505 if (VT.getSizeInBits() == 16) {
8506 SDValue Vec = Op.getOperand(0);
8507 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8509 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8510 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8511 DAG.getNode(ISD::BITCAST, dl,
8514 // Transform it so it match pextrw which produces a 32-bit result.
8515 MVT EltVT = MVT::i32;
8516 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8517 Op.getOperand(0), Op.getOperand(1));
8518 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8519 DAG.getValueType(VT));
8520 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8523 if (VT.getSizeInBits() == 32) {
8524 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8528 // SHUFPS the element to the lowest double word, then movss.
8529 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8530 MVT VVT = Op.getOperand(0).getSimpleValueType();
8531 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8532 DAG.getUNDEF(VVT), Mask);
8533 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8534 DAG.getIntPtrConstant(0));
8537 if (VT.getSizeInBits() == 64) {
8538 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8539 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8540 // to match extract_elt for f64.
8541 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8545 // UNPCKHPD the element to the lowest double word, then movsd.
8546 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8547 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8548 int Mask[2] = { 1, -1 };
8549 MVT VVT = Op.getOperand(0).getSimpleValueType();
8550 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8551 DAG.getUNDEF(VVT), Mask);
8552 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8553 DAG.getIntPtrConstant(0));
8559 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8560 MVT VT = Op.getSimpleValueType();
8561 MVT EltVT = VT.getVectorElementType();
8564 SDValue N0 = Op.getOperand(0);
8565 SDValue N1 = Op.getOperand(1);
8566 SDValue N2 = Op.getOperand(2);
8568 if (!VT.is128BitVector())
8571 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8572 isa<ConstantSDNode>(N2)) {
8574 if (VT == MVT::v8i16)
8575 Opc = X86ISD::PINSRW;
8576 else if (VT == MVT::v16i8)
8577 Opc = X86ISD::PINSRB;
8579 Opc = X86ISD::PINSRB;
8581 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8583 if (N1.getValueType() != MVT::i32)
8584 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8585 if (N2.getValueType() != MVT::i32)
8586 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8587 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8590 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8591 // Bits [7:6] of the constant are the source select. This will always be
8592 // zero here. The DAG Combiner may combine an extract_elt index into these
8593 // bits. For example (insert (extract, 3), 2) could be matched by putting
8594 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8595 // Bits [5:4] of the constant are the destination select. This is the
8596 // value of the incoming immediate.
8597 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8598 // combine either bitwise AND or insert of float 0.0 to set these bits.
8599 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8600 // Create this as a scalar to vector..
8601 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8602 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8605 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8606 // PINSR* works with constant index.
8612 /// Insert one bit to mask vector, like v16i1 or v8i1.
8613 /// AVX-512 feature.
8615 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8617 SDValue Vec = Op.getOperand(0);
8618 SDValue Elt = Op.getOperand(1);
8619 SDValue Idx = Op.getOperand(2);
8620 MVT VecVT = Vec.getSimpleValueType();
8622 if (!isa<ConstantSDNode>(Idx)) {
8623 // Non constant index. Extend source and destination,
8624 // insert element and then truncate the result.
8625 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8626 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8627 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8628 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8629 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8630 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8633 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8634 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8635 if (Vec.getOpcode() == ISD::UNDEF)
8636 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8637 DAG.getConstant(IdxVal, MVT::i8));
8638 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8639 unsigned MaxSift = rc->getSize()*8 - 1;
8640 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8641 DAG.getConstant(MaxSift, MVT::i8));
8642 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8643 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8644 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8647 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8648 MVT VT = Op.getSimpleValueType();
8649 MVT EltVT = VT.getVectorElementType();
8651 if (EltVT == MVT::i1)
8652 return InsertBitToMaskVector(Op, DAG);
8655 SDValue N0 = Op.getOperand(0);
8656 SDValue N1 = Op.getOperand(1);
8657 SDValue N2 = Op.getOperand(2);
8659 // If this is a 256-bit vector result, first extract the 128-bit vector,
8660 // insert the element into the extracted half and then place it back.
8661 if (VT.is256BitVector() || VT.is512BitVector()) {
8662 if (!isa<ConstantSDNode>(N2))
8665 // Get the desired 128-bit vector half.
8666 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8667 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8669 // Insert the element into the desired half.
8670 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8671 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8673 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8674 DAG.getConstant(IdxIn128, MVT::i32));
8676 // Insert the changed part back to the 256-bit vector
8677 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8680 if (Subtarget->hasSSE41())
8681 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8683 if (EltVT == MVT::i8)
8686 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8687 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8688 // as its second argument.
8689 if (N1.getValueType() != MVT::i32)
8690 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8691 if (N2.getValueType() != MVT::i32)
8692 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8693 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8698 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8700 MVT OpVT = Op.getSimpleValueType();
8702 // If this is a 256-bit vector result, first insert into a 128-bit
8703 // vector and then insert into the 256-bit vector.
8704 if (!OpVT.is128BitVector()) {
8705 // Insert into a 128-bit vector.
8706 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8707 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8708 OpVT.getVectorNumElements() / SizeFactor);
8710 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8712 // Insert the 128-bit vector.
8713 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8716 if (OpVT == MVT::v1i64 &&
8717 Op.getOperand(0).getValueType() == MVT::i64)
8718 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8720 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8721 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8722 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8723 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8726 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8727 // a simple subregister reference or explicit instructions to grab
8728 // upper bits of a vector.
8729 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8730 SelectionDAG &DAG) {
8732 SDValue In = Op.getOperand(0);
8733 SDValue Idx = Op.getOperand(1);
8734 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8735 MVT ResVT = Op.getSimpleValueType();
8736 MVT InVT = In.getSimpleValueType();
8738 if (Subtarget->hasFp256()) {
8739 if (ResVT.is128BitVector() &&
8740 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8741 isa<ConstantSDNode>(Idx)) {
8742 return Extract128BitVector(In, IdxVal, DAG, dl);
8744 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8745 isa<ConstantSDNode>(Idx)) {
8746 return Extract256BitVector(In, IdxVal, DAG, dl);
8752 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8753 // simple superregister reference or explicit instructions to insert
8754 // the upper bits of a vector.
8755 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8756 SelectionDAG &DAG) {
8757 if (Subtarget->hasFp256()) {
8758 SDLoc dl(Op.getNode());
8759 SDValue Vec = Op.getNode()->getOperand(0);
8760 SDValue SubVec = Op.getNode()->getOperand(1);
8761 SDValue Idx = Op.getNode()->getOperand(2);
8763 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8764 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8765 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8766 isa<ConstantSDNode>(Idx)) {
8767 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8768 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8771 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8772 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8773 isa<ConstantSDNode>(Idx)) {
8774 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8775 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8781 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8782 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8783 // one of the above mentioned nodes. It has to be wrapped because otherwise
8784 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8785 // be used to form addressing mode. These wrapped nodes will be selected
8788 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8789 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8791 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8793 unsigned char OpFlag = 0;
8794 unsigned WrapperKind = X86ISD::Wrapper;
8795 CodeModel::Model M = DAG.getTarget().getCodeModel();
8797 if (Subtarget->isPICStyleRIPRel() &&
8798 (M == CodeModel::Small || M == CodeModel::Kernel))
8799 WrapperKind = X86ISD::WrapperRIP;
8800 else if (Subtarget->isPICStyleGOT())
8801 OpFlag = X86II::MO_GOTOFF;
8802 else if (Subtarget->isPICStyleStubPIC())
8803 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8805 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8807 CP->getOffset(), OpFlag);
8809 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8810 // With PIC, the address is actually $g + Offset.
8812 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8813 DAG.getNode(X86ISD::GlobalBaseReg,
8814 SDLoc(), getPointerTy()),
8821 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8822 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8824 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8826 unsigned char OpFlag = 0;
8827 unsigned WrapperKind = X86ISD::Wrapper;
8828 CodeModel::Model M = DAG.getTarget().getCodeModel();
8830 if (Subtarget->isPICStyleRIPRel() &&
8831 (M == CodeModel::Small || M == CodeModel::Kernel))
8832 WrapperKind = X86ISD::WrapperRIP;
8833 else if (Subtarget->isPICStyleGOT())
8834 OpFlag = X86II::MO_GOTOFF;
8835 else if (Subtarget->isPICStyleStubPIC())
8836 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8838 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8841 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8843 // With PIC, the address is actually $g + Offset.
8845 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8846 DAG.getNode(X86ISD::GlobalBaseReg,
8847 SDLoc(), getPointerTy()),
8854 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8855 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8857 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8859 unsigned char OpFlag = 0;
8860 unsigned WrapperKind = X86ISD::Wrapper;
8861 CodeModel::Model M = DAG.getTarget().getCodeModel();
8863 if (Subtarget->isPICStyleRIPRel() &&
8864 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8865 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8866 OpFlag = X86II::MO_GOTPCREL;
8867 WrapperKind = X86ISD::WrapperRIP;
8868 } else if (Subtarget->isPICStyleGOT()) {
8869 OpFlag = X86II::MO_GOT;
8870 } else if (Subtarget->isPICStyleStubPIC()) {
8871 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8872 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8873 OpFlag = X86II::MO_DARWIN_NONLAZY;
8876 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8879 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8881 // With PIC, the address is actually $g + Offset.
8882 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
8883 !Subtarget->is64Bit()) {
8884 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8885 DAG.getNode(X86ISD::GlobalBaseReg,
8886 SDLoc(), getPointerTy()),
8890 // For symbols that require a load from a stub to get the address, emit the
8892 if (isGlobalStubReference(OpFlag))
8893 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8894 MachinePointerInfo::getGOT(), false, false, false, 0);
8900 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8901 // Create the TargetBlockAddressAddress node.
8902 unsigned char OpFlags =
8903 Subtarget->ClassifyBlockAddressReference();
8904 CodeModel::Model M = DAG.getTarget().getCodeModel();
8905 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8906 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8908 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8911 if (Subtarget->isPICStyleRIPRel() &&
8912 (M == CodeModel::Small || M == CodeModel::Kernel))
8913 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8915 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8917 // With PIC, the address is actually $g + Offset.
8918 if (isGlobalRelativeToPICBase(OpFlags)) {
8919 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8920 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8928 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8929 int64_t Offset, SelectionDAG &DAG) const {
8930 // Create the TargetGlobalAddress node, folding in the constant
8931 // offset if it is legal.
8932 unsigned char OpFlags =
8933 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
8934 CodeModel::Model M = DAG.getTarget().getCodeModel();
8936 if (OpFlags == X86II::MO_NO_FLAG &&
8937 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8938 // A direct static reference to a global.
8939 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8942 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8945 if (Subtarget->isPICStyleRIPRel() &&
8946 (M == CodeModel::Small || M == CodeModel::Kernel))
8947 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8949 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8951 // With PIC, the address is actually $g + Offset.
8952 if (isGlobalRelativeToPICBase(OpFlags)) {
8953 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8954 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8958 // For globals that require a load from a stub to get the address, emit the
8960 if (isGlobalStubReference(OpFlags))
8961 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8962 MachinePointerInfo::getGOT(), false, false, false, 0);
8964 // If there was a non-zero offset that we didn't fold, create an explicit
8967 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8968 DAG.getConstant(Offset, getPointerTy()));
8974 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8975 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8976 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8977 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8981 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8982 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8983 unsigned char OperandFlags, bool LocalDynamic = false) {
8984 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8985 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8987 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8988 GA->getValueType(0),
8992 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8996 SDValue Ops[] = { Chain, TGA, *InFlag };
8997 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8999 SDValue Ops[] = { Chain, TGA };
9000 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9003 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9004 MFI->setAdjustsStack(true);
9006 SDValue Flag = Chain.getValue(1);
9007 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9010 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9012 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9015 SDLoc dl(GA); // ? function entry point might be better
9016 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9017 DAG.getNode(X86ISD::GlobalBaseReg,
9018 SDLoc(), PtrVT), InFlag);
9019 InFlag = Chain.getValue(1);
9021 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9024 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9026 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9028 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9029 X86::RAX, X86II::MO_TLSGD);
9032 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9038 // Get the start address of the TLS block for this module.
9039 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9040 .getInfo<X86MachineFunctionInfo>();
9041 MFI->incNumLocalDynamicTLSAccesses();
9045 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9046 X86II::MO_TLSLD, /*LocalDynamic=*/true);
9049 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9050 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9051 InFlag = Chain.getValue(1);
9052 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9053 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9056 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9060 unsigned char OperandFlags = X86II::MO_DTPOFF;
9061 unsigned WrapperKind = X86ISD::Wrapper;
9062 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9063 GA->getValueType(0),
9064 GA->getOffset(), OperandFlags);
9065 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9067 // Add x@dtpoff with the base.
9068 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9071 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9072 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9073 const EVT PtrVT, TLSModel::Model model,
9074 bool is64Bit, bool isPIC) {
9077 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9078 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9079 is64Bit ? 257 : 256));
9081 SDValue ThreadPointer =
9082 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9083 MachinePointerInfo(Ptr), false, false, false, 0);
9085 unsigned char OperandFlags = 0;
9086 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
9088 unsigned WrapperKind = X86ISD::Wrapper;
9089 if (model == TLSModel::LocalExec) {
9090 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9091 } else if (model == TLSModel::InitialExec) {
9093 OperandFlags = X86II::MO_GOTTPOFF;
9094 WrapperKind = X86ISD::WrapperRIP;
9096 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9099 llvm_unreachable("Unexpected model");
9102 // emit "addl x@ntpoff,%eax" (local exec)
9103 // or "addl x@indntpoff,%eax" (initial exec)
9104 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9106 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9107 GA->getOffset(), OperandFlags);
9108 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9110 if (model == TLSModel::InitialExec) {
9111 if (isPIC && !is64Bit) {
9112 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9113 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9117 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9118 MachinePointerInfo::getGOT(), false, false, false, 0);
9121 // The address of the thread local variable is the add of the thread
9122 // pointer with the offset of the variable.
9123 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9127 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9129 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9130 const GlobalValue *GV = GA->getGlobal();
9132 if (Subtarget->isTargetELF()) {
9133 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9136 case TLSModel::GeneralDynamic:
9137 if (Subtarget->is64Bit())
9138 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9139 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9140 case TLSModel::LocalDynamic:
9141 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9142 Subtarget->is64Bit());
9143 case TLSModel::InitialExec:
9144 case TLSModel::LocalExec:
9145 return LowerToTLSExecModel(
9146 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9147 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9149 llvm_unreachable("Unknown TLS model.");
9152 if (Subtarget->isTargetDarwin()) {
9153 // Darwin only has one model of TLS. Lower to that.
9154 unsigned char OpFlag = 0;
9155 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9156 X86ISD::WrapperRIP : X86ISD::Wrapper;
9158 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9160 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9161 !Subtarget->is64Bit();
9163 OpFlag = X86II::MO_TLVP_PIC_BASE;
9165 OpFlag = X86II::MO_TLVP;
9167 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9168 GA->getValueType(0),
9169 GA->getOffset(), OpFlag);
9170 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9172 // With PIC32, the address is actually $g + Offset.
9174 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9175 DAG.getNode(X86ISD::GlobalBaseReg,
9176 SDLoc(), getPointerTy()),
9179 // Lowering the machine isd will make sure everything is in the right
9181 SDValue Chain = DAG.getEntryNode();
9182 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9183 SDValue Args[] = { Chain, Offset };
9184 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9186 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9187 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9188 MFI->setAdjustsStack(true);
9190 // And our return value (tls address) is in the standard call return value
9192 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9193 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9197 if (Subtarget->isTargetKnownWindowsMSVC() ||
9198 Subtarget->isTargetWindowsGNU()) {
9199 // Just use the implicit TLS architecture
9200 // Need to generate someting similar to:
9201 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9203 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9204 // mov rcx, qword [rdx+rcx*8]
9205 // mov eax, .tls$:tlsvar
9206 // [rax+rcx] contains the address
9207 // Windows 64bit: gs:0x58
9208 // Windows 32bit: fs:__tls_array
9211 SDValue Chain = DAG.getEntryNode();
9213 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9214 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9215 // use its literal value of 0x2C.
9216 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9217 ? Type::getInt8PtrTy(*DAG.getContext(),
9219 : Type::getInt32PtrTy(*DAG.getContext(),
9223 Subtarget->is64Bit()
9224 ? DAG.getIntPtrConstant(0x58)
9225 : (Subtarget->isTargetWindowsGNU()
9226 ? DAG.getIntPtrConstant(0x2C)
9227 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9229 SDValue ThreadPointer =
9230 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9231 MachinePointerInfo(Ptr), false, false, false, 0);
9233 // Load the _tls_index variable
9234 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9235 if (Subtarget->is64Bit())
9236 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9237 IDX, MachinePointerInfo(), MVT::i32,
9240 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9241 false, false, false, 0);
9243 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9245 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9247 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9248 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9249 false, false, false, 0);
9251 // Get the offset of start of .tls section
9252 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9253 GA->getValueType(0),
9254 GA->getOffset(), X86II::MO_SECREL);
9255 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9257 // The address of the thread local variable is the add of the thread
9258 // pointer with the offset of the variable.
9259 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9262 llvm_unreachable("TLS not implemented for this target.");
9265 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9266 /// and take a 2 x i32 value to shift plus a shift amount.
9267 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9268 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9269 MVT VT = Op.getSimpleValueType();
9270 unsigned VTBits = VT.getSizeInBits();
9272 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9273 SDValue ShOpLo = Op.getOperand(0);
9274 SDValue ShOpHi = Op.getOperand(1);
9275 SDValue ShAmt = Op.getOperand(2);
9276 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9277 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9279 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9280 DAG.getConstant(VTBits - 1, MVT::i8));
9281 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9282 DAG.getConstant(VTBits - 1, MVT::i8))
9283 : DAG.getConstant(0, VT);
9286 if (Op.getOpcode() == ISD::SHL_PARTS) {
9287 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9288 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9290 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9291 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9294 // If the shift amount is larger or equal than the width of a part we can't
9295 // rely on the results of shld/shrd. Insert a test and select the appropriate
9296 // values for large shift amounts.
9297 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9298 DAG.getConstant(VTBits, MVT::i8));
9299 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9300 AndNode, DAG.getConstant(0, MVT::i8));
9303 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9304 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9305 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9307 if (Op.getOpcode() == ISD::SHL_PARTS) {
9308 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9309 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9311 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9312 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9315 SDValue Ops[2] = { Lo, Hi };
9316 return DAG.getMergeValues(Ops, dl);
9319 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9320 SelectionDAG &DAG) const {
9321 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9323 if (SrcVT.isVector())
9326 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9327 "Unknown SINT_TO_FP to lower!");
9329 // These are really Legal; return the operand so the caller accepts it as
9331 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9333 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9334 Subtarget->is64Bit()) {
9339 unsigned Size = SrcVT.getSizeInBits()/8;
9340 MachineFunction &MF = DAG.getMachineFunction();
9341 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9342 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9343 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9345 MachinePointerInfo::getFixedStack(SSFI),
9347 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9350 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9352 SelectionDAG &DAG) const {
9356 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9358 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9360 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9362 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9364 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9365 MachineMemOperand *MMO;
9367 int SSFI = FI->getIndex();
9369 DAG.getMachineFunction()
9370 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9371 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9373 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9374 StackSlot = StackSlot.getOperand(1);
9376 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9377 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9379 Tys, Ops, SrcVT, MMO);
9382 Chain = Result.getValue(1);
9383 SDValue InFlag = Result.getValue(2);
9385 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9386 // shouldn't be necessary except that RFP cannot be live across
9387 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9388 MachineFunction &MF = DAG.getMachineFunction();
9389 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9390 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9391 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9392 Tys = DAG.getVTList(MVT::Other);
9394 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9396 MachineMemOperand *MMO =
9397 DAG.getMachineFunction()
9398 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9399 MachineMemOperand::MOStore, SSFISize, SSFISize);
9401 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9402 Ops, Op.getValueType(), MMO);
9403 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9404 MachinePointerInfo::getFixedStack(SSFI),
9405 false, false, false, 0);
9411 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9412 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9413 SelectionDAG &DAG) const {
9414 // This algorithm is not obvious. Here it is what we're trying to output:
9417 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9418 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9422 pshufd $0x4e, %xmm0, %xmm1
9428 LLVMContext *Context = DAG.getContext();
9430 // Build some magic constants.
9431 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9432 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9433 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9435 SmallVector<Constant*,2> CV1;
9437 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9438 APInt(64, 0x4330000000000000ULL))));
9440 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9441 APInt(64, 0x4530000000000000ULL))));
9442 Constant *C1 = ConstantVector::get(CV1);
9443 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9445 // Load the 64-bit value into an XMM register.
9446 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9448 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9449 MachinePointerInfo::getConstantPool(),
9450 false, false, false, 16);
9451 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9452 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9455 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9456 MachinePointerInfo::getConstantPool(),
9457 false, false, false, 16);
9458 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9459 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9462 if (Subtarget->hasSSE3()) {
9463 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9464 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9466 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9467 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9469 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9470 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9474 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9475 DAG.getIntPtrConstant(0));
9478 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9479 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9480 SelectionDAG &DAG) const {
9482 // FP constant to bias correct the final result.
9483 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9486 // Load the 32-bit value into an XMM register.
9487 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9490 // Zero out the upper parts of the register.
9491 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9493 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9494 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9495 DAG.getIntPtrConstant(0));
9497 // Or the load with the bias.
9498 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9499 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9500 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9502 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9503 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9504 MVT::v2f64, Bias)));
9505 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9506 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9507 DAG.getIntPtrConstant(0));
9509 // Subtract the bias.
9510 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9512 // Handle final rounding.
9513 EVT DestVT = Op.getValueType();
9515 if (DestVT.bitsLT(MVT::f64))
9516 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9517 DAG.getIntPtrConstant(0));
9518 if (DestVT.bitsGT(MVT::f64))
9519 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9521 // Handle final rounding.
9525 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9526 SelectionDAG &DAG) const {
9527 SDValue N0 = Op.getOperand(0);
9528 MVT SVT = N0.getSimpleValueType();
9531 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9532 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9533 "Custom UINT_TO_FP is not supported!");
9535 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9536 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9537 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9540 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9541 SelectionDAG &DAG) const {
9542 SDValue N0 = Op.getOperand(0);
9545 if (Op.getValueType().isVector())
9546 return lowerUINT_TO_FP_vec(Op, DAG);
9548 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9549 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9550 // the optimization here.
9551 if (DAG.SignBitIsZero(N0))
9552 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9554 MVT SrcVT = N0.getSimpleValueType();
9555 MVT DstVT = Op.getSimpleValueType();
9556 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9557 return LowerUINT_TO_FP_i64(Op, DAG);
9558 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9559 return LowerUINT_TO_FP_i32(Op, DAG);
9560 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9563 // Make a 64-bit buffer, and use it to build an FILD.
9564 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9565 if (SrcVT == MVT::i32) {
9566 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9567 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9568 getPointerTy(), StackSlot, WordOff);
9569 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9570 StackSlot, MachinePointerInfo(),
9572 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9573 OffsetSlot, MachinePointerInfo(),
9575 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9579 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9580 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9581 StackSlot, MachinePointerInfo(),
9583 // For i64 source, we need to add the appropriate power of 2 if the input
9584 // was negative. This is the same as the optimization in
9585 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9586 // we must be careful to do the computation in x87 extended precision, not
9587 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9588 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9589 MachineMemOperand *MMO =
9590 DAG.getMachineFunction()
9591 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9592 MachineMemOperand::MOLoad, 8, 8);
9594 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9595 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9596 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9599 APInt FF(32, 0x5F800000ULL);
9601 // Check whether the sign bit is set.
9602 SDValue SignSet = DAG.getSetCC(dl,
9603 getSetCCResultType(*DAG.getContext(), MVT::i64),
9604 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9607 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9608 SDValue FudgePtr = DAG.getConstantPool(
9609 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9612 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9613 SDValue Zero = DAG.getIntPtrConstant(0);
9614 SDValue Four = DAG.getIntPtrConstant(4);
9615 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9617 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9619 // Load the value out, extending it from f32 to f80.
9620 // FIXME: Avoid the extend by constructing the right constant pool?
9621 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9622 FudgePtr, MachinePointerInfo::getConstantPool(),
9623 MVT::f32, false, false, 4);
9624 // Extend everything to 80 bits to force it to be done on x87.
9625 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9626 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9629 std::pair<SDValue,SDValue>
9630 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9631 bool IsSigned, bool IsReplace) const {
9634 EVT DstTy = Op.getValueType();
9636 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9637 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9641 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9642 DstTy.getSimpleVT() >= MVT::i16 &&
9643 "Unknown FP_TO_INT to lower!");
9645 // These are really Legal.
9646 if (DstTy == MVT::i32 &&
9647 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9648 return std::make_pair(SDValue(), SDValue());
9649 if (Subtarget->is64Bit() &&
9650 DstTy == MVT::i64 &&
9651 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9652 return std::make_pair(SDValue(), SDValue());
9654 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9655 // stack slot, or into the FTOL runtime function.
9656 MachineFunction &MF = DAG.getMachineFunction();
9657 unsigned MemSize = DstTy.getSizeInBits()/8;
9658 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9659 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9662 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9663 Opc = X86ISD::WIN_FTOL;
9665 switch (DstTy.getSimpleVT().SimpleTy) {
9666 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9667 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9668 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9669 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9672 SDValue Chain = DAG.getEntryNode();
9673 SDValue Value = Op.getOperand(0);
9674 EVT TheVT = Op.getOperand(0).getValueType();
9675 // FIXME This causes a redundant load/store if the SSE-class value is already
9676 // in memory, such as if it is on the callstack.
9677 if (isScalarFPTypeInSSEReg(TheVT)) {
9678 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9679 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9680 MachinePointerInfo::getFixedStack(SSFI),
9682 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9684 Chain, StackSlot, DAG.getValueType(TheVT)
9687 MachineMemOperand *MMO =
9688 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9689 MachineMemOperand::MOLoad, MemSize, MemSize);
9690 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9691 Chain = Value.getValue(1);
9692 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9693 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9696 MachineMemOperand *MMO =
9697 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9698 MachineMemOperand::MOStore, MemSize, MemSize);
9700 if (Opc != X86ISD::WIN_FTOL) {
9701 // Build the FP_TO_INT*_IN_MEM
9702 SDValue Ops[] = { Chain, Value, StackSlot };
9703 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9705 return std::make_pair(FIST, StackSlot);
9707 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9708 DAG.getVTList(MVT::Other, MVT::Glue),
9710 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9711 MVT::i32, ftol.getValue(1));
9712 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9713 MVT::i32, eax.getValue(2));
9714 SDValue Ops[] = { eax, edx };
9715 SDValue pair = IsReplace
9716 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9717 : DAG.getMergeValues(Ops, DL);
9718 return std::make_pair(pair, SDValue());
9722 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9723 const X86Subtarget *Subtarget) {
9724 MVT VT = Op->getSimpleValueType(0);
9725 SDValue In = Op->getOperand(0);
9726 MVT InVT = In.getSimpleValueType();
9729 // Optimize vectors in AVX mode:
9732 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9733 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9734 // Concat upper and lower parts.
9737 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9738 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9739 // Concat upper and lower parts.
9742 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9743 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9744 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9747 if (Subtarget->hasInt256())
9748 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9750 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9751 SDValue Undef = DAG.getUNDEF(InVT);
9752 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9753 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9754 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9756 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9757 VT.getVectorNumElements()/2);
9759 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9760 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9762 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9765 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9766 SelectionDAG &DAG) {
9767 MVT VT = Op->getSimpleValueType(0);
9768 SDValue In = Op->getOperand(0);
9769 MVT InVT = In.getSimpleValueType();
9771 unsigned int NumElts = VT.getVectorNumElements();
9772 if (NumElts != 8 && NumElts != 16)
9775 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9776 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9778 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9779 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9780 // Now we have only mask extension
9781 assert(InVT.getVectorElementType() == MVT::i1);
9782 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9783 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9784 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9785 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9786 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9787 MachinePointerInfo::getConstantPool(),
9788 false, false, false, Alignment);
9790 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9791 if (VT.is512BitVector())
9793 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9796 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9797 SelectionDAG &DAG) {
9798 if (Subtarget->hasFp256()) {
9799 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9807 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9808 SelectionDAG &DAG) {
9810 MVT VT = Op.getSimpleValueType();
9811 SDValue In = Op.getOperand(0);
9812 MVT SVT = In.getSimpleValueType();
9814 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9815 return LowerZERO_EXTEND_AVX512(Op, DAG);
9817 if (Subtarget->hasFp256()) {
9818 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9823 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9824 VT.getVectorNumElements() != SVT.getVectorNumElements());
9828 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9830 MVT VT = Op.getSimpleValueType();
9831 SDValue In = Op.getOperand(0);
9832 MVT InVT = In.getSimpleValueType();
9834 if (VT == MVT::i1) {
9835 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9836 "Invalid scalar TRUNCATE operation");
9837 if (InVT == MVT::i32)
9839 if (InVT.getSizeInBits() == 64)
9840 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9841 else if (InVT.getSizeInBits() < 32)
9842 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9843 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9845 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9846 "Invalid TRUNCATE operation");
9848 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9849 if (VT.getVectorElementType().getSizeInBits() >=8)
9850 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9852 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9853 unsigned NumElts = InVT.getVectorNumElements();
9854 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9855 if (InVT.getSizeInBits() < 512) {
9856 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9857 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9861 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9862 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9863 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9864 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9865 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9866 MachinePointerInfo::getConstantPool(),
9867 false, false, false, Alignment);
9868 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9869 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9870 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9873 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9874 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9875 if (Subtarget->hasInt256()) {
9876 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9877 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9878 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9880 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9881 DAG.getIntPtrConstant(0));
9884 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9885 DAG.getIntPtrConstant(0));
9886 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9887 DAG.getIntPtrConstant(2));
9888 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9889 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9890 static const int ShufMask[] = {0, 2, 4, 6};
9891 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9894 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9895 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9896 if (Subtarget->hasInt256()) {
9897 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9899 SmallVector<SDValue,32> pshufbMask;
9900 for (unsigned i = 0; i < 2; ++i) {
9901 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9902 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9903 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9904 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9905 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9906 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9907 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9908 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9909 for (unsigned j = 0; j < 8; ++j)
9910 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9912 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9913 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9914 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9916 static const int ShufMask[] = {0, 2, -1, -1};
9917 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9919 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9920 DAG.getIntPtrConstant(0));
9921 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9924 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9925 DAG.getIntPtrConstant(0));
9927 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9928 DAG.getIntPtrConstant(4));
9930 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9931 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9934 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9935 -1, -1, -1, -1, -1, -1, -1, -1};
9937 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9938 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9939 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9941 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9942 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9944 // The MOVLHPS Mask:
9945 static const int ShufMask2[] = {0, 1, 4, 5};
9946 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9947 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9950 // Handle truncation of V256 to V128 using shuffles.
9951 if (!VT.is128BitVector() || !InVT.is256BitVector())
9954 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9956 unsigned NumElems = VT.getVectorNumElements();
9957 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9959 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9960 // Prepare truncation shuffle mask
9961 for (unsigned i = 0; i != NumElems; ++i)
9963 SDValue V = DAG.getVectorShuffle(NVT, DL,
9964 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9965 DAG.getUNDEF(NVT), &MaskVec[0]);
9966 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9967 DAG.getIntPtrConstant(0));
9970 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9971 SelectionDAG &DAG) const {
9972 assert(!Op.getSimpleValueType().isVector());
9974 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9975 /*IsSigned=*/ true, /*IsReplace=*/ false);
9976 SDValue FIST = Vals.first, StackSlot = Vals.second;
9977 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9978 if (!FIST.getNode()) return Op;
9980 if (StackSlot.getNode())
9982 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9983 FIST, StackSlot, MachinePointerInfo(),
9984 false, false, false, 0);
9986 // The node is the result.
9990 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9991 SelectionDAG &DAG) const {
9992 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9993 /*IsSigned=*/ false, /*IsReplace=*/ false);
9994 SDValue FIST = Vals.first, StackSlot = Vals.second;
9995 assert(FIST.getNode() && "Unexpected failure");
9997 if (StackSlot.getNode())
9999 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10000 FIST, StackSlot, MachinePointerInfo(),
10001 false, false, false, 0);
10003 // The node is the result.
10007 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10009 MVT VT = Op.getSimpleValueType();
10010 SDValue In = Op.getOperand(0);
10011 MVT SVT = In.getSimpleValueType();
10013 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10015 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10016 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10017 In, DAG.getUNDEF(SVT)));
10020 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10021 LLVMContext *Context = DAG.getContext();
10023 MVT VT = Op.getSimpleValueType();
10025 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10026 if (VT.isVector()) {
10027 EltVT = VT.getVectorElementType();
10028 NumElts = VT.getVectorNumElements();
10031 if (EltVT == MVT::f64)
10032 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10033 APInt(64, ~(1ULL << 63))));
10035 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10036 APInt(32, ~(1U << 31))));
10037 C = ConstantVector::getSplat(NumElts, C);
10038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10039 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10040 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10041 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10042 MachinePointerInfo::getConstantPool(),
10043 false, false, false, Alignment);
10044 if (VT.isVector()) {
10045 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10046 return DAG.getNode(ISD::BITCAST, dl, VT,
10047 DAG.getNode(ISD::AND, dl, ANDVT,
10048 DAG.getNode(ISD::BITCAST, dl, ANDVT,
10050 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10052 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10055 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10056 LLVMContext *Context = DAG.getContext();
10058 MVT VT = Op.getSimpleValueType();
10060 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10061 if (VT.isVector()) {
10062 EltVT = VT.getVectorElementType();
10063 NumElts = VT.getVectorNumElements();
10066 if (EltVT == MVT::f64)
10067 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10068 APInt(64, 1ULL << 63)));
10070 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10071 APInt(32, 1U << 31)));
10072 C = ConstantVector::getSplat(NumElts, C);
10073 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10074 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10075 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10076 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10077 MachinePointerInfo::getConstantPool(),
10078 false, false, false, Alignment);
10079 if (VT.isVector()) {
10080 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10081 return DAG.getNode(ISD::BITCAST, dl, VT,
10082 DAG.getNode(ISD::XOR, dl, XORVT,
10083 DAG.getNode(ISD::BITCAST, dl, XORVT,
10085 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10088 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10091 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10092 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10093 LLVMContext *Context = DAG.getContext();
10094 SDValue Op0 = Op.getOperand(0);
10095 SDValue Op1 = Op.getOperand(1);
10097 MVT VT = Op.getSimpleValueType();
10098 MVT SrcVT = Op1.getSimpleValueType();
10100 // If second operand is smaller, extend it first.
10101 if (SrcVT.bitsLT(VT)) {
10102 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10105 // And if it is bigger, shrink it first.
10106 if (SrcVT.bitsGT(VT)) {
10107 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10111 // At this point the operands and the result should have the same
10112 // type, and that won't be f80 since that is not custom lowered.
10114 // First get the sign bit of second operand.
10115 SmallVector<Constant*,4> CV;
10116 if (SrcVT == MVT::f64) {
10117 const fltSemantics &Sem = APFloat::IEEEdouble;
10118 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10119 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10121 const fltSemantics &Sem = APFloat::IEEEsingle;
10122 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10123 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10124 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10125 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10127 Constant *C = ConstantVector::get(CV);
10128 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10129 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10130 MachinePointerInfo::getConstantPool(),
10131 false, false, false, 16);
10132 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10134 // Shift sign bit right or left if the two operands have different types.
10135 if (SrcVT.bitsGT(VT)) {
10136 // Op0 is MVT::f32, Op1 is MVT::f64.
10137 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10138 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10139 DAG.getConstant(32, MVT::i32));
10140 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10141 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10142 DAG.getIntPtrConstant(0));
10145 // Clear first operand sign bit.
10147 if (VT == MVT::f64) {
10148 const fltSemantics &Sem = APFloat::IEEEdouble;
10149 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10150 APInt(64, ~(1ULL << 63)))));
10151 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10153 const fltSemantics &Sem = APFloat::IEEEsingle;
10154 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10155 APInt(32, ~(1U << 31)))));
10156 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10157 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10158 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10160 C = ConstantVector::get(CV);
10161 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10162 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10163 MachinePointerInfo::getConstantPool(),
10164 false, false, false, 16);
10165 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10167 // Or the value with the sign bit.
10168 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10171 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10172 SDValue N0 = Op.getOperand(0);
10174 MVT VT = Op.getSimpleValueType();
10176 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10177 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10178 DAG.getConstant(1, VT));
10179 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10182 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10184 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10185 SelectionDAG &DAG) {
10186 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10188 if (!Subtarget->hasSSE41())
10191 if (!Op->hasOneUse())
10194 SDNode *N = Op.getNode();
10197 SmallVector<SDValue, 8> Opnds;
10198 DenseMap<SDValue, unsigned> VecInMap;
10199 SmallVector<SDValue, 8> VecIns;
10200 EVT VT = MVT::Other;
10202 // Recognize a special case where a vector is casted into wide integer to
10204 Opnds.push_back(N->getOperand(0));
10205 Opnds.push_back(N->getOperand(1));
10207 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10208 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10209 // BFS traverse all OR'd operands.
10210 if (I->getOpcode() == ISD::OR) {
10211 Opnds.push_back(I->getOperand(0));
10212 Opnds.push_back(I->getOperand(1));
10213 // Re-evaluate the number of nodes to be traversed.
10214 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10218 // Quit if a non-EXTRACT_VECTOR_ELT
10219 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10222 // Quit if without a constant index.
10223 SDValue Idx = I->getOperand(1);
10224 if (!isa<ConstantSDNode>(Idx))
10227 SDValue ExtractedFromVec = I->getOperand(0);
10228 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10229 if (M == VecInMap.end()) {
10230 VT = ExtractedFromVec.getValueType();
10231 // Quit if not 128/256-bit vector.
10232 if (!VT.is128BitVector() && !VT.is256BitVector())
10234 // Quit if not the same type.
10235 if (VecInMap.begin() != VecInMap.end() &&
10236 VT != VecInMap.begin()->first.getValueType())
10238 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10239 VecIns.push_back(ExtractedFromVec);
10241 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10244 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10245 "Not extracted from 128-/256-bit vector.");
10247 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10249 for (DenseMap<SDValue, unsigned>::const_iterator
10250 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10251 // Quit if not all elements are used.
10252 if (I->second != FullMask)
10256 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10258 // Cast all vectors into TestVT for PTEST.
10259 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10260 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10262 // If more than one full vectors are evaluated, OR them first before PTEST.
10263 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10264 // Each iteration will OR 2 nodes and append the result until there is only
10265 // 1 node left, i.e. the final OR'd value of all vectors.
10266 SDValue LHS = VecIns[Slot];
10267 SDValue RHS = VecIns[Slot + 1];
10268 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10271 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10272 VecIns.back(), VecIns.back());
10275 /// \brief return true if \c Op has a use that doesn't just read flags.
10276 static bool hasNonFlagsUse(SDValue Op) {
10277 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10279 SDNode *User = *UI;
10280 unsigned UOpNo = UI.getOperandNo();
10281 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10282 // Look pass truncate.
10283 UOpNo = User->use_begin().getOperandNo();
10284 User = *User->use_begin();
10287 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10288 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10294 /// Emit nodes that will be selected as "test Op0,Op0", or something
10296 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10297 SelectionDAG &DAG) const {
10298 if (Op.getValueType() == MVT::i1)
10299 // KORTEST instruction should be selected
10300 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10301 DAG.getConstant(0, Op.getValueType()));
10303 // CF and OF aren't always set the way we want. Determine which
10304 // of these we need.
10305 bool NeedCF = false;
10306 bool NeedOF = false;
10309 case X86::COND_A: case X86::COND_AE:
10310 case X86::COND_B: case X86::COND_BE:
10313 case X86::COND_G: case X86::COND_GE:
10314 case X86::COND_L: case X86::COND_LE:
10315 case X86::COND_O: case X86::COND_NO: {
10316 // Check if we really need to set the
10317 // Overflow flag. If NoSignedWrap is present
10318 // that is not actually needed.
10319 switch (Op->getOpcode()) {
10324 const BinaryWithFlagsSDNode *BinNode =
10325 cast<BinaryWithFlagsSDNode>(Op.getNode());
10326 if (BinNode->hasNoSignedWrap())
10336 // See if we can use the EFLAGS value from the operand instead of
10337 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10338 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10339 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10340 // Emit a CMP with 0, which is the TEST pattern.
10341 //if (Op.getValueType() == MVT::i1)
10342 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10343 // DAG.getConstant(0, MVT::i1));
10344 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10345 DAG.getConstant(0, Op.getValueType()));
10347 unsigned Opcode = 0;
10348 unsigned NumOperands = 0;
10350 // Truncate operations may prevent the merge of the SETCC instruction
10351 // and the arithmetic instruction before it. Attempt to truncate the operands
10352 // of the arithmetic instruction and use a reduced bit-width instruction.
10353 bool NeedTruncation = false;
10354 SDValue ArithOp = Op;
10355 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10356 SDValue Arith = Op->getOperand(0);
10357 // Both the trunc and the arithmetic op need to have one user each.
10358 if (Arith->hasOneUse())
10359 switch (Arith.getOpcode()) {
10366 NeedTruncation = true;
10372 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10373 // which may be the result of a CAST. We use the variable 'Op', which is the
10374 // non-casted variable when we check for possible users.
10375 switch (ArithOp.getOpcode()) {
10377 // Due to an isel shortcoming, be conservative if this add is likely to be
10378 // selected as part of a load-modify-store instruction. When the root node
10379 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10380 // uses of other nodes in the match, such as the ADD in this case. This
10381 // leads to the ADD being left around and reselected, with the result being
10382 // two adds in the output. Alas, even if none our users are stores, that
10383 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10384 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10385 // climbing the DAG back to the root, and it doesn't seem to be worth the
10387 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10388 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10389 if (UI->getOpcode() != ISD::CopyToReg &&
10390 UI->getOpcode() != ISD::SETCC &&
10391 UI->getOpcode() != ISD::STORE)
10394 if (ConstantSDNode *C =
10395 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10396 // An add of one will be selected as an INC.
10397 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10398 Opcode = X86ISD::INC;
10403 // An add of negative one (subtract of one) will be selected as a DEC.
10404 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10405 Opcode = X86ISD::DEC;
10411 // Otherwise use a regular EFLAGS-setting add.
10412 Opcode = X86ISD::ADD;
10417 // If we have a constant logical shift that's only used in a comparison
10418 // against zero turn it into an equivalent AND. This allows turning it into
10419 // a TEST instruction later.
10420 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10421 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10422 EVT VT = Op.getValueType();
10423 unsigned BitWidth = VT.getSizeInBits();
10424 unsigned ShAmt = Op->getConstantOperandVal(1);
10425 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10427 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10428 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10429 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10430 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10432 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10433 DAG.getConstant(Mask, VT));
10434 DAG.ReplaceAllUsesWith(Op, New);
10440 // If the primary and result isn't used, don't bother using X86ISD::AND,
10441 // because a TEST instruction will be better.
10442 if (!hasNonFlagsUse(Op))
10448 // Due to the ISEL shortcoming noted above, be conservative if this op is
10449 // likely to be selected as part of a load-modify-store instruction.
10450 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10451 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10452 if (UI->getOpcode() == ISD::STORE)
10455 // Otherwise use a regular EFLAGS-setting instruction.
10456 switch (ArithOp.getOpcode()) {
10457 default: llvm_unreachable("unexpected operator!");
10458 case ISD::SUB: Opcode = X86ISD::SUB; break;
10459 case ISD::XOR: Opcode = X86ISD::XOR; break;
10460 case ISD::AND: Opcode = X86ISD::AND; break;
10462 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10463 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10464 if (EFLAGS.getNode())
10467 Opcode = X86ISD::OR;
10481 return SDValue(Op.getNode(), 1);
10487 // If we found that truncation is beneficial, perform the truncation and
10489 if (NeedTruncation) {
10490 EVT VT = Op.getValueType();
10491 SDValue WideVal = Op->getOperand(0);
10492 EVT WideVT = WideVal.getValueType();
10493 unsigned ConvertedOp = 0;
10494 // Use a target machine opcode to prevent further DAGCombine
10495 // optimizations that may separate the arithmetic operations
10496 // from the setcc node.
10497 switch (WideVal.getOpcode()) {
10499 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10500 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10501 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10502 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10503 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10507 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10508 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10509 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10510 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10511 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10517 // Emit a CMP with 0, which is the TEST pattern.
10518 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10519 DAG.getConstant(0, Op.getValueType()));
10521 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10522 SmallVector<SDValue, 4> Ops;
10523 for (unsigned i = 0; i != NumOperands; ++i)
10524 Ops.push_back(Op.getOperand(i));
10526 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10527 DAG.ReplaceAllUsesWith(Op, New);
10528 return SDValue(New.getNode(), 1);
10531 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10533 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10534 SDLoc dl, SelectionDAG &DAG) const {
10535 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10536 if (C->getAPIntValue() == 0)
10537 return EmitTest(Op0, X86CC, dl, DAG);
10539 if (Op0.getValueType() == MVT::i1)
10540 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10543 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10544 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10545 // Do the comparison at i32 if it's smaller, besides the Atom case.
10546 // This avoids subregister aliasing issues. Keep the smaller reference
10547 // if we're optimizing for size, however, as that'll allow better folding
10548 // of memory operations.
10549 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10550 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10551 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10552 !Subtarget->isAtom()) {
10553 unsigned ExtendOp =
10554 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10555 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10556 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10558 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10559 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10560 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10562 return SDValue(Sub.getNode(), 1);
10564 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10567 /// Convert a comparison if required by the subtarget.
10568 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10569 SelectionDAG &DAG) const {
10570 // If the subtarget does not support the FUCOMI instruction, floating-point
10571 // comparisons have to be converted.
10572 if (Subtarget->hasCMov() ||
10573 Cmp.getOpcode() != X86ISD::CMP ||
10574 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10575 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10578 // The instruction selector will select an FUCOM instruction instead of
10579 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10580 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10581 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10583 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10584 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10585 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10586 DAG.getConstant(8, MVT::i8));
10587 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10588 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10591 static bool isAllOnes(SDValue V) {
10592 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10593 return C && C->isAllOnesValue();
10596 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10597 /// if it's possible.
10598 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10599 SDLoc dl, SelectionDAG &DAG) const {
10600 SDValue Op0 = And.getOperand(0);
10601 SDValue Op1 = And.getOperand(1);
10602 if (Op0.getOpcode() == ISD::TRUNCATE)
10603 Op0 = Op0.getOperand(0);
10604 if (Op1.getOpcode() == ISD::TRUNCATE)
10605 Op1 = Op1.getOperand(0);
10608 if (Op1.getOpcode() == ISD::SHL)
10609 std::swap(Op0, Op1);
10610 if (Op0.getOpcode() == ISD::SHL) {
10611 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10612 if (And00C->getZExtValue() == 1) {
10613 // If we looked past a truncate, check that it's only truncating away
10615 unsigned BitWidth = Op0.getValueSizeInBits();
10616 unsigned AndBitWidth = And.getValueSizeInBits();
10617 if (BitWidth > AndBitWidth) {
10619 DAG.computeKnownBits(Op0, Zeros, Ones);
10620 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10624 RHS = Op0.getOperand(1);
10626 } else if (Op1.getOpcode() == ISD::Constant) {
10627 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10628 uint64_t AndRHSVal = AndRHS->getZExtValue();
10629 SDValue AndLHS = Op0;
10631 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10632 LHS = AndLHS.getOperand(0);
10633 RHS = AndLHS.getOperand(1);
10636 // Use BT if the immediate can't be encoded in a TEST instruction.
10637 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10639 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10643 if (LHS.getNode()) {
10644 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10645 // instruction. Since the shift amount is in-range-or-undefined, we know
10646 // that doing a bittest on the i32 value is ok. We extend to i32 because
10647 // the encoding for the i16 version is larger than the i32 version.
10648 // Also promote i16 to i32 for performance / code size reason.
10649 if (LHS.getValueType() == MVT::i8 ||
10650 LHS.getValueType() == MVT::i16)
10651 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10653 // If the operand types disagree, extend the shift amount to match. Since
10654 // BT ignores high bits (like shifts) we can use anyextend.
10655 if (LHS.getValueType() != RHS.getValueType())
10656 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10658 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10659 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10660 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10661 DAG.getConstant(Cond, MVT::i8), BT);
10667 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10669 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10674 // SSE Condition code mapping:
10683 switch (SetCCOpcode) {
10684 default: llvm_unreachable("Unexpected SETCC condition");
10686 case ISD::SETEQ: SSECC = 0; break;
10688 case ISD::SETGT: Swap = true; // Fallthrough
10690 case ISD::SETOLT: SSECC = 1; break;
10692 case ISD::SETGE: Swap = true; // Fallthrough
10694 case ISD::SETOLE: SSECC = 2; break;
10695 case ISD::SETUO: SSECC = 3; break;
10697 case ISD::SETNE: SSECC = 4; break;
10698 case ISD::SETULE: Swap = true; // Fallthrough
10699 case ISD::SETUGE: SSECC = 5; break;
10700 case ISD::SETULT: Swap = true; // Fallthrough
10701 case ISD::SETUGT: SSECC = 6; break;
10702 case ISD::SETO: SSECC = 7; break;
10704 case ISD::SETONE: SSECC = 8; break;
10707 std::swap(Op0, Op1);
10712 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10713 // ones, and then concatenate the result back.
10714 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10715 MVT VT = Op.getSimpleValueType();
10717 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10718 "Unsupported value type for operation");
10720 unsigned NumElems = VT.getVectorNumElements();
10722 SDValue CC = Op.getOperand(2);
10724 // Extract the LHS vectors
10725 SDValue LHS = Op.getOperand(0);
10726 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10727 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10729 // Extract the RHS vectors
10730 SDValue RHS = Op.getOperand(1);
10731 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10732 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10734 // Issue the operation on the smaller types and concatenate the result back
10735 MVT EltVT = VT.getVectorElementType();
10736 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10737 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10738 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10739 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10742 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10743 const X86Subtarget *Subtarget) {
10744 SDValue Op0 = Op.getOperand(0);
10745 SDValue Op1 = Op.getOperand(1);
10746 SDValue CC = Op.getOperand(2);
10747 MVT VT = Op.getSimpleValueType();
10750 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10751 Op.getValueType().getScalarType() == MVT::i1 &&
10752 "Cannot set masked compare for this operation");
10754 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10756 bool Unsigned = false;
10759 switch (SetCCOpcode) {
10760 default: llvm_unreachable("Unexpected SETCC condition");
10761 case ISD::SETNE: SSECC = 4; break;
10762 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10763 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10764 case ISD::SETLT: Swap = true; //fall-through
10765 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10766 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10767 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10768 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10769 case ISD::SETULE: Unsigned = true; //fall-through
10770 case ISD::SETLE: SSECC = 2; break;
10774 std::swap(Op0, Op1);
10776 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10777 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10778 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10779 DAG.getConstant(SSECC, MVT::i8));
10782 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10783 /// operand \p Op1. If non-trivial (for example because it's not constant)
10784 /// return an empty value.
10785 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10787 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10791 MVT VT = Op1.getSimpleValueType();
10792 MVT EVT = VT.getVectorElementType();
10793 unsigned n = VT.getVectorNumElements();
10794 SmallVector<SDValue, 8> ULTOp1;
10796 for (unsigned i = 0; i < n; ++i) {
10797 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10798 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10801 // Avoid underflow.
10802 APInt Val = Elt->getAPIntValue();
10806 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10809 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10812 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10813 SelectionDAG &DAG) {
10814 SDValue Op0 = Op.getOperand(0);
10815 SDValue Op1 = Op.getOperand(1);
10816 SDValue CC = Op.getOperand(2);
10817 MVT VT = Op.getSimpleValueType();
10818 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10819 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10824 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10825 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10828 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10829 unsigned Opc = X86ISD::CMPP;
10830 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10831 assert(VT.getVectorNumElements() <= 16);
10832 Opc = X86ISD::CMPM;
10834 // In the two special cases we can't handle, emit two comparisons.
10837 unsigned CombineOpc;
10838 if (SetCCOpcode == ISD::SETUEQ) {
10839 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10841 assert(SetCCOpcode == ISD::SETONE);
10842 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10845 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10846 DAG.getConstant(CC0, MVT::i8));
10847 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10848 DAG.getConstant(CC1, MVT::i8));
10849 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10851 // Handle all other FP comparisons here.
10852 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10853 DAG.getConstant(SSECC, MVT::i8));
10856 // Break 256-bit integer vector compare into smaller ones.
10857 if (VT.is256BitVector() && !Subtarget->hasInt256())
10858 return Lower256IntVSETCC(Op, DAG);
10860 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10861 EVT OpVT = Op1.getValueType();
10862 if (Subtarget->hasAVX512()) {
10863 if (Op1.getValueType().is512BitVector() ||
10864 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10865 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10867 // In AVX-512 architecture setcc returns mask with i1 elements,
10868 // But there is no compare instruction for i8 and i16 elements.
10869 // We are not talking about 512-bit operands in this case, these
10870 // types are illegal.
10872 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10873 OpVT.getVectorElementType().getSizeInBits() >= 8))
10874 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10875 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10878 // We are handling one of the integer comparisons here. Since SSE only has
10879 // GT and EQ comparisons for integer, swapping operands and multiple
10880 // operations may be required for some comparisons.
10882 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10883 bool Subus = false;
10885 switch (SetCCOpcode) {
10886 default: llvm_unreachable("Unexpected SETCC condition");
10887 case ISD::SETNE: Invert = true;
10888 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10889 case ISD::SETLT: Swap = true;
10890 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10891 case ISD::SETGE: Swap = true;
10892 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10893 Invert = true; break;
10894 case ISD::SETULT: Swap = true;
10895 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10896 FlipSigns = true; break;
10897 case ISD::SETUGE: Swap = true;
10898 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10899 FlipSigns = true; Invert = true; break;
10902 // Special case: Use min/max operations for SETULE/SETUGE
10903 MVT VET = VT.getVectorElementType();
10905 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10906 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10909 switch (SetCCOpcode) {
10911 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10912 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10915 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10918 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10919 if (!MinMax && hasSubus) {
10920 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10922 // t = psubus Op0, Op1
10923 // pcmpeq t, <0..0>
10924 switch (SetCCOpcode) {
10926 case ISD::SETULT: {
10927 // If the comparison is against a constant we can turn this into a
10928 // setule. With psubus, setule does not require a swap. This is
10929 // beneficial because the constant in the register is no longer
10930 // destructed as the destination so it can be hoisted out of a loop.
10931 // Only do this pre-AVX since vpcmp* is no longer destructive.
10932 if (Subtarget->hasAVX())
10934 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10935 if (ULEOp1.getNode()) {
10937 Subus = true; Invert = false; Swap = false;
10941 // Psubus is better than flip-sign because it requires no inversion.
10942 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10943 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10947 Opc = X86ISD::SUBUS;
10953 std::swap(Op0, Op1);
10955 // Check that the operation in question is available (most are plain SSE2,
10956 // but PCMPGTQ and PCMPEQQ have different requirements).
10957 if (VT == MVT::v2i64) {
10958 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10959 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10961 // First cast everything to the right type.
10962 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10963 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10965 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10966 // bits of the inputs before performing those operations. The lower
10967 // compare is always unsigned.
10970 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10972 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10973 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10974 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10975 Sign, Zero, Sign, Zero);
10977 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10978 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10980 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10981 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10982 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10984 // Create masks for only the low parts/high parts of the 64 bit integers.
10985 static const int MaskHi[] = { 1, 1, 3, 3 };
10986 static const int MaskLo[] = { 0, 0, 2, 2 };
10987 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10988 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10989 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10991 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10992 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10995 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10997 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11000 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
11001 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
11002 // pcmpeqd + pshufd + pand.
11003 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
11005 // First cast everything to the right type.
11006 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11007 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11010 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11012 // Make sure the lower and upper halves are both all-ones.
11013 static const int Mask[] = { 1, 0, 3, 2 };
11014 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11015 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11018 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11020 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11024 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11025 // bits of the inputs before performing those operations.
11027 EVT EltVT = VT.getVectorElementType();
11028 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11029 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11030 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11033 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11035 // If the logical-not of the result is required, perform that now.
11037 Result = DAG.getNOT(dl, Result, VT);
11040 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11043 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11044 getZeroVector(VT, Subtarget, DAG, dl));
11049 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11051 MVT VT = Op.getSimpleValueType();
11053 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11055 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11056 && "SetCC type must be 8-bit or 1-bit integer");
11057 SDValue Op0 = Op.getOperand(0);
11058 SDValue Op1 = Op.getOperand(1);
11060 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11062 // Optimize to BT if possible.
11063 // Lower (X & (1 << N)) == 0 to BT(X, N).
11064 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11065 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11066 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11067 Op1.getOpcode() == ISD::Constant &&
11068 cast<ConstantSDNode>(Op1)->isNullValue() &&
11069 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11070 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11071 if (NewSetCC.getNode())
11075 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
11077 if (Op1.getOpcode() == ISD::Constant &&
11078 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11079 cast<ConstantSDNode>(Op1)->isNullValue()) &&
11080 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11082 // If the input is a setcc, then reuse the input setcc or use a new one with
11083 // the inverted condition.
11084 if (Op0.getOpcode() == X86ISD::SETCC) {
11085 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11086 bool Invert = (CC == ISD::SETNE) ^
11087 cast<ConstantSDNode>(Op1)->isNullValue();
11091 CCode = X86::GetOppositeBranchCondition(CCode);
11092 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11093 DAG.getConstant(CCode, MVT::i8),
11094 Op0.getOperand(1));
11096 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11100 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11101 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11102 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11104 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11105 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11108 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11109 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11110 if (X86CC == X86::COND_INVALID)
11113 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11114 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11115 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11116 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11118 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11122 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11123 static bool isX86LogicalCmp(SDValue Op) {
11124 unsigned Opc = Op.getNode()->getOpcode();
11125 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11126 Opc == X86ISD::SAHF)
11128 if (Op.getResNo() == 1 &&
11129 (Opc == X86ISD::ADD ||
11130 Opc == X86ISD::SUB ||
11131 Opc == X86ISD::ADC ||
11132 Opc == X86ISD::SBB ||
11133 Opc == X86ISD::SMUL ||
11134 Opc == X86ISD::UMUL ||
11135 Opc == X86ISD::INC ||
11136 Opc == X86ISD::DEC ||
11137 Opc == X86ISD::OR ||
11138 Opc == X86ISD::XOR ||
11139 Opc == X86ISD::AND))
11142 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11148 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11149 if (V.getOpcode() != ISD::TRUNCATE)
11152 SDValue VOp0 = V.getOperand(0);
11153 unsigned InBits = VOp0.getValueSizeInBits();
11154 unsigned Bits = V.getValueSizeInBits();
11155 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11158 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11159 bool addTest = true;
11160 SDValue Cond = Op.getOperand(0);
11161 SDValue Op1 = Op.getOperand(1);
11162 SDValue Op2 = Op.getOperand(2);
11164 EVT VT = Op1.getValueType();
11167 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11168 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11169 // sequence later on.
11170 if (Cond.getOpcode() == ISD::SETCC &&
11171 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11172 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11173 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11174 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11175 int SSECC = translateX86FSETCC(
11176 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11179 if (Subtarget->hasAVX512()) {
11180 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11181 DAG.getConstant(SSECC, MVT::i8));
11182 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11184 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11185 DAG.getConstant(SSECC, MVT::i8));
11186 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11187 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11188 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11192 if (Cond.getOpcode() == ISD::SETCC) {
11193 SDValue NewCond = LowerSETCC(Cond, DAG);
11194 if (NewCond.getNode())
11198 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11199 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11200 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11201 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11202 if (Cond.getOpcode() == X86ISD::SETCC &&
11203 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11204 isZero(Cond.getOperand(1).getOperand(1))) {
11205 SDValue Cmp = Cond.getOperand(1);
11207 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11209 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11210 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11211 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11213 SDValue CmpOp0 = Cmp.getOperand(0);
11214 // Apply further optimizations for special cases
11215 // (select (x != 0), -1, 0) -> neg & sbb
11216 // (select (x == 0), 0, -1) -> neg & sbb
11217 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11218 if (YC->isNullValue() &&
11219 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11220 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11221 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11222 DAG.getConstant(0, CmpOp0.getValueType()),
11224 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11225 DAG.getConstant(X86::COND_B, MVT::i8),
11226 SDValue(Neg.getNode(), 1));
11230 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11231 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11232 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11234 SDValue Res = // Res = 0 or -1.
11235 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11236 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11238 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11239 Res = DAG.getNOT(DL, Res, Res.getValueType());
11241 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11242 if (!N2C || !N2C->isNullValue())
11243 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11248 // Look past (and (setcc_carry (cmp ...)), 1).
11249 if (Cond.getOpcode() == ISD::AND &&
11250 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11251 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11252 if (C && C->getAPIntValue() == 1)
11253 Cond = Cond.getOperand(0);
11256 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11257 // setting operand in place of the X86ISD::SETCC.
11258 unsigned CondOpcode = Cond.getOpcode();
11259 if (CondOpcode == X86ISD::SETCC ||
11260 CondOpcode == X86ISD::SETCC_CARRY) {
11261 CC = Cond.getOperand(0);
11263 SDValue Cmp = Cond.getOperand(1);
11264 unsigned Opc = Cmp.getOpcode();
11265 MVT VT = Op.getSimpleValueType();
11267 bool IllegalFPCMov = false;
11268 if (VT.isFloatingPoint() && !VT.isVector() &&
11269 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11270 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11272 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11273 Opc == X86ISD::BT) { // FIXME
11277 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11278 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11279 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11280 Cond.getOperand(0).getValueType() != MVT::i8)) {
11281 SDValue LHS = Cond.getOperand(0);
11282 SDValue RHS = Cond.getOperand(1);
11283 unsigned X86Opcode;
11286 switch (CondOpcode) {
11287 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11288 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11289 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11290 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11291 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11292 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11293 default: llvm_unreachable("unexpected overflowing operator");
11295 if (CondOpcode == ISD::UMULO)
11296 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11299 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11301 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11303 if (CondOpcode == ISD::UMULO)
11304 Cond = X86Op.getValue(2);
11306 Cond = X86Op.getValue(1);
11308 CC = DAG.getConstant(X86Cond, MVT::i8);
11313 // Look pass the truncate if the high bits are known zero.
11314 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11315 Cond = Cond.getOperand(0);
11317 // We know the result of AND is compared against zero. Try to match
11319 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11320 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11321 if (NewSetCC.getNode()) {
11322 CC = NewSetCC.getOperand(0);
11323 Cond = NewSetCC.getOperand(1);
11330 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11331 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11334 // a < b ? -1 : 0 -> RES = ~setcc_carry
11335 // a < b ? 0 : -1 -> RES = setcc_carry
11336 // a >= b ? -1 : 0 -> RES = setcc_carry
11337 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11338 if (Cond.getOpcode() == X86ISD::SUB) {
11339 Cond = ConvertCmpIfNecessary(Cond, DAG);
11340 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11342 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11343 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11344 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11345 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11346 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11347 return DAG.getNOT(DL, Res, Res.getValueType());
11352 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11353 // widen the cmov and push the truncate through. This avoids introducing a new
11354 // branch during isel and doesn't add any extensions.
11355 if (Op.getValueType() == MVT::i8 &&
11356 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11357 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11358 if (T1.getValueType() == T2.getValueType() &&
11359 // Blacklist CopyFromReg to avoid partial register stalls.
11360 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11361 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11362 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11363 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11367 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11368 // condition is true.
11369 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11370 SDValue Ops[] = { Op2, Op1, CC, Cond };
11371 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11374 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11375 MVT VT = Op->getSimpleValueType(0);
11376 SDValue In = Op->getOperand(0);
11377 MVT InVT = In.getSimpleValueType();
11380 unsigned int NumElts = VT.getVectorNumElements();
11381 if (NumElts != 8 && NumElts != 16)
11384 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11385 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11387 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11388 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11390 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11391 Constant *C = ConstantInt::get(*DAG.getContext(),
11392 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11394 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11395 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11396 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11397 MachinePointerInfo::getConstantPool(),
11398 false, false, false, Alignment);
11399 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11400 if (VT.is512BitVector())
11402 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11405 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11406 SelectionDAG &DAG) {
11407 MVT VT = Op->getSimpleValueType(0);
11408 SDValue In = Op->getOperand(0);
11409 MVT InVT = In.getSimpleValueType();
11412 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11413 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11415 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11416 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11417 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11420 if (Subtarget->hasInt256())
11421 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11423 // Optimize vectors in AVX mode
11424 // Sign extend v8i16 to v8i32 and
11427 // Divide input vector into two parts
11428 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11429 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11430 // concat the vectors to original VT
11432 unsigned NumElems = InVT.getVectorNumElements();
11433 SDValue Undef = DAG.getUNDEF(InVT);
11435 SmallVector<int,8> ShufMask1(NumElems, -1);
11436 for (unsigned i = 0; i != NumElems/2; ++i)
11439 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11441 SmallVector<int,8> ShufMask2(NumElems, -1);
11442 for (unsigned i = 0; i != NumElems/2; ++i)
11443 ShufMask2[i] = i + NumElems/2;
11445 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11447 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11448 VT.getVectorNumElements()/2);
11450 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11451 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11453 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11456 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11457 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11458 // from the AND / OR.
11459 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11460 Opc = Op.getOpcode();
11461 if (Opc != ISD::OR && Opc != ISD::AND)
11463 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11464 Op.getOperand(0).hasOneUse() &&
11465 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11466 Op.getOperand(1).hasOneUse());
11469 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11470 // 1 and that the SETCC node has a single use.
11471 static bool isXor1OfSetCC(SDValue Op) {
11472 if (Op.getOpcode() != ISD::XOR)
11474 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11475 if (N1C && N1C->getAPIntValue() == 1) {
11476 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11477 Op.getOperand(0).hasOneUse();
11482 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11483 bool addTest = true;
11484 SDValue Chain = Op.getOperand(0);
11485 SDValue Cond = Op.getOperand(1);
11486 SDValue Dest = Op.getOperand(2);
11489 bool Inverted = false;
11491 if (Cond.getOpcode() == ISD::SETCC) {
11492 // Check for setcc([su]{add,sub,mul}o == 0).
11493 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11494 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11495 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11496 Cond.getOperand(0).getResNo() == 1 &&
11497 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11498 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11499 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11500 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11501 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11502 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11504 Cond = Cond.getOperand(0);
11506 SDValue NewCond = LowerSETCC(Cond, DAG);
11507 if (NewCond.getNode())
11512 // FIXME: LowerXALUO doesn't handle these!!
11513 else if (Cond.getOpcode() == X86ISD::ADD ||
11514 Cond.getOpcode() == X86ISD::SUB ||
11515 Cond.getOpcode() == X86ISD::SMUL ||
11516 Cond.getOpcode() == X86ISD::UMUL)
11517 Cond = LowerXALUO(Cond, DAG);
11520 // Look pass (and (setcc_carry (cmp ...)), 1).
11521 if (Cond.getOpcode() == ISD::AND &&
11522 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11523 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11524 if (C && C->getAPIntValue() == 1)
11525 Cond = Cond.getOperand(0);
11528 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11529 // setting operand in place of the X86ISD::SETCC.
11530 unsigned CondOpcode = Cond.getOpcode();
11531 if (CondOpcode == X86ISD::SETCC ||
11532 CondOpcode == X86ISD::SETCC_CARRY) {
11533 CC = Cond.getOperand(0);
11535 SDValue Cmp = Cond.getOperand(1);
11536 unsigned Opc = Cmp.getOpcode();
11537 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11538 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11542 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11546 // These can only come from an arithmetic instruction with overflow,
11547 // e.g. SADDO, UADDO.
11548 Cond = Cond.getNode()->getOperand(1);
11554 CondOpcode = Cond.getOpcode();
11555 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11556 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11557 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11558 Cond.getOperand(0).getValueType() != MVT::i8)) {
11559 SDValue LHS = Cond.getOperand(0);
11560 SDValue RHS = Cond.getOperand(1);
11561 unsigned X86Opcode;
11564 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11565 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11567 switch (CondOpcode) {
11568 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11570 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11572 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11575 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11576 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11578 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11580 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11583 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11584 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11585 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11586 default: llvm_unreachable("unexpected overflowing operator");
11589 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11590 if (CondOpcode == ISD::UMULO)
11591 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11594 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11596 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11598 if (CondOpcode == ISD::UMULO)
11599 Cond = X86Op.getValue(2);
11601 Cond = X86Op.getValue(1);
11603 CC = DAG.getConstant(X86Cond, MVT::i8);
11607 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11608 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11609 if (CondOpc == ISD::OR) {
11610 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11611 // two branches instead of an explicit OR instruction with a
11613 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11614 isX86LogicalCmp(Cmp)) {
11615 CC = Cond.getOperand(0).getOperand(0);
11616 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11617 Chain, Dest, CC, Cmp);
11618 CC = Cond.getOperand(1).getOperand(0);
11622 } else { // ISD::AND
11623 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11624 // two branches instead of an explicit AND instruction with a
11625 // separate test. However, we only do this if this block doesn't
11626 // have a fall-through edge, because this requires an explicit
11627 // jmp when the condition is false.
11628 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11629 isX86LogicalCmp(Cmp) &&
11630 Op.getNode()->hasOneUse()) {
11631 X86::CondCode CCode =
11632 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11633 CCode = X86::GetOppositeBranchCondition(CCode);
11634 CC = DAG.getConstant(CCode, MVT::i8);
11635 SDNode *User = *Op.getNode()->use_begin();
11636 // Look for an unconditional branch following this conditional branch.
11637 // We need this because we need to reverse the successors in order
11638 // to implement FCMP_OEQ.
11639 if (User->getOpcode() == ISD::BR) {
11640 SDValue FalseBB = User->getOperand(1);
11642 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11643 assert(NewBR == User);
11647 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11648 Chain, Dest, CC, Cmp);
11649 X86::CondCode CCode =
11650 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11651 CCode = X86::GetOppositeBranchCondition(CCode);
11652 CC = DAG.getConstant(CCode, MVT::i8);
11658 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11659 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11660 // It should be transformed during dag combiner except when the condition
11661 // is set by a arithmetics with overflow node.
11662 X86::CondCode CCode =
11663 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11664 CCode = X86::GetOppositeBranchCondition(CCode);
11665 CC = DAG.getConstant(CCode, MVT::i8);
11666 Cond = Cond.getOperand(0).getOperand(1);
11668 } else if (Cond.getOpcode() == ISD::SETCC &&
11669 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11670 // For FCMP_OEQ, we can emit
11671 // two branches instead of an explicit AND instruction with a
11672 // separate test. However, we only do this if this block doesn't
11673 // have a fall-through edge, because this requires an explicit
11674 // jmp when the condition is false.
11675 if (Op.getNode()->hasOneUse()) {
11676 SDNode *User = *Op.getNode()->use_begin();
11677 // Look for an unconditional branch following this conditional branch.
11678 // We need this because we need to reverse the successors in order
11679 // to implement FCMP_OEQ.
11680 if (User->getOpcode() == ISD::BR) {
11681 SDValue FalseBB = User->getOperand(1);
11683 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11684 assert(NewBR == User);
11688 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11689 Cond.getOperand(0), Cond.getOperand(1));
11690 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11691 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11692 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11693 Chain, Dest, CC, Cmp);
11694 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11699 } else if (Cond.getOpcode() == ISD::SETCC &&
11700 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11701 // For FCMP_UNE, we can emit
11702 // two branches instead of an explicit AND instruction with a
11703 // separate test. However, we only do this if this block doesn't
11704 // have a fall-through edge, because this requires an explicit
11705 // jmp when the condition is false.
11706 if (Op.getNode()->hasOneUse()) {
11707 SDNode *User = *Op.getNode()->use_begin();
11708 // Look for an unconditional branch following this conditional branch.
11709 // We need this because we need to reverse the successors in order
11710 // to implement FCMP_UNE.
11711 if (User->getOpcode() == ISD::BR) {
11712 SDValue FalseBB = User->getOperand(1);
11714 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11715 assert(NewBR == User);
11718 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11719 Cond.getOperand(0), Cond.getOperand(1));
11720 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11721 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11722 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11723 Chain, Dest, CC, Cmp);
11724 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11734 // Look pass the truncate if the high bits are known zero.
11735 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11736 Cond = Cond.getOperand(0);
11738 // We know the result of AND is compared against zero. Try to match
11740 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11741 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11742 if (NewSetCC.getNode()) {
11743 CC = NewSetCC.getOperand(0);
11744 Cond = NewSetCC.getOperand(1);
11751 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11752 CC = DAG.getConstant(X86Cond, MVT::i8);
11753 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11755 Cond = ConvertCmpIfNecessary(Cond, DAG);
11756 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11757 Chain, Dest, CC, Cond);
11760 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11761 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11762 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11763 // that the guard pages used by the OS virtual memory manager are allocated in
11764 // correct sequence.
11766 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11767 SelectionDAG &DAG) const {
11768 MachineFunction &MF = DAG.getMachineFunction();
11769 bool SplitStack = MF.shouldSplitStack();
11770 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11776 SDNode* Node = Op.getNode();
11778 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11779 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11780 " not tell us which reg is the stack pointer!");
11781 EVT VT = Node->getValueType(0);
11782 SDValue Tmp1 = SDValue(Node, 0);
11783 SDValue Tmp2 = SDValue(Node, 1);
11784 SDValue Tmp3 = Node->getOperand(2);
11785 SDValue Chain = Tmp1.getOperand(0);
11787 // Chain the dynamic stack allocation so that it doesn't modify the stack
11788 // pointer when other instructions are using the stack.
11789 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11792 SDValue Size = Tmp2.getOperand(1);
11793 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11794 Chain = SP.getValue(1);
11795 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11796 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
11797 unsigned StackAlign = TFI.getStackAlignment();
11798 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11799 if (Align > StackAlign)
11800 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11801 DAG.getConstant(-(uint64_t)Align, VT));
11802 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11804 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11805 DAG.getIntPtrConstant(0, true), SDValue(),
11808 SDValue Ops[2] = { Tmp1, Tmp2 };
11809 return DAG.getMergeValues(Ops, dl);
11813 SDValue Chain = Op.getOperand(0);
11814 SDValue Size = Op.getOperand(1);
11815 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11816 EVT VT = Op.getNode()->getValueType(0);
11818 bool Is64Bit = Subtarget->is64Bit();
11819 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11822 MachineRegisterInfo &MRI = MF.getRegInfo();
11825 // The 64 bit implementation of segmented stacks needs to clobber both r10
11826 // r11. This makes it impossible to use it along with nested parameters.
11827 const Function *F = MF.getFunction();
11829 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11831 if (I->hasNestAttr())
11832 report_fatal_error("Cannot use segmented stacks with functions that "
11833 "have nested arguments.");
11836 const TargetRegisterClass *AddrRegClass =
11837 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11838 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11839 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11840 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11841 DAG.getRegister(Vreg, SPTy));
11842 SDValue Ops1[2] = { Value, Chain };
11843 return DAG.getMergeValues(Ops1, dl);
11846 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11848 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11849 Flag = Chain.getValue(1);
11850 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11852 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11854 const X86RegisterInfo *RegInfo =
11855 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
11856 unsigned SPReg = RegInfo->getStackRegister();
11857 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11858 Chain = SP.getValue(1);
11861 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11862 DAG.getConstant(-(uint64_t)Align, VT));
11863 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11866 SDValue Ops1[2] = { SP, Chain };
11867 return DAG.getMergeValues(Ops1, dl);
11871 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11872 MachineFunction &MF = DAG.getMachineFunction();
11873 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11875 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11878 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11879 // vastart just stores the address of the VarArgsFrameIndex slot into the
11880 // memory location argument.
11881 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11883 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11884 MachinePointerInfo(SV), false, false, 0);
11888 // gp_offset (0 - 6 * 8)
11889 // fp_offset (48 - 48 + 8 * 16)
11890 // overflow_arg_area (point to parameters coming in memory).
11892 SmallVector<SDValue, 8> MemOps;
11893 SDValue FIN = Op.getOperand(1);
11895 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11896 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11898 FIN, MachinePointerInfo(SV), false, false, 0);
11899 MemOps.push_back(Store);
11902 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11903 FIN, DAG.getIntPtrConstant(4));
11904 Store = DAG.getStore(Op.getOperand(0), DL,
11905 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11907 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11908 MemOps.push_back(Store);
11910 // Store ptr to overflow_arg_area
11911 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11912 FIN, DAG.getIntPtrConstant(4));
11913 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11915 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11916 MachinePointerInfo(SV, 8),
11918 MemOps.push_back(Store);
11920 // Store ptr to reg_save_area.
11921 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11922 FIN, DAG.getIntPtrConstant(8));
11923 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11925 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11926 MachinePointerInfo(SV, 16), false, false, 0);
11927 MemOps.push_back(Store);
11928 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11931 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11932 assert(Subtarget->is64Bit() &&
11933 "LowerVAARG only handles 64-bit va_arg!");
11934 assert((Subtarget->isTargetLinux() ||
11935 Subtarget->isTargetDarwin()) &&
11936 "Unhandled target in LowerVAARG");
11937 assert(Op.getNode()->getNumOperands() == 4);
11938 SDValue Chain = Op.getOperand(0);
11939 SDValue SrcPtr = Op.getOperand(1);
11940 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11941 unsigned Align = Op.getConstantOperandVal(3);
11944 EVT ArgVT = Op.getNode()->getValueType(0);
11945 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11946 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11949 // Decide which area this value should be read from.
11950 // TODO: Implement the AMD64 ABI in its entirety. This simple
11951 // selection mechanism works only for the basic types.
11952 if (ArgVT == MVT::f80) {
11953 llvm_unreachable("va_arg for f80 not yet implemented");
11954 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11955 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11956 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11957 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11959 llvm_unreachable("Unhandled argument type in LowerVAARG");
11962 if (ArgMode == 2) {
11963 // Sanity Check: Make sure using fp_offset makes sense.
11964 assert(!DAG.getTarget().Options.UseSoftFloat &&
11965 !(DAG.getMachineFunction()
11966 .getFunction()->getAttributes()
11967 .hasAttribute(AttributeSet::FunctionIndex,
11968 Attribute::NoImplicitFloat)) &&
11969 Subtarget->hasSSE1());
11972 // Insert VAARG_64 node into the DAG
11973 // VAARG_64 returns two values: Variable Argument Address, Chain
11974 SmallVector<SDValue, 11> InstOps;
11975 InstOps.push_back(Chain);
11976 InstOps.push_back(SrcPtr);
11977 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11978 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11979 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11980 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11981 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11982 VTs, InstOps, MVT::i64,
11983 MachinePointerInfo(SV),
11985 /*Volatile=*/false,
11987 /*WriteMem=*/true);
11988 Chain = VAARG.getValue(1);
11990 // Load the next argument and return it
11991 return DAG.getLoad(ArgVT, dl,
11994 MachinePointerInfo(),
11995 false, false, false, 0);
11998 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11999 SelectionDAG &DAG) {
12000 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
12001 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
12002 SDValue Chain = Op.getOperand(0);
12003 SDValue DstPtr = Op.getOperand(1);
12004 SDValue SrcPtr = Op.getOperand(2);
12005 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12006 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12009 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12010 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12012 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12015 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12016 // amount is a constant. Takes immediate version of shift as input.
12017 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12018 SDValue SrcOp, uint64_t ShiftAmt,
12019 SelectionDAG &DAG) {
12020 MVT ElementType = VT.getVectorElementType();
12022 // Fold this packed shift into its first operand if ShiftAmt is 0.
12026 // Check for ShiftAmt >= element width
12027 if (ShiftAmt >= ElementType.getSizeInBits()) {
12028 if (Opc == X86ISD::VSRAI)
12029 ShiftAmt = ElementType.getSizeInBits() - 1;
12031 return DAG.getConstant(0, VT);
12034 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12035 && "Unknown target vector shift-by-constant node");
12037 // Fold this packed vector shift into a build vector if SrcOp is a
12038 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12039 if (VT == SrcOp.getSimpleValueType() &&
12040 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12041 SmallVector<SDValue, 8> Elts;
12042 unsigned NumElts = SrcOp->getNumOperands();
12043 ConstantSDNode *ND;
12046 default: llvm_unreachable(nullptr);
12047 case X86ISD::VSHLI:
12048 for (unsigned i=0; i!=NumElts; ++i) {
12049 SDValue CurrentOp = SrcOp->getOperand(i);
12050 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12051 Elts.push_back(CurrentOp);
12054 ND = cast<ConstantSDNode>(CurrentOp);
12055 const APInt &C = ND->getAPIntValue();
12056 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12059 case X86ISD::VSRLI:
12060 for (unsigned i=0; i!=NumElts; ++i) {
12061 SDValue CurrentOp = SrcOp->getOperand(i);
12062 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12063 Elts.push_back(CurrentOp);
12066 ND = cast<ConstantSDNode>(CurrentOp);
12067 const APInt &C = ND->getAPIntValue();
12068 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12071 case X86ISD::VSRAI:
12072 for (unsigned i=0; i!=NumElts; ++i) {
12073 SDValue CurrentOp = SrcOp->getOperand(i);
12074 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12075 Elts.push_back(CurrentOp);
12078 ND = cast<ConstantSDNode>(CurrentOp);
12079 const APInt &C = ND->getAPIntValue();
12080 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12085 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12088 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12091 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12092 // may or may not be a constant. Takes immediate version of shift as input.
12093 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12094 SDValue SrcOp, SDValue ShAmt,
12095 SelectionDAG &DAG) {
12096 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12098 // Catch shift-by-constant.
12099 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12100 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12101 CShAmt->getZExtValue(), DAG);
12103 // Change opcode to non-immediate version
12105 default: llvm_unreachable("Unknown target vector shift node");
12106 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12107 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12108 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12111 // Need to build a vector containing shift amount
12112 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12115 ShOps[1] = DAG.getConstant(0, MVT::i32);
12116 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12117 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12119 // The return type has to be a 128-bit type with the same element
12120 // type as the input type.
12121 MVT EltVT = VT.getVectorElementType();
12122 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12124 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12125 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12128 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12130 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12132 default: return SDValue(); // Don't custom lower most intrinsics.
12133 // Comparison intrinsics.
12134 case Intrinsic::x86_sse_comieq_ss:
12135 case Intrinsic::x86_sse_comilt_ss:
12136 case Intrinsic::x86_sse_comile_ss:
12137 case Intrinsic::x86_sse_comigt_ss:
12138 case Intrinsic::x86_sse_comige_ss:
12139 case Intrinsic::x86_sse_comineq_ss:
12140 case Intrinsic::x86_sse_ucomieq_ss:
12141 case Intrinsic::x86_sse_ucomilt_ss:
12142 case Intrinsic::x86_sse_ucomile_ss:
12143 case Intrinsic::x86_sse_ucomigt_ss:
12144 case Intrinsic::x86_sse_ucomige_ss:
12145 case Intrinsic::x86_sse_ucomineq_ss:
12146 case Intrinsic::x86_sse2_comieq_sd:
12147 case Intrinsic::x86_sse2_comilt_sd:
12148 case Intrinsic::x86_sse2_comile_sd:
12149 case Intrinsic::x86_sse2_comigt_sd:
12150 case Intrinsic::x86_sse2_comige_sd:
12151 case Intrinsic::x86_sse2_comineq_sd:
12152 case Intrinsic::x86_sse2_ucomieq_sd:
12153 case Intrinsic::x86_sse2_ucomilt_sd:
12154 case Intrinsic::x86_sse2_ucomile_sd:
12155 case Intrinsic::x86_sse2_ucomigt_sd:
12156 case Intrinsic::x86_sse2_ucomige_sd:
12157 case Intrinsic::x86_sse2_ucomineq_sd: {
12161 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12162 case Intrinsic::x86_sse_comieq_ss:
12163 case Intrinsic::x86_sse2_comieq_sd:
12164 Opc = X86ISD::COMI;
12167 case Intrinsic::x86_sse_comilt_ss:
12168 case Intrinsic::x86_sse2_comilt_sd:
12169 Opc = X86ISD::COMI;
12172 case Intrinsic::x86_sse_comile_ss:
12173 case Intrinsic::x86_sse2_comile_sd:
12174 Opc = X86ISD::COMI;
12177 case Intrinsic::x86_sse_comigt_ss:
12178 case Intrinsic::x86_sse2_comigt_sd:
12179 Opc = X86ISD::COMI;
12182 case Intrinsic::x86_sse_comige_ss:
12183 case Intrinsic::x86_sse2_comige_sd:
12184 Opc = X86ISD::COMI;
12187 case Intrinsic::x86_sse_comineq_ss:
12188 case Intrinsic::x86_sse2_comineq_sd:
12189 Opc = X86ISD::COMI;
12192 case Intrinsic::x86_sse_ucomieq_ss:
12193 case Intrinsic::x86_sse2_ucomieq_sd:
12194 Opc = X86ISD::UCOMI;
12197 case Intrinsic::x86_sse_ucomilt_ss:
12198 case Intrinsic::x86_sse2_ucomilt_sd:
12199 Opc = X86ISD::UCOMI;
12202 case Intrinsic::x86_sse_ucomile_ss:
12203 case Intrinsic::x86_sse2_ucomile_sd:
12204 Opc = X86ISD::UCOMI;
12207 case Intrinsic::x86_sse_ucomigt_ss:
12208 case Intrinsic::x86_sse2_ucomigt_sd:
12209 Opc = X86ISD::UCOMI;
12212 case Intrinsic::x86_sse_ucomige_ss:
12213 case Intrinsic::x86_sse2_ucomige_sd:
12214 Opc = X86ISD::UCOMI;
12217 case Intrinsic::x86_sse_ucomineq_ss:
12218 case Intrinsic::x86_sse2_ucomineq_sd:
12219 Opc = X86ISD::UCOMI;
12224 SDValue LHS = Op.getOperand(1);
12225 SDValue RHS = Op.getOperand(2);
12226 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12227 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12228 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12229 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12230 DAG.getConstant(X86CC, MVT::i8), Cond);
12231 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12234 // Arithmetic intrinsics.
12235 case Intrinsic::x86_sse2_pmulu_dq:
12236 case Intrinsic::x86_avx2_pmulu_dq:
12237 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12238 Op.getOperand(1), Op.getOperand(2));
12240 case Intrinsic::x86_sse41_pmuldq:
12241 case Intrinsic::x86_avx2_pmul_dq:
12242 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12243 Op.getOperand(1), Op.getOperand(2));
12245 case Intrinsic::x86_sse2_pmulhu_w:
12246 case Intrinsic::x86_avx2_pmulhu_w:
12247 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12248 Op.getOperand(1), Op.getOperand(2));
12250 case Intrinsic::x86_sse2_pmulh_w:
12251 case Intrinsic::x86_avx2_pmulh_w:
12252 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12253 Op.getOperand(1), Op.getOperand(2));
12255 // SSE2/AVX2 sub with unsigned saturation intrinsics
12256 case Intrinsic::x86_sse2_psubus_b:
12257 case Intrinsic::x86_sse2_psubus_w:
12258 case Intrinsic::x86_avx2_psubus_b:
12259 case Intrinsic::x86_avx2_psubus_w:
12260 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12261 Op.getOperand(1), Op.getOperand(2));
12263 // SSE3/AVX horizontal add/sub intrinsics
12264 case Intrinsic::x86_sse3_hadd_ps:
12265 case Intrinsic::x86_sse3_hadd_pd:
12266 case Intrinsic::x86_avx_hadd_ps_256:
12267 case Intrinsic::x86_avx_hadd_pd_256:
12268 case Intrinsic::x86_sse3_hsub_ps:
12269 case Intrinsic::x86_sse3_hsub_pd:
12270 case Intrinsic::x86_avx_hsub_ps_256:
12271 case Intrinsic::x86_avx_hsub_pd_256:
12272 case Intrinsic::x86_ssse3_phadd_w_128:
12273 case Intrinsic::x86_ssse3_phadd_d_128:
12274 case Intrinsic::x86_avx2_phadd_w:
12275 case Intrinsic::x86_avx2_phadd_d:
12276 case Intrinsic::x86_ssse3_phsub_w_128:
12277 case Intrinsic::x86_ssse3_phsub_d_128:
12278 case Intrinsic::x86_avx2_phsub_w:
12279 case Intrinsic::x86_avx2_phsub_d: {
12282 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12283 case Intrinsic::x86_sse3_hadd_ps:
12284 case Intrinsic::x86_sse3_hadd_pd:
12285 case Intrinsic::x86_avx_hadd_ps_256:
12286 case Intrinsic::x86_avx_hadd_pd_256:
12287 Opcode = X86ISD::FHADD;
12289 case Intrinsic::x86_sse3_hsub_ps:
12290 case Intrinsic::x86_sse3_hsub_pd:
12291 case Intrinsic::x86_avx_hsub_ps_256:
12292 case Intrinsic::x86_avx_hsub_pd_256:
12293 Opcode = X86ISD::FHSUB;
12295 case Intrinsic::x86_ssse3_phadd_w_128:
12296 case Intrinsic::x86_ssse3_phadd_d_128:
12297 case Intrinsic::x86_avx2_phadd_w:
12298 case Intrinsic::x86_avx2_phadd_d:
12299 Opcode = X86ISD::HADD;
12301 case Intrinsic::x86_ssse3_phsub_w_128:
12302 case Intrinsic::x86_ssse3_phsub_d_128:
12303 case Intrinsic::x86_avx2_phsub_w:
12304 case Intrinsic::x86_avx2_phsub_d:
12305 Opcode = X86ISD::HSUB;
12308 return DAG.getNode(Opcode, dl, Op.getValueType(),
12309 Op.getOperand(1), Op.getOperand(2));
12312 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12313 case Intrinsic::x86_sse2_pmaxu_b:
12314 case Intrinsic::x86_sse41_pmaxuw:
12315 case Intrinsic::x86_sse41_pmaxud:
12316 case Intrinsic::x86_avx2_pmaxu_b:
12317 case Intrinsic::x86_avx2_pmaxu_w:
12318 case Intrinsic::x86_avx2_pmaxu_d:
12319 case Intrinsic::x86_sse2_pminu_b:
12320 case Intrinsic::x86_sse41_pminuw:
12321 case Intrinsic::x86_sse41_pminud:
12322 case Intrinsic::x86_avx2_pminu_b:
12323 case Intrinsic::x86_avx2_pminu_w:
12324 case Intrinsic::x86_avx2_pminu_d:
12325 case Intrinsic::x86_sse41_pmaxsb:
12326 case Intrinsic::x86_sse2_pmaxs_w:
12327 case Intrinsic::x86_sse41_pmaxsd:
12328 case Intrinsic::x86_avx2_pmaxs_b:
12329 case Intrinsic::x86_avx2_pmaxs_w:
12330 case Intrinsic::x86_avx2_pmaxs_d:
12331 case Intrinsic::x86_sse41_pminsb:
12332 case Intrinsic::x86_sse2_pmins_w:
12333 case Intrinsic::x86_sse41_pminsd:
12334 case Intrinsic::x86_avx2_pmins_b:
12335 case Intrinsic::x86_avx2_pmins_w:
12336 case Intrinsic::x86_avx2_pmins_d: {
12339 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12340 case Intrinsic::x86_sse2_pmaxu_b:
12341 case Intrinsic::x86_sse41_pmaxuw:
12342 case Intrinsic::x86_sse41_pmaxud:
12343 case Intrinsic::x86_avx2_pmaxu_b:
12344 case Intrinsic::x86_avx2_pmaxu_w:
12345 case Intrinsic::x86_avx2_pmaxu_d:
12346 Opcode = X86ISD::UMAX;
12348 case Intrinsic::x86_sse2_pminu_b:
12349 case Intrinsic::x86_sse41_pminuw:
12350 case Intrinsic::x86_sse41_pminud:
12351 case Intrinsic::x86_avx2_pminu_b:
12352 case Intrinsic::x86_avx2_pminu_w:
12353 case Intrinsic::x86_avx2_pminu_d:
12354 Opcode = X86ISD::UMIN;
12356 case Intrinsic::x86_sse41_pmaxsb:
12357 case Intrinsic::x86_sse2_pmaxs_w:
12358 case Intrinsic::x86_sse41_pmaxsd:
12359 case Intrinsic::x86_avx2_pmaxs_b:
12360 case Intrinsic::x86_avx2_pmaxs_w:
12361 case Intrinsic::x86_avx2_pmaxs_d:
12362 Opcode = X86ISD::SMAX;
12364 case Intrinsic::x86_sse41_pminsb:
12365 case Intrinsic::x86_sse2_pmins_w:
12366 case Intrinsic::x86_sse41_pminsd:
12367 case Intrinsic::x86_avx2_pmins_b:
12368 case Intrinsic::x86_avx2_pmins_w:
12369 case Intrinsic::x86_avx2_pmins_d:
12370 Opcode = X86ISD::SMIN;
12373 return DAG.getNode(Opcode, dl, Op.getValueType(),
12374 Op.getOperand(1), Op.getOperand(2));
12377 // SSE/SSE2/AVX floating point max/min intrinsics.
12378 case Intrinsic::x86_sse_max_ps:
12379 case Intrinsic::x86_sse2_max_pd:
12380 case Intrinsic::x86_avx_max_ps_256:
12381 case Intrinsic::x86_avx_max_pd_256:
12382 case Intrinsic::x86_sse_min_ps:
12383 case Intrinsic::x86_sse2_min_pd:
12384 case Intrinsic::x86_avx_min_ps_256:
12385 case Intrinsic::x86_avx_min_pd_256: {
12388 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12389 case Intrinsic::x86_sse_max_ps:
12390 case Intrinsic::x86_sse2_max_pd:
12391 case Intrinsic::x86_avx_max_ps_256:
12392 case Intrinsic::x86_avx_max_pd_256:
12393 Opcode = X86ISD::FMAX;
12395 case Intrinsic::x86_sse_min_ps:
12396 case Intrinsic::x86_sse2_min_pd:
12397 case Intrinsic::x86_avx_min_ps_256:
12398 case Intrinsic::x86_avx_min_pd_256:
12399 Opcode = X86ISD::FMIN;
12402 return DAG.getNode(Opcode, dl, Op.getValueType(),
12403 Op.getOperand(1), Op.getOperand(2));
12406 // AVX2 variable shift intrinsics
12407 case Intrinsic::x86_avx2_psllv_d:
12408 case Intrinsic::x86_avx2_psllv_q:
12409 case Intrinsic::x86_avx2_psllv_d_256:
12410 case Intrinsic::x86_avx2_psllv_q_256:
12411 case Intrinsic::x86_avx2_psrlv_d:
12412 case Intrinsic::x86_avx2_psrlv_q:
12413 case Intrinsic::x86_avx2_psrlv_d_256:
12414 case Intrinsic::x86_avx2_psrlv_q_256:
12415 case Intrinsic::x86_avx2_psrav_d:
12416 case Intrinsic::x86_avx2_psrav_d_256: {
12419 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12420 case Intrinsic::x86_avx2_psllv_d:
12421 case Intrinsic::x86_avx2_psllv_q:
12422 case Intrinsic::x86_avx2_psllv_d_256:
12423 case Intrinsic::x86_avx2_psllv_q_256:
12426 case Intrinsic::x86_avx2_psrlv_d:
12427 case Intrinsic::x86_avx2_psrlv_q:
12428 case Intrinsic::x86_avx2_psrlv_d_256:
12429 case Intrinsic::x86_avx2_psrlv_q_256:
12432 case Intrinsic::x86_avx2_psrav_d:
12433 case Intrinsic::x86_avx2_psrav_d_256:
12437 return DAG.getNode(Opcode, dl, Op.getValueType(),
12438 Op.getOperand(1), Op.getOperand(2));
12441 case Intrinsic::x86_ssse3_pshuf_b_128:
12442 case Intrinsic::x86_avx2_pshuf_b:
12443 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12444 Op.getOperand(1), Op.getOperand(2));
12446 case Intrinsic::x86_ssse3_psign_b_128:
12447 case Intrinsic::x86_ssse3_psign_w_128:
12448 case Intrinsic::x86_ssse3_psign_d_128:
12449 case Intrinsic::x86_avx2_psign_b:
12450 case Intrinsic::x86_avx2_psign_w:
12451 case Intrinsic::x86_avx2_psign_d:
12452 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12453 Op.getOperand(1), Op.getOperand(2));
12455 case Intrinsic::x86_sse41_insertps:
12456 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12457 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12459 case Intrinsic::x86_avx_vperm2f128_ps_256:
12460 case Intrinsic::x86_avx_vperm2f128_pd_256:
12461 case Intrinsic::x86_avx_vperm2f128_si_256:
12462 case Intrinsic::x86_avx2_vperm2i128:
12463 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12464 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12466 case Intrinsic::x86_avx2_permd:
12467 case Intrinsic::x86_avx2_permps:
12468 // Operands intentionally swapped. Mask is last operand to intrinsic,
12469 // but second operand for node/instruction.
12470 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12471 Op.getOperand(2), Op.getOperand(1));
12473 case Intrinsic::x86_sse_sqrt_ps:
12474 case Intrinsic::x86_sse2_sqrt_pd:
12475 case Intrinsic::x86_avx_sqrt_ps_256:
12476 case Intrinsic::x86_avx_sqrt_pd_256:
12477 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12479 // ptest and testp intrinsics. The intrinsic these come from are designed to
12480 // return an integer value, not just an instruction so lower it to the ptest
12481 // or testp pattern and a setcc for the result.
12482 case Intrinsic::x86_sse41_ptestz:
12483 case Intrinsic::x86_sse41_ptestc:
12484 case Intrinsic::x86_sse41_ptestnzc:
12485 case Intrinsic::x86_avx_ptestz_256:
12486 case Intrinsic::x86_avx_ptestc_256:
12487 case Intrinsic::x86_avx_ptestnzc_256:
12488 case Intrinsic::x86_avx_vtestz_ps:
12489 case Intrinsic::x86_avx_vtestc_ps:
12490 case Intrinsic::x86_avx_vtestnzc_ps:
12491 case Intrinsic::x86_avx_vtestz_pd:
12492 case Intrinsic::x86_avx_vtestc_pd:
12493 case Intrinsic::x86_avx_vtestnzc_pd:
12494 case Intrinsic::x86_avx_vtestz_ps_256:
12495 case Intrinsic::x86_avx_vtestc_ps_256:
12496 case Intrinsic::x86_avx_vtestnzc_ps_256:
12497 case Intrinsic::x86_avx_vtestz_pd_256:
12498 case Intrinsic::x86_avx_vtestc_pd_256:
12499 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12500 bool IsTestPacked = false;
12503 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12504 case Intrinsic::x86_avx_vtestz_ps:
12505 case Intrinsic::x86_avx_vtestz_pd:
12506 case Intrinsic::x86_avx_vtestz_ps_256:
12507 case Intrinsic::x86_avx_vtestz_pd_256:
12508 IsTestPacked = true; // Fallthrough
12509 case Intrinsic::x86_sse41_ptestz:
12510 case Intrinsic::x86_avx_ptestz_256:
12512 X86CC = X86::COND_E;
12514 case Intrinsic::x86_avx_vtestc_ps:
12515 case Intrinsic::x86_avx_vtestc_pd:
12516 case Intrinsic::x86_avx_vtestc_ps_256:
12517 case Intrinsic::x86_avx_vtestc_pd_256:
12518 IsTestPacked = true; // Fallthrough
12519 case Intrinsic::x86_sse41_ptestc:
12520 case Intrinsic::x86_avx_ptestc_256:
12522 X86CC = X86::COND_B;
12524 case Intrinsic::x86_avx_vtestnzc_ps:
12525 case Intrinsic::x86_avx_vtestnzc_pd:
12526 case Intrinsic::x86_avx_vtestnzc_ps_256:
12527 case Intrinsic::x86_avx_vtestnzc_pd_256:
12528 IsTestPacked = true; // Fallthrough
12529 case Intrinsic::x86_sse41_ptestnzc:
12530 case Intrinsic::x86_avx_ptestnzc_256:
12532 X86CC = X86::COND_A;
12536 SDValue LHS = Op.getOperand(1);
12537 SDValue RHS = Op.getOperand(2);
12538 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12539 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12540 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12541 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12542 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12544 case Intrinsic::x86_avx512_kortestz_w:
12545 case Intrinsic::x86_avx512_kortestc_w: {
12546 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12547 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12548 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12549 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12550 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12551 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12552 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12555 // SSE/AVX shift intrinsics
12556 case Intrinsic::x86_sse2_psll_w:
12557 case Intrinsic::x86_sse2_psll_d:
12558 case Intrinsic::x86_sse2_psll_q:
12559 case Intrinsic::x86_avx2_psll_w:
12560 case Intrinsic::x86_avx2_psll_d:
12561 case Intrinsic::x86_avx2_psll_q:
12562 case Intrinsic::x86_sse2_psrl_w:
12563 case Intrinsic::x86_sse2_psrl_d:
12564 case Intrinsic::x86_sse2_psrl_q:
12565 case Intrinsic::x86_avx2_psrl_w:
12566 case Intrinsic::x86_avx2_psrl_d:
12567 case Intrinsic::x86_avx2_psrl_q:
12568 case Intrinsic::x86_sse2_psra_w:
12569 case Intrinsic::x86_sse2_psra_d:
12570 case Intrinsic::x86_avx2_psra_w:
12571 case Intrinsic::x86_avx2_psra_d: {
12574 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12575 case Intrinsic::x86_sse2_psll_w:
12576 case Intrinsic::x86_sse2_psll_d:
12577 case Intrinsic::x86_sse2_psll_q:
12578 case Intrinsic::x86_avx2_psll_w:
12579 case Intrinsic::x86_avx2_psll_d:
12580 case Intrinsic::x86_avx2_psll_q:
12581 Opcode = X86ISD::VSHL;
12583 case Intrinsic::x86_sse2_psrl_w:
12584 case Intrinsic::x86_sse2_psrl_d:
12585 case Intrinsic::x86_sse2_psrl_q:
12586 case Intrinsic::x86_avx2_psrl_w:
12587 case Intrinsic::x86_avx2_psrl_d:
12588 case Intrinsic::x86_avx2_psrl_q:
12589 Opcode = X86ISD::VSRL;
12591 case Intrinsic::x86_sse2_psra_w:
12592 case Intrinsic::x86_sse2_psra_d:
12593 case Intrinsic::x86_avx2_psra_w:
12594 case Intrinsic::x86_avx2_psra_d:
12595 Opcode = X86ISD::VSRA;
12598 return DAG.getNode(Opcode, dl, Op.getValueType(),
12599 Op.getOperand(1), Op.getOperand(2));
12602 // SSE/AVX immediate shift intrinsics
12603 case Intrinsic::x86_sse2_pslli_w:
12604 case Intrinsic::x86_sse2_pslli_d:
12605 case Intrinsic::x86_sse2_pslli_q:
12606 case Intrinsic::x86_avx2_pslli_w:
12607 case Intrinsic::x86_avx2_pslli_d:
12608 case Intrinsic::x86_avx2_pslli_q:
12609 case Intrinsic::x86_sse2_psrli_w:
12610 case Intrinsic::x86_sse2_psrli_d:
12611 case Intrinsic::x86_sse2_psrli_q:
12612 case Intrinsic::x86_avx2_psrli_w:
12613 case Intrinsic::x86_avx2_psrli_d:
12614 case Intrinsic::x86_avx2_psrli_q:
12615 case Intrinsic::x86_sse2_psrai_w:
12616 case Intrinsic::x86_sse2_psrai_d:
12617 case Intrinsic::x86_avx2_psrai_w:
12618 case Intrinsic::x86_avx2_psrai_d: {
12621 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12622 case Intrinsic::x86_sse2_pslli_w:
12623 case Intrinsic::x86_sse2_pslli_d:
12624 case Intrinsic::x86_sse2_pslli_q:
12625 case Intrinsic::x86_avx2_pslli_w:
12626 case Intrinsic::x86_avx2_pslli_d:
12627 case Intrinsic::x86_avx2_pslli_q:
12628 Opcode = X86ISD::VSHLI;
12630 case Intrinsic::x86_sse2_psrli_w:
12631 case Intrinsic::x86_sse2_psrli_d:
12632 case Intrinsic::x86_sse2_psrli_q:
12633 case Intrinsic::x86_avx2_psrli_w:
12634 case Intrinsic::x86_avx2_psrli_d:
12635 case Intrinsic::x86_avx2_psrli_q:
12636 Opcode = X86ISD::VSRLI;
12638 case Intrinsic::x86_sse2_psrai_w:
12639 case Intrinsic::x86_sse2_psrai_d:
12640 case Intrinsic::x86_avx2_psrai_w:
12641 case Intrinsic::x86_avx2_psrai_d:
12642 Opcode = X86ISD::VSRAI;
12645 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12646 Op.getOperand(1), Op.getOperand(2), DAG);
12649 case Intrinsic::x86_sse42_pcmpistria128:
12650 case Intrinsic::x86_sse42_pcmpestria128:
12651 case Intrinsic::x86_sse42_pcmpistric128:
12652 case Intrinsic::x86_sse42_pcmpestric128:
12653 case Intrinsic::x86_sse42_pcmpistrio128:
12654 case Intrinsic::x86_sse42_pcmpestrio128:
12655 case Intrinsic::x86_sse42_pcmpistris128:
12656 case Intrinsic::x86_sse42_pcmpestris128:
12657 case Intrinsic::x86_sse42_pcmpistriz128:
12658 case Intrinsic::x86_sse42_pcmpestriz128: {
12662 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12663 case Intrinsic::x86_sse42_pcmpistria128:
12664 Opcode = X86ISD::PCMPISTRI;
12665 X86CC = X86::COND_A;
12667 case Intrinsic::x86_sse42_pcmpestria128:
12668 Opcode = X86ISD::PCMPESTRI;
12669 X86CC = X86::COND_A;
12671 case Intrinsic::x86_sse42_pcmpistric128:
12672 Opcode = X86ISD::PCMPISTRI;
12673 X86CC = X86::COND_B;
12675 case Intrinsic::x86_sse42_pcmpestric128:
12676 Opcode = X86ISD::PCMPESTRI;
12677 X86CC = X86::COND_B;
12679 case Intrinsic::x86_sse42_pcmpistrio128:
12680 Opcode = X86ISD::PCMPISTRI;
12681 X86CC = X86::COND_O;
12683 case Intrinsic::x86_sse42_pcmpestrio128:
12684 Opcode = X86ISD::PCMPESTRI;
12685 X86CC = X86::COND_O;
12687 case Intrinsic::x86_sse42_pcmpistris128:
12688 Opcode = X86ISD::PCMPISTRI;
12689 X86CC = X86::COND_S;
12691 case Intrinsic::x86_sse42_pcmpestris128:
12692 Opcode = X86ISD::PCMPESTRI;
12693 X86CC = X86::COND_S;
12695 case Intrinsic::x86_sse42_pcmpistriz128:
12696 Opcode = X86ISD::PCMPISTRI;
12697 X86CC = X86::COND_E;
12699 case Intrinsic::x86_sse42_pcmpestriz128:
12700 Opcode = X86ISD::PCMPESTRI;
12701 X86CC = X86::COND_E;
12704 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12705 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12706 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12707 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12708 DAG.getConstant(X86CC, MVT::i8),
12709 SDValue(PCMP.getNode(), 1));
12710 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12713 case Intrinsic::x86_sse42_pcmpistri128:
12714 case Intrinsic::x86_sse42_pcmpestri128: {
12716 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12717 Opcode = X86ISD::PCMPISTRI;
12719 Opcode = X86ISD::PCMPESTRI;
12721 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12722 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12723 return DAG.getNode(Opcode, dl, VTs, NewOps);
12725 case Intrinsic::x86_fma_vfmadd_ps:
12726 case Intrinsic::x86_fma_vfmadd_pd:
12727 case Intrinsic::x86_fma_vfmsub_ps:
12728 case Intrinsic::x86_fma_vfmsub_pd:
12729 case Intrinsic::x86_fma_vfnmadd_ps:
12730 case Intrinsic::x86_fma_vfnmadd_pd:
12731 case Intrinsic::x86_fma_vfnmsub_ps:
12732 case Intrinsic::x86_fma_vfnmsub_pd:
12733 case Intrinsic::x86_fma_vfmaddsub_ps:
12734 case Intrinsic::x86_fma_vfmaddsub_pd:
12735 case Intrinsic::x86_fma_vfmsubadd_ps:
12736 case Intrinsic::x86_fma_vfmsubadd_pd:
12737 case Intrinsic::x86_fma_vfmadd_ps_256:
12738 case Intrinsic::x86_fma_vfmadd_pd_256:
12739 case Intrinsic::x86_fma_vfmsub_ps_256:
12740 case Intrinsic::x86_fma_vfmsub_pd_256:
12741 case Intrinsic::x86_fma_vfnmadd_ps_256:
12742 case Intrinsic::x86_fma_vfnmadd_pd_256:
12743 case Intrinsic::x86_fma_vfnmsub_ps_256:
12744 case Intrinsic::x86_fma_vfnmsub_pd_256:
12745 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12746 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12747 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12748 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12749 case Intrinsic::x86_fma_vfmadd_ps_512:
12750 case Intrinsic::x86_fma_vfmadd_pd_512:
12751 case Intrinsic::x86_fma_vfmsub_ps_512:
12752 case Intrinsic::x86_fma_vfmsub_pd_512:
12753 case Intrinsic::x86_fma_vfnmadd_ps_512:
12754 case Intrinsic::x86_fma_vfnmadd_pd_512:
12755 case Intrinsic::x86_fma_vfnmsub_ps_512:
12756 case Intrinsic::x86_fma_vfnmsub_pd_512:
12757 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12758 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12759 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12760 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12763 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12764 case Intrinsic::x86_fma_vfmadd_ps:
12765 case Intrinsic::x86_fma_vfmadd_pd:
12766 case Intrinsic::x86_fma_vfmadd_ps_256:
12767 case Intrinsic::x86_fma_vfmadd_pd_256:
12768 case Intrinsic::x86_fma_vfmadd_ps_512:
12769 case Intrinsic::x86_fma_vfmadd_pd_512:
12770 Opc = X86ISD::FMADD;
12772 case Intrinsic::x86_fma_vfmsub_ps:
12773 case Intrinsic::x86_fma_vfmsub_pd:
12774 case Intrinsic::x86_fma_vfmsub_ps_256:
12775 case Intrinsic::x86_fma_vfmsub_pd_256:
12776 case Intrinsic::x86_fma_vfmsub_ps_512:
12777 case Intrinsic::x86_fma_vfmsub_pd_512:
12778 Opc = X86ISD::FMSUB;
12780 case Intrinsic::x86_fma_vfnmadd_ps:
12781 case Intrinsic::x86_fma_vfnmadd_pd:
12782 case Intrinsic::x86_fma_vfnmadd_ps_256:
12783 case Intrinsic::x86_fma_vfnmadd_pd_256:
12784 case Intrinsic::x86_fma_vfnmadd_ps_512:
12785 case Intrinsic::x86_fma_vfnmadd_pd_512:
12786 Opc = X86ISD::FNMADD;
12788 case Intrinsic::x86_fma_vfnmsub_ps:
12789 case Intrinsic::x86_fma_vfnmsub_pd:
12790 case Intrinsic::x86_fma_vfnmsub_ps_256:
12791 case Intrinsic::x86_fma_vfnmsub_pd_256:
12792 case Intrinsic::x86_fma_vfnmsub_ps_512:
12793 case Intrinsic::x86_fma_vfnmsub_pd_512:
12794 Opc = X86ISD::FNMSUB;
12796 case Intrinsic::x86_fma_vfmaddsub_ps:
12797 case Intrinsic::x86_fma_vfmaddsub_pd:
12798 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12799 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12800 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12801 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12802 Opc = X86ISD::FMADDSUB;
12804 case Intrinsic::x86_fma_vfmsubadd_ps:
12805 case Intrinsic::x86_fma_vfmsubadd_pd:
12806 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12807 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12808 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12809 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12810 Opc = X86ISD::FMSUBADD;
12814 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12815 Op.getOperand(2), Op.getOperand(3));
12820 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12821 SDValue Src, SDValue Mask, SDValue Base,
12822 SDValue Index, SDValue ScaleOp, SDValue Chain,
12823 const X86Subtarget * Subtarget) {
12825 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12826 assert(C && "Invalid scale type");
12827 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12828 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12829 Index.getSimpleValueType().getVectorNumElements());
12831 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12833 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12835 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12836 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12837 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12838 SDValue Segment = DAG.getRegister(0, MVT::i32);
12839 if (Src.getOpcode() == ISD::UNDEF)
12840 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12841 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12842 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12843 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12844 return DAG.getMergeValues(RetOps, dl);
12847 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12848 SDValue Src, SDValue Mask, SDValue Base,
12849 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12851 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12852 assert(C && "Invalid scale type");
12853 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12854 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12855 SDValue Segment = DAG.getRegister(0, MVT::i32);
12856 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12857 Index.getSimpleValueType().getVectorNumElements());
12859 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12861 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12863 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12864 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12865 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12866 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12867 return SDValue(Res, 1);
12870 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12871 SDValue Mask, SDValue Base, SDValue Index,
12872 SDValue ScaleOp, SDValue Chain) {
12874 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12875 assert(C && "Invalid scale type");
12876 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12877 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12878 SDValue Segment = DAG.getRegister(0, MVT::i32);
12880 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12882 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12884 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12886 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12887 //SDVTList VTs = DAG.getVTList(MVT::Other);
12888 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12889 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12890 return SDValue(Res, 0);
12893 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12894 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12895 // also used to custom lower READCYCLECOUNTER nodes.
12896 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12897 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12898 SmallVectorImpl<SDValue> &Results) {
12899 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12900 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12903 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12904 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12905 // and the EAX register is loaded with the low-order 32 bits.
12906 if (Subtarget->is64Bit()) {
12907 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12908 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12911 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12912 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12915 SDValue Chain = HI.getValue(1);
12917 if (Opcode == X86ISD::RDTSCP_DAG) {
12918 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12920 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12921 // the ECX register. Add 'ecx' explicitly to the chain.
12922 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12924 // Explicitly store the content of ECX at the location passed in input
12925 // to the 'rdtscp' intrinsic.
12926 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12927 MachinePointerInfo(), false, false, 0);
12930 if (Subtarget->is64Bit()) {
12931 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12932 // the EAX register is loaded with the low-order 32 bits.
12933 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12934 DAG.getConstant(32, MVT::i8));
12935 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12936 Results.push_back(Chain);
12940 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12941 SDValue Ops[] = { LO, HI };
12942 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12943 Results.push_back(Pair);
12944 Results.push_back(Chain);
12947 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12948 SelectionDAG &DAG) {
12949 SmallVector<SDValue, 2> Results;
12951 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12953 return DAG.getMergeValues(Results, DL);
12956 enum IntrinsicType {
12957 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12960 struct IntrinsicData {
12961 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12962 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12963 IntrinsicType Type;
12968 std::map < unsigned, IntrinsicData> IntrMap;
12969 static void InitIntinsicsMap() {
12970 static bool Initialized = false;
12973 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12974 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12975 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12976 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12977 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12978 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12979 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12980 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12981 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12982 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12983 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12984 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12985 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12986 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12987 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12988 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12989 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12990 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12992 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12993 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12994 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12995 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12996 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12997 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12998 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12999 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
13000 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
13001 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
13002 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
13003 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
13004 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
13005 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13006 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
13007 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13009 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
13010 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13011 X86::VGATHERPF1QPSm)));
13012 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
13013 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13014 X86::VGATHERPF1QPDm)));
13015 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
13016 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13017 X86::VGATHERPF1DPDm)));
13018 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
13019 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13020 X86::VGATHERPF1DPSm)));
13021 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
13022 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13023 X86::VSCATTERPF1QPSm)));
13024 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
13025 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13026 X86::VSCATTERPF1QPDm)));
13027 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
13028 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13029 X86::VSCATTERPF1DPDm)));
13030 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
13031 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13032 X86::VSCATTERPF1DPSm)));
13033 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13034 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13035 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13036 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13037 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13038 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13039 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13040 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13041 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13042 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13043 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13044 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13045 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13046 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
13047 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13048 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
13049 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13050 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
13051 Initialized = true;
13054 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13055 SelectionDAG &DAG) {
13056 InitIntinsicsMap();
13057 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13058 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13059 if (itr == IntrMap.end())
13063 IntrinsicData Intr = itr->second;
13064 switch(Intr.Type) {
13067 // Emit the node with the right value type.
13068 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13069 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13071 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13072 // Otherwise return the value from Rand, which is always 0, casted to i32.
13073 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13074 DAG.getConstant(1, Op->getValueType(1)),
13075 DAG.getConstant(X86::COND_B, MVT::i32),
13076 SDValue(Result.getNode(), 1) };
13077 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13078 DAG.getVTList(Op->getValueType(1), MVT::Glue),
13081 // Return { result, isValid, chain }.
13082 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13083 SDValue(Result.getNode(), 2));
13086 //gather(v1, mask, index, base, scale);
13087 SDValue Chain = Op.getOperand(0);
13088 SDValue Src = Op.getOperand(2);
13089 SDValue Base = Op.getOperand(3);
13090 SDValue Index = Op.getOperand(4);
13091 SDValue Mask = Op.getOperand(5);
13092 SDValue Scale = Op.getOperand(6);
13093 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13097 //scatter(base, mask, index, v1, scale);
13098 SDValue Chain = Op.getOperand(0);
13099 SDValue Base = Op.getOperand(2);
13100 SDValue Mask = Op.getOperand(3);
13101 SDValue Index = Op.getOperand(4);
13102 SDValue Src = Op.getOperand(5);
13103 SDValue Scale = Op.getOperand(6);
13104 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13107 SDValue Hint = Op.getOperand(6);
13109 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13110 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13111 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13112 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13113 SDValue Chain = Op.getOperand(0);
13114 SDValue Mask = Op.getOperand(2);
13115 SDValue Index = Op.getOperand(3);
13116 SDValue Base = Op.getOperand(4);
13117 SDValue Scale = Op.getOperand(5);
13118 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13120 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13122 SmallVector<SDValue, 2> Results;
13123 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13124 return DAG.getMergeValues(Results, dl);
13126 // XTEST intrinsics.
13128 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13129 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13130 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13131 DAG.getConstant(X86::COND_NE, MVT::i8),
13133 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13134 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13135 Ret, SDValue(InTrans.getNode(), 1));
13138 llvm_unreachable("Unknown Intrinsic Type");
13141 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13142 SelectionDAG &DAG) const {
13143 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13144 MFI->setReturnAddressIsTaken(true);
13146 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13149 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13151 EVT PtrVT = getPointerTy();
13154 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13155 const X86RegisterInfo *RegInfo =
13156 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13157 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13158 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13159 DAG.getNode(ISD::ADD, dl, PtrVT,
13160 FrameAddr, Offset),
13161 MachinePointerInfo(), false, false, false, 0);
13164 // Just load the return address.
13165 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13166 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13167 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13170 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13171 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13172 MFI->setFrameAddressIsTaken(true);
13174 EVT VT = Op.getValueType();
13175 SDLoc dl(Op); // FIXME probably not meaningful
13176 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13177 const X86RegisterInfo *RegInfo =
13178 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13179 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13180 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13181 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13182 "Invalid Frame Register!");
13183 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13185 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13186 MachinePointerInfo(),
13187 false, false, false, 0);
13191 // FIXME? Maybe this could be a TableGen attribute on some registers and
13192 // this table could be generated automatically from RegInfo.
13193 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13195 unsigned Reg = StringSwitch<unsigned>(RegName)
13196 .Case("esp", X86::ESP)
13197 .Case("rsp", X86::RSP)
13201 report_fatal_error("Invalid register name global variable");
13204 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13205 SelectionDAG &DAG) const {
13206 const X86RegisterInfo *RegInfo =
13207 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13208 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13211 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13212 SDValue Chain = Op.getOperand(0);
13213 SDValue Offset = Op.getOperand(1);
13214 SDValue Handler = Op.getOperand(2);
13217 EVT PtrVT = getPointerTy();
13218 const X86RegisterInfo *RegInfo =
13219 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13220 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13221 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13222 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13223 "Invalid Frame Register!");
13224 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13225 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13227 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13228 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13229 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13230 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13232 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13234 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13235 DAG.getRegister(StoreAddrReg, PtrVT));
13238 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13239 SelectionDAG &DAG) const {
13241 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13242 DAG.getVTList(MVT::i32, MVT::Other),
13243 Op.getOperand(0), Op.getOperand(1));
13246 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13247 SelectionDAG &DAG) const {
13249 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13250 Op.getOperand(0), Op.getOperand(1));
13253 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13254 return Op.getOperand(0);
13257 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13258 SelectionDAG &DAG) const {
13259 SDValue Root = Op.getOperand(0);
13260 SDValue Trmp = Op.getOperand(1); // trampoline
13261 SDValue FPtr = Op.getOperand(2); // nested function
13262 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13265 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13266 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13268 if (Subtarget->is64Bit()) {
13269 SDValue OutChains[6];
13271 // Large code-model.
13272 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13273 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13275 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13276 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13278 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13280 // Load the pointer to the nested function into R11.
13281 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13282 SDValue Addr = Trmp;
13283 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13284 Addr, MachinePointerInfo(TrmpAddr),
13287 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13288 DAG.getConstant(2, MVT::i64));
13289 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13290 MachinePointerInfo(TrmpAddr, 2),
13293 // Load the 'nest' parameter value into R10.
13294 // R10 is specified in X86CallingConv.td
13295 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13296 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13297 DAG.getConstant(10, MVT::i64));
13298 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13299 Addr, MachinePointerInfo(TrmpAddr, 10),
13302 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13303 DAG.getConstant(12, MVT::i64));
13304 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13305 MachinePointerInfo(TrmpAddr, 12),
13308 // Jump to the nested function.
13309 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13310 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13311 DAG.getConstant(20, MVT::i64));
13312 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13313 Addr, MachinePointerInfo(TrmpAddr, 20),
13316 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13317 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13318 DAG.getConstant(22, MVT::i64));
13319 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13320 MachinePointerInfo(TrmpAddr, 22),
13323 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13325 const Function *Func =
13326 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13327 CallingConv::ID CC = Func->getCallingConv();
13332 llvm_unreachable("Unsupported calling convention");
13333 case CallingConv::C:
13334 case CallingConv::X86_StdCall: {
13335 // Pass 'nest' parameter in ECX.
13336 // Must be kept in sync with X86CallingConv.td
13337 NestReg = X86::ECX;
13339 // Check that ECX wasn't needed by an 'inreg' parameter.
13340 FunctionType *FTy = Func->getFunctionType();
13341 const AttributeSet &Attrs = Func->getAttributes();
13343 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13344 unsigned InRegCount = 0;
13347 for (FunctionType::param_iterator I = FTy->param_begin(),
13348 E = FTy->param_end(); I != E; ++I, ++Idx)
13349 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13350 // FIXME: should only count parameters that are lowered to integers.
13351 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13353 if (InRegCount > 2) {
13354 report_fatal_error("Nest register in use - reduce number of inreg"
13360 case CallingConv::X86_FastCall:
13361 case CallingConv::X86_ThisCall:
13362 case CallingConv::Fast:
13363 // Pass 'nest' parameter in EAX.
13364 // Must be kept in sync with X86CallingConv.td
13365 NestReg = X86::EAX;
13369 SDValue OutChains[4];
13370 SDValue Addr, Disp;
13372 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13373 DAG.getConstant(10, MVT::i32));
13374 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13376 // This is storing the opcode for MOV32ri.
13377 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13378 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13379 OutChains[0] = DAG.getStore(Root, dl,
13380 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13381 Trmp, MachinePointerInfo(TrmpAddr),
13384 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13385 DAG.getConstant(1, MVT::i32));
13386 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13387 MachinePointerInfo(TrmpAddr, 1),
13390 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13391 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13392 DAG.getConstant(5, MVT::i32));
13393 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13394 MachinePointerInfo(TrmpAddr, 5),
13397 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13398 DAG.getConstant(6, MVT::i32));
13399 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13400 MachinePointerInfo(TrmpAddr, 6),
13403 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13407 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13408 SelectionDAG &DAG) const {
13410 The rounding mode is in bits 11:10 of FPSR, and has the following
13412 00 Round to nearest
13417 FLT_ROUNDS, on the other hand, expects the following:
13424 To perform the conversion, we do:
13425 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13428 MachineFunction &MF = DAG.getMachineFunction();
13429 const TargetMachine &TM = MF.getTarget();
13430 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13431 unsigned StackAlignment = TFI.getStackAlignment();
13432 MVT VT = Op.getSimpleValueType();
13435 // Save FP Control Word to stack slot
13436 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13437 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13439 MachineMemOperand *MMO =
13440 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13441 MachineMemOperand::MOStore, 2, 2);
13443 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13444 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13445 DAG.getVTList(MVT::Other),
13446 Ops, MVT::i16, MMO);
13448 // Load FP Control Word from stack slot
13449 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13450 MachinePointerInfo(), false, false, false, 0);
13452 // Transform as necessary
13454 DAG.getNode(ISD::SRL, DL, MVT::i16,
13455 DAG.getNode(ISD::AND, DL, MVT::i16,
13456 CWD, DAG.getConstant(0x800, MVT::i16)),
13457 DAG.getConstant(11, MVT::i8));
13459 DAG.getNode(ISD::SRL, DL, MVT::i16,
13460 DAG.getNode(ISD::AND, DL, MVT::i16,
13461 CWD, DAG.getConstant(0x400, MVT::i16)),
13462 DAG.getConstant(9, MVT::i8));
13465 DAG.getNode(ISD::AND, DL, MVT::i16,
13466 DAG.getNode(ISD::ADD, DL, MVT::i16,
13467 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13468 DAG.getConstant(1, MVT::i16)),
13469 DAG.getConstant(3, MVT::i16));
13471 return DAG.getNode((VT.getSizeInBits() < 16 ?
13472 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13475 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13476 MVT VT = Op.getSimpleValueType();
13478 unsigned NumBits = VT.getSizeInBits();
13481 Op = Op.getOperand(0);
13482 if (VT == MVT::i8) {
13483 // Zero extend to i32 since there is not an i8 bsr.
13485 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13488 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13489 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13490 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13492 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13495 DAG.getConstant(NumBits+NumBits-1, OpVT),
13496 DAG.getConstant(X86::COND_E, MVT::i8),
13499 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13501 // Finally xor with NumBits-1.
13502 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13505 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13509 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13510 MVT VT = Op.getSimpleValueType();
13512 unsigned NumBits = VT.getSizeInBits();
13515 Op = Op.getOperand(0);
13516 if (VT == MVT::i8) {
13517 // Zero extend to i32 since there is not an i8 bsr.
13519 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13522 // Issue a bsr (scan bits in reverse).
13523 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13524 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13526 // And xor with NumBits-1.
13527 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13530 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13534 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13535 MVT VT = Op.getSimpleValueType();
13536 unsigned NumBits = VT.getSizeInBits();
13538 Op = Op.getOperand(0);
13540 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13541 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13542 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13544 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13547 DAG.getConstant(NumBits, VT),
13548 DAG.getConstant(X86::COND_E, MVT::i8),
13551 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13554 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13555 // ones, and then concatenate the result back.
13556 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13557 MVT VT = Op.getSimpleValueType();
13559 assert(VT.is256BitVector() && VT.isInteger() &&
13560 "Unsupported value type for operation");
13562 unsigned NumElems = VT.getVectorNumElements();
13565 // Extract the LHS vectors
13566 SDValue LHS = Op.getOperand(0);
13567 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13568 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13570 // Extract the RHS vectors
13571 SDValue RHS = Op.getOperand(1);
13572 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13573 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13575 MVT EltVT = VT.getVectorElementType();
13576 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13578 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13579 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13580 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13583 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13584 assert(Op.getSimpleValueType().is256BitVector() &&
13585 Op.getSimpleValueType().isInteger() &&
13586 "Only handle AVX 256-bit vector integer operation");
13587 return Lower256IntArith(Op, DAG);
13590 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13591 assert(Op.getSimpleValueType().is256BitVector() &&
13592 Op.getSimpleValueType().isInteger() &&
13593 "Only handle AVX 256-bit vector integer operation");
13594 return Lower256IntArith(Op, DAG);
13597 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13598 SelectionDAG &DAG) {
13600 MVT VT = Op.getSimpleValueType();
13602 // Decompose 256-bit ops into smaller 128-bit ops.
13603 if (VT.is256BitVector() && !Subtarget->hasInt256())
13604 return Lower256IntArith(Op, DAG);
13606 SDValue A = Op.getOperand(0);
13607 SDValue B = Op.getOperand(1);
13609 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13610 if (VT == MVT::v4i32) {
13611 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13612 "Should not custom lower when pmuldq is available!");
13614 // Extract the odd parts.
13615 static const int UnpackMask[] = { 1, -1, 3, -1 };
13616 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13617 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13619 // Multiply the even parts.
13620 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13621 // Now multiply odd parts.
13622 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13624 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13625 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13627 // Merge the two vectors back together with a shuffle. This expands into 2
13629 static const int ShufMask[] = { 0, 4, 2, 6 };
13630 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13633 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13634 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13636 // Ahi = psrlqi(a, 32);
13637 // Bhi = psrlqi(b, 32);
13639 // AloBlo = pmuludq(a, b);
13640 // AloBhi = pmuludq(a, Bhi);
13641 // AhiBlo = pmuludq(Ahi, b);
13643 // AloBhi = psllqi(AloBhi, 32);
13644 // AhiBlo = psllqi(AhiBlo, 32);
13645 // return AloBlo + AloBhi + AhiBlo;
13647 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13648 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13650 // Bit cast to 32-bit vectors for MULUDQ
13651 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13652 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13653 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13654 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13655 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13656 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13658 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13659 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13660 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13662 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13663 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13665 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13666 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13669 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13670 assert(Subtarget->isTargetWin64() && "Unexpected target");
13671 EVT VT = Op.getValueType();
13672 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13673 "Unexpected return type for lowering");
13677 switch (Op->getOpcode()) {
13678 default: llvm_unreachable("Unexpected request for libcall!");
13679 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13680 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13681 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13682 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13683 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13684 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13688 SDValue InChain = DAG.getEntryNode();
13690 TargetLowering::ArgListTy Args;
13691 TargetLowering::ArgListEntry Entry;
13692 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13693 EVT ArgVT = Op->getOperand(i).getValueType();
13694 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13695 "Unexpected argument type for lowering");
13696 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13697 Entry.Node = StackPtr;
13698 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13700 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13701 Entry.Ty = PointerType::get(ArgTy,0);
13702 Entry.isSExt = false;
13703 Entry.isZExt = false;
13704 Args.push_back(Entry);
13707 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13710 TargetLowering::CallLoweringInfo CLI(DAG);
13711 CLI.setDebugLoc(dl).setChain(InChain)
13712 .setCallee(getLibcallCallingConv(LC),
13713 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13715 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13717 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13718 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13721 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13722 SelectionDAG &DAG) {
13723 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13724 EVT VT = Op0.getValueType();
13727 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13728 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13730 // Get the high parts.
13731 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13732 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13733 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13735 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13737 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13738 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13740 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13741 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13742 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13743 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13744 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13746 // Shuffle it back into the right order.
13747 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13748 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13749 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13750 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13752 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13753 // unsigned multiply.
13754 if (IsSigned && !Subtarget->hasSSE41()) {
13756 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13757 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13758 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13759 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13760 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13762 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13763 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13766 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13769 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13770 const X86Subtarget *Subtarget) {
13771 MVT VT = Op.getSimpleValueType();
13773 SDValue R = Op.getOperand(0);
13774 SDValue Amt = Op.getOperand(1);
13776 // Optimize shl/srl/sra with constant shift amount.
13777 if (isSplatVector(Amt.getNode())) {
13778 SDValue SclrAmt = Amt->getOperand(0);
13779 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13780 uint64_t ShiftAmt = C->getZExtValue();
13782 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13783 (Subtarget->hasInt256() &&
13784 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13785 (Subtarget->hasAVX512() &&
13786 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13787 if (Op.getOpcode() == ISD::SHL)
13788 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13790 if (Op.getOpcode() == ISD::SRL)
13791 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13793 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13794 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13798 if (VT == MVT::v16i8) {
13799 if (Op.getOpcode() == ISD::SHL) {
13800 // Make a large shift.
13801 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13802 MVT::v8i16, R, ShiftAmt,
13804 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13805 // Zero out the rightmost bits.
13806 SmallVector<SDValue, 16> V(16,
13807 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13809 return DAG.getNode(ISD::AND, dl, VT, SHL,
13810 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13812 if (Op.getOpcode() == ISD::SRL) {
13813 // Make a large shift.
13814 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13815 MVT::v8i16, R, ShiftAmt,
13817 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13818 // Zero out the leftmost bits.
13819 SmallVector<SDValue, 16> V(16,
13820 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13822 return DAG.getNode(ISD::AND, dl, VT, SRL,
13823 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13825 if (Op.getOpcode() == ISD::SRA) {
13826 if (ShiftAmt == 7) {
13827 // R s>> 7 === R s< 0
13828 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13829 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13832 // R s>> a === ((R u>> a) ^ m) - m
13833 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13834 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13836 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13837 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13838 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13841 llvm_unreachable("Unknown shift opcode.");
13844 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13845 if (Op.getOpcode() == ISD::SHL) {
13846 // Make a large shift.
13847 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13848 MVT::v16i16, R, ShiftAmt,
13850 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13851 // Zero out the rightmost bits.
13852 SmallVector<SDValue, 32> V(32,
13853 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13855 return DAG.getNode(ISD::AND, dl, VT, SHL,
13856 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13858 if (Op.getOpcode() == ISD::SRL) {
13859 // Make a large shift.
13860 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13861 MVT::v16i16, R, ShiftAmt,
13863 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13864 // Zero out the leftmost bits.
13865 SmallVector<SDValue, 32> V(32,
13866 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13868 return DAG.getNode(ISD::AND, dl, VT, SRL,
13869 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13871 if (Op.getOpcode() == ISD::SRA) {
13872 if (ShiftAmt == 7) {
13873 // R s>> 7 === R s< 0
13874 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13875 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13878 // R s>> a === ((R u>> a) ^ m) - m
13879 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13880 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13882 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13883 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13884 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13887 llvm_unreachable("Unknown shift opcode.");
13892 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13893 if (!Subtarget->is64Bit() &&
13894 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13895 Amt.getOpcode() == ISD::BITCAST &&
13896 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13897 Amt = Amt.getOperand(0);
13898 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13899 VT.getVectorNumElements();
13900 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13901 uint64_t ShiftAmt = 0;
13902 for (unsigned i = 0; i != Ratio; ++i) {
13903 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13907 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13909 // Check remaining shift amounts.
13910 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13911 uint64_t ShAmt = 0;
13912 for (unsigned j = 0; j != Ratio; ++j) {
13913 ConstantSDNode *C =
13914 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13918 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13920 if (ShAmt != ShiftAmt)
13923 switch (Op.getOpcode()) {
13925 llvm_unreachable("Unknown shift opcode!");
13927 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13930 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13933 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13941 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13942 const X86Subtarget* Subtarget) {
13943 MVT VT = Op.getSimpleValueType();
13945 SDValue R = Op.getOperand(0);
13946 SDValue Amt = Op.getOperand(1);
13948 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13949 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13950 (Subtarget->hasInt256() &&
13951 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13952 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13953 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13955 EVT EltVT = VT.getVectorElementType();
13957 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13958 unsigned NumElts = VT.getVectorNumElements();
13960 for (i = 0; i != NumElts; ++i) {
13961 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13965 for (j = i; j != NumElts; ++j) {
13966 SDValue Arg = Amt.getOperand(j);
13967 if (Arg.getOpcode() == ISD::UNDEF) continue;
13968 if (Arg != Amt.getOperand(i))
13971 if (i != NumElts && j == NumElts)
13972 BaseShAmt = Amt.getOperand(i);
13974 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13975 Amt = Amt.getOperand(0);
13976 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13977 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13978 SDValue InVec = Amt.getOperand(0);
13979 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13980 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13982 for (; i != NumElts; ++i) {
13983 SDValue Arg = InVec.getOperand(i);
13984 if (Arg.getOpcode() == ISD::UNDEF) continue;
13988 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13989 if (ConstantSDNode *C =
13990 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13991 unsigned SplatIdx =
13992 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13993 if (C->getZExtValue() == SplatIdx)
13994 BaseShAmt = InVec.getOperand(1);
13997 if (!BaseShAmt.getNode())
13998 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13999 DAG.getIntPtrConstant(0));
14003 if (BaseShAmt.getNode()) {
14004 if (EltVT.bitsGT(MVT::i32))
14005 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14006 else if (EltVT.bitsLT(MVT::i32))
14007 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14009 switch (Op.getOpcode()) {
14011 llvm_unreachable("Unknown shift opcode!");
14013 switch (VT.SimpleTy) {
14014 default: return SDValue();
14023 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14026 switch (VT.SimpleTy) {
14027 default: return SDValue();
14034 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14037 switch (VT.SimpleTy) {
14038 default: return SDValue();
14047 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14053 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14054 if (!Subtarget->is64Bit() &&
14055 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14056 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14057 Amt.getOpcode() == ISD::BITCAST &&
14058 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14059 Amt = Amt.getOperand(0);
14060 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14061 VT.getVectorNumElements();
14062 std::vector<SDValue> Vals(Ratio);
14063 for (unsigned i = 0; i != Ratio; ++i)
14064 Vals[i] = Amt.getOperand(i);
14065 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14066 for (unsigned j = 0; j != Ratio; ++j)
14067 if (Vals[j] != Amt.getOperand(i + j))
14070 switch (Op.getOpcode()) {
14072 llvm_unreachable("Unknown shift opcode!");
14074 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14076 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14078 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14085 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14086 SelectionDAG &DAG) {
14088 MVT VT = Op.getSimpleValueType();
14090 SDValue R = Op.getOperand(0);
14091 SDValue Amt = Op.getOperand(1);
14094 if (!Subtarget->hasSSE2())
14097 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14101 V = LowerScalarVariableShift(Op, DAG, Subtarget);
14105 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14107 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14108 if (Subtarget->hasInt256()) {
14109 if (Op.getOpcode() == ISD::SRL &&
14110 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14111 VT == MVT::v4i64 || VT == MVT::v8i32))
14113 if (Op.getOpcode() == ISD::SHL &&
14114 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14115 VT == MVT::v4i64 || VT == MVT::v8i32))
14117 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14121 // If possible, lower this packed shift into a vector multiply instead of
14122 // expanding it into a sequence of scalar shifts.
14123 // Do this only if the vector shift count is a constant build_vector.
14124 if (Op.getOpcode() == ISD::SHL &&
14125 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14126 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14127 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14128 SmallVector<SDValue, 8> Elts;
14129 EVT SVT = VT.getScalarType();
14130 unsigned SVTBits = SVT.getSizeInBits();
14131 const APInt &One = APInt(SVTBits, 1);
14132 unsigned NumElems = VT.getVectorNumElements();
14134 for (unsigned i=0; i !=NumElems; ++i) {
14135 SDValue Op = Amt->getOperand(i);
14136 if (Op->getOpcode() == ISD::UNDEF) {
14137 Elts.push_back(Op);
14141 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14142 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14143 uint64_t ShAmt = C.getZExtValue();
14144 if (ShAmt >= SVTBits) {
14145 Elts.push_back(DAG.getUNDEF(SVT));
14148 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14150 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14151 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14154 // Lower SHL with variable shift amount.
14155 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14156 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14158 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14159 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14160 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14161 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14164 // If possible, lower this shift as a sequence of two shifts by
14165 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14167 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14169 // Could be rewritten as:
14170 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14172 // The advantage is that the two shifts from the example would be
14173 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14174 // the vector shift into four scalar shifts plus four pairs of vector
14176 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14177 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14178 unsigned TargetOpcode = X86ISD::MOVSS;
14179 bool CanBeSimplified;
14180 // The splat value for the first packed shift (the 'X' from the example).
14181 SDValue Amt1 = Amt->getOperand(0);
14182 // The splat value for the second packed shift (the 'Y' from the example).
14183 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14184 Amt->getOperand(2);
14186 // See if it is possible to replace this node with a sequence of
14187 // two shifts followed by a MOVSS/MOVSD
14188 if (VT == MVT::v4i32) {
14189 // Check if it is legal to use a MOVSS.
14190 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14191 Amt2 == Amt->getOperand(3);
14192 if (!CanBeSimplified) {
14193 // Otherwise, check if we can still simplify this node using a MOVSD.
14194 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14195 Amt->getOperand(2) == Amt->getOperand(3);
14196 TargetOpcode = X86ISD::MOVSD;
14197 Amt2 = Amt->getOperand(2);
14200 // Do similar checks for the case where the machine value type
14202 CanBeSimplified = Amt1 == Amt->getOperand(1);
14203 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14204 CanBeSimplified = Amt2 == Amt->getOperand(i);
14206 if (!CanBeSimplified) {
14207 TargetOpcode = X86ISD::MOVSD;
14208 CanBeSimplified = true;
14209 Amt2 = Amt->getOperand(4);
14210 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14211 CanBeSimplified = Amt1 == Amt->getOperand(i);
14212 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14213 CanBeSimplified = Amt2 == Amt->getOperand(j);
14217 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14218 isa<ConstantSDNode>(Amt2)) {
14219 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14220 EVT CastVT = MVT::v4i32;
14222 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14223 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14225 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14226 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14227 if (TargetOpcode == X86ISD::MOVSD)
14228 CastVT = MVT::v2i64;
14229 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14230 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14231 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14233 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14237 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14238 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14241 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14242 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14244 // Turn 'a' into a mask suitable for VSELECT
14245 SDValue VSelM = DAG.getConstant(0x80, VT);
14246 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14247 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14249 SDValue CM1 = DAG.getConstant(0x0f, VT);
14250 SDValue CM2 = DAG.getConstant(0x3f, VT);
14252 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14253 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14254 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14255 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14256 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14259 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14260 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14261 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14263 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14264 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14265 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14266 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14267 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14270 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14271 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14272 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14274 // return VSELECT(r, r+r, a);
14275 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14276 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14280 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14281 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14282 // solution better.
14283 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14284 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14286 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14287 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14288 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14289 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14290 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14293 // Decompose 256-bit shifts into smaller 128-bit shifts.
14294 if (VT.is256BitVector()) {
14295 unsigned NumElems = VT.getVectorNumElements();
14296 MVT EltVT = VT.getVectorElementType();
14297 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14299 // Extract the two vectors
14300 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14301 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14303 // Recreate the shift amount vectors
14304 SDValue Amt1, Amt2;
14305 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14306 // Constant shift amount
14307 SmallVector<SDValue, 4> Amt1Csts;
14308 SmallVector<SDValue, 4> Amt2Csts;
14309 for (unsigned i = 0; i != NumElems/2; ++i)
14310 Amt1Csts.push_back(Amt->getOperand(i));
14311 for (unsigned i = NumElems/2; i != NumElems; ++i)
14312 Amt2Csts.push_back(Amt->getOperand(i));
14314 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14315 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14317 // Variable shift amount
14318 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14319 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14322 // Issue new vector shifts for the smaller types
14323 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14324 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14326 // Concatenate the result back
14327 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14333 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14334 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14335 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14336 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14337 // has only one use.
14338 SDNode *N = Op.getNode();
14339 SDValue LHS = N->getOperand(0);
14340 SDValue RHS = N->getOperand(1);
14341 unsigned BaseOp = 0;
14344 switch (Op.getOpcode()) {
14345 default: llvm_unreachable("Unknown ovf instruction!");
14347 // A subtract of one will be selected as a INC. Note that INC doesn't
14348 // set CF, so we can't do this for UADDO.
14349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14351 BaseOp = X86ISD::INC;
14352 Cond = X86::COND_O;
14355 BaseOp = X86ISD::ADD;
14356 Cond = X86::COND_O;
14359 BaseOp = X86ISD::ADD;
14360 Cond = X86::COND_B;
14363 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14364 // set CF, so we can't do this for USUBO.
14365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14367 BaseOp = X86ISD::DEC;
14368 Cond = X86::COND_O;
14371 BaseOp = X86ISD::SUB;
14372 Cond = X86::COND_O;
14375 BaseOp = X86ISD::SUB;
14376 Cond = X86::COND_B;
14379 BaseOp = X86ISD::SMUL;
14380 Cond = X86::COND_O;
14382 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14383 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14385 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14388 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14389 DAG.getConstant(X86::COND_O, MVT::i32),
14390 SDValue(Sum.getNode(), 2));
14392 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14396 // Also sets EFLAGS.
14397 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14398 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14401 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14402 DAG.getConstant(Cond, MVT::i32),
14403 SDValue(Sum.getNode(), 1));
14405 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14408 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14409 SelectionDAG &DAG) const {
14411 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14412 MVT VT = Op.getSimpleValueType();
14414 if (!Subtarget->hasSSE2() || !VT.isVector())
14417 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14418 ExtraVT.getScalarType().getSizeInBits();
14420 switch (VT.SimpleTy) {
14421 default: return SDValue();
14424 if (!Subtarget->hasFp256())
14426 if (!Subtarget->hasInt256()) {
14427 // needs to be split
14428 unsigned NumElems = VT.getVectorNumElements();
14430 // Extract the LHS vectors
14431 SDValue LHS = Op.getOperand(0);
14432 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14433 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14435 MVT EltVT = VT.getVectorElementType();
14436 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14438 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14439 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14440 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14442 SDValue Extra = DAG.getValueType(ExtraVT);
14444 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14445 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14447 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14452 SDValue Op0 = Op.getOperand(0);
14453 SDValue Op00 = Op0.getOperand(0);
14455 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14456 if (Op0.getOpcode() == ISD::BITCAST &&
14457 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14458 // (sext (vzext x)) -> (vsext x)
14459 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14460 if (Tmp1.getNode()) {
14461 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14462 // This folding is only valid when the in-reg type is a vector of i8,
14464 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14465 ExtraEltVT == MVT::i32) {
14466 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14467 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14468 "This optimization is invalid without a VZEXT.");
14469 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14475 // If the above didn't work, then just use Shift-Left + Shift-Right.
14476 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14478 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14484 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14485 SelectionDAG &DAG) {
14487 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14488 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14489 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14490 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14492 // The only fence that needs an instruction is a sequentially-consistent
14493 // cross-thread fence.
14494 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14495 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14496 // no-sse2). There isn't any reason to disable it if the target processor
14498 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14499 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14501 SDValue Chain = Op.getOperand(0);
14502 SDValue Zero = DAG.getConstant(0, MVT::i32);
14504 DAG.getRegister(X86::ESP, MVT::i32), // Base
14505 DAG.getTargetConstant(1, MVT::i8), // Scale
14506 DAG.getRegister(0, MVT::i32), // Index
14507 DAG.getTargetConstant(0, MVT::i32), // Disp
14508 DAG.getRegister(0, MVT::i32), // Segment.
14512 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14513 return SDValue(Res, 0);
14516 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14517 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14520 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14521 SelectionDAG &DAG) {
14522 MVT T = Op.getSimpleValueType();
14526 switch(T.SimpleTy) {
14527 default: llvm_unreachable("Invalid value type!");
14528 case MVT::i8: Reg = X86::AL; size = 1; break;
14529 case MVT::i16: Reg = X86::AX; size = 2; break;
14530 case MVT::i32: Reg = X86::EAX; size = 4; break;
14532 assert(Subtarget->is64Bit() && "Node not type legal!");
14533 Reg = X86::RAX; size = 8;
14536 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14537 Op.getOperand(2), SDValue());
14538 SDValue Ops[] = { cpIn.getValue(0),
14541 DAG.getTargetConstant(size, MVT::i8),
14542 cpIn.getValue(1) };
14543 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14544 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14545 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14549 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14550 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
14551 MVT::i32, cpOut.getValue(2));
14552 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
14553 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
14555 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
14556 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
14557 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
14561 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14562 SelectionDAG &DAG) {
14563 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14564 MVT DstVT = Op.getSimpleValueType();
14566 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14567 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14568 if (DstVT != MVT::f64)
14569 // This conversion needs to be expanded.
14572 SDValue InVec = Op->getOperand(0);
14574 unsigned NumElts = SrcVT.getVectorNumElements();
14575 EVT SVT = SrcVT.getVectorElementType();
14577 // Widen the vector in input in the case of MVT::v2i32.
14578 // Example: from MVT::v2i32 to MVT::v4i32.
14579 SmallVector<SDValue, 16> Elts;
14580 for (unsigned i = 0, e = NumElts; i != e; ++i)
14581 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14582 DAG.getIntPtrConstant(i)));
14584 // Explicitly mark the extra elements as Undef.
14585 SDValue Undef = DAG.getUNDEF(SVT);
14586 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14587 Elts.push_back(Undef);
14589 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14590 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14591 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14592 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14593 DAG.getIntPtrConstant(0));
14596 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14597 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14598 assert((DstVT == MVT::i64 ||
14599 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14600 "Unexpected custom BITCAST");
14601 // i64 <=> MMX conversions are Legal.
14602 if (SrcVT==MVT::i64 && DstVT.isVector())
14604 if (DstVT==MVT::i64 && SrcVT.isVector())
14606 // MMX <=> MMX conversions are Legal.
14607 if (SrcVT.isVector() && DstVT.isVector())
14609 // All other conversions need to be expanded.
14613 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14614 SDNode *Node = Op.getNode();
14616 EVT T = Node->getValueType(0);
14617 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14618 DAG.getConstant(0, T), Node->getOperand(2));
14619 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14620 cast<AtomicSDNode>(Node)->getMemoryVT(),
14621 Node->getOperand(0),
14622 Node->getOperand(1), negOp,
14623 cast<AtomicSDNode>(Node)->getMemOperand(),
14624 cast<AtomicSDNode>(Node)->getOrdering(),
14625 cast<AtomicSDNode>(Node)->getSynchScope());
14628 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14629 SDNode *Node = Op.getNode();
14631 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14633 // Convert seq_cst store -> xchg
14634 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14635 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14636 // (The only way to get a 16-byte store is cmpxchg16b)
14637 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14638 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14639 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14640 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14641 cast<AtomicSDNode>(Node)->getMemoryVT(),
14642 Node->getOperand(0),
14643 Node->getOperand(1), Node->getOperand(2),
14644 cast<AtomicSDNode>(Node)->getMemOperand(),
14645 cast<AtomicSDNode>(Node)->getOrdering(),
14646 cast<AtomicSDNode>(Node)->getSynchScope());
14647 return Swap.getValue(1);
14649 // Other atomic stores have a simple pattern.
14653 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14654 EVT VT = Op.getNode()->getSimpleValueType(0);
14656 // Let legalize expand this if it isn't a legal type yet.
14657 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14660 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14663 bool ExtraOp = false;
14664 switch (Op.getOpcode()) {
14665 default: llvm_unreachable("Invalid code");
14666 case ISD::ADDC: Opc = X86ISD::ADD; break;
14667 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14668 case ISD::SUBC: Opc = X86ISD::SUB; break;
14669 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14673 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14675 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14676 Op.getOperand(1), Op.getOperand(2));
14679 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14680 SelectionDAG &DAG) {
14681 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14683 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14684 // which returns the values as { float, float } (in XMM0) or
14685 // { double, double } (which is returned in XMM0, XMM1).
14687 SDValue Arg = Op.getOperand(0);
14688 EVT ArgVT = Arg.getValueType();
14689 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14691 TargetLowering::ArgListTy Args;
14692 TargetLowering::ArgListEntry Entry;
14696 Entry.isSExt = false;
14697 Entry.isZExt = false;
14698 Args.push_back(Entry);
14700 bool isF64 = ArgVT == MVT::f64;
14701 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14702 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14703 // the results are returned via SRet in memory.
14704 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14705 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14706 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14708 Type *RetTy = isF64
14709 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14710 : (Type*)VectorType::get(ArgTy, 4);
14712 TargetLowering::CallLoweringInfo CLI(DAG);
14713 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14714 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14716 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14719 // Returned in xmm0 and xmm1.
14720 return CallResult.first;
14722 // Returned in bits 0:31 and 32:64 xmm0.
14723 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14724 CallResult.first, DAG.getIntPtrConstant(0));
14725 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14726 CallResult.first, DAG.getIntPtrConstant(1));
14727 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14728 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14731 /// LowerOperation - Provide custom lowering hooks for some operations.
14733 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14734 switch (Op.getOpcode()) {
14735 default: llvm_unreachable("Should not custom lower this!");
14736 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14737 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14738 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
14739 return LowerCMP_SWAP(Op, Subtarget, DAG);
14740 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14741 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14742 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14743 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14744 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14745 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14746 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14747 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14748 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14749 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14750 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14751 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14752 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14753 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14754 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14755 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14756 case ISD::SHL_PARTS:
14757 case ISD::SRA_PARTS:
14758 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14759 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14760 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14761 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14762 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14763 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14764 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14765 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14766 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14767 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14768 case ISD::FABS: return LowerFABS(Op, DAG);
14769 case ISD::FNEG: return LowerFNEG(Op, DAG);
14770 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14771 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14772 case ISD::SETCC: return LowerSETCC(Op, DAG);
14773 case ISD::SELECT: return LowerSELECT(Op, DAG);
14774 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14775 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14776 case ISD::VASTART: return LowerVASTART(Op, DAG);
14777 case ISD::VAARG: return LowerVAARG(Op, DAG);
14778 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14779 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14780 case ISD::INTRINSIC_VOID:
14781 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14782 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14783 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14784 case ISD::FRAME_TO_ARGS_OFFSET:
14785 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14786 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14787 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14788 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14789 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14790 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14791 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14792 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14793 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14794 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14795 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14796 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14797 case ISD::UMUL_LOHI:
14798 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14801 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14807 case ISD::UMULO: return LowerXALUO(Op, DAG);
14808 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14809 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14813 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14814 case ISD::ADD: return LowerADD(Op, DAG);
14815 case ISD::SUB: return LowerSUB(Op, DAG);
14816 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14820 static void ReplaceATOMIC_LOAD(SDNode *Node,
14821 SmallVectorImpl<SDValue> &Results,
14822 SelectionDAG &DAG) {
14824 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14826 // Convert wide load -> cmpxchg8b/cmpxchg16b
14827 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14828 // (The only way to get a 16-byte load is cmpxchg16b)
14829 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14830 SDValue Zero = DAG.getConstant(0, VT);
14831 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
14833 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
14834 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
14835 cast<AtomicSDNode>(Node)->getMemOperand(),
14836 cast<AtomicSDNode>(Node)->getOrdering(),
14837 cast<AtomicSDNode>(Node)->getOrdering(),
14838 cast<AtomicSDNode>(Node)->getSynchScope());
14839 Results.push_back(Swap.getValue(0));
14840 Results.push_back(Swap.getValue(2));
14844 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14845 SelectionDAG &DAG, unsigned NewOp) {
14847 assert (Node->getValueType(0) == MVT::i64 &&
14848 "Only know how to expand i64 atomics");
14850 SDValue Chain = Node->getOperand(0);
14851 SDValue In1 = Node->getOperand(1);
14852 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14853 Node->getOperand(2), DAG.getIntPtrConstant(0));
14854 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14855 Node->getOperand(2), DAG.getIntPtrConstant(1));
14856 SDValue Ops[] = { Chain, In1, In2L, In2H };
14857 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14859 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14860 cast<MemSDNode>(Node)->getMemOperand());
14861 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14862 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14863 Results.push_back(Result.getValue(2));
14866 /// ReplaceNodeResults - Replace a node with an illegal result type
14867 /// with a new node built out of custom code.
14868 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14869 SmallVectorImpl<SDValue>&Results,
14870 SelectionDAG &DAG) const {
14872 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14873 switch (N->getOpcode()) {
14875 llvm_unreachable("Do not know how to custom type legalize this operation!");
14876 case ISD::SIGN_EXTEND_INREG:
14881 // We don't want to expand or promote these.
14888 case ISD::UDIVREM: {
14889 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14890 Results.push_back(V);
14893 case ISD::FP_TO_SINT:
14894 case ISD::FP_TO_UINT: {
14895 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14897 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14900 std::pair<SDValue,SDValue> Vals =
14901 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14902 SDValue FIST = Vals.first, StackSlot = Vals.second;
14903 if (FIST.getNode()) {
14904 EVT VT = N->getValueType(0);
14905 // Return a load from the stack slot.
14906 if (StackSlot.getNode())
14907 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14908 MachinePointerInfo(),
14909 false, false, false, 0));
14911 Results.push_back(FIST);
14915 case ISD::UINT_TO_FP: {
14916 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14917 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14918 N->getValueType(0) != MVT::v2f32)
14920 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14922 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14924 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14925 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14926 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14927 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14928 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14929 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14932 case ISD::FP_ROUND: {
14933 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14935 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14936 Results.push_back(V);
14939 case ISD::INTRINSIC_W_CHAIN: {
14940 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14942 default : llvm_unreachable("Do not know how to custom type "
14943 "legalize this intrinsic operation!");
14944 case Intrinsic::x86_rdtsc:
14945 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14947 case Intrinsic::x86_rdtscp:
14948 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14952 case ISD::READCYCLECOUNTER: {
14953 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14956 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
14957 EVT T = N->getValueType(0);
14958 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14959 bool Regs64bit = T == MVT::i128;
14960 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14961 SDValue cpInL, cpInH;
14962 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14963 DAG.getConstant(0, HalfT));
14964 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14965 DAG.getConstant(1, HalfT));
14966 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14967 Regs64bit ? X86::RAX : X86::EAX,
14969 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14970 Regs64bit ? X86::RDX : X86::EDX,
14971 cpInH, cpInL.getValue(1));
14972 SDValue swapInL, swapInH;
14973 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14974 DAG.getConstant(0, HalfT));
14975 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14976 DAG.getConstant(1, HalfT));
14977 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14978 Regs64bit ? X86::RBX : X86::EBX,
14979 swapInL, cpInH.getValue(1));
14980 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14981 Regs64bit ? X86::RCX : X86::ECX,
14982 swapInH, swapInL.getValue(1));
14983 SDValue Ops[] = { swapInH.getValue(0),
14985 swapInH.getValue(1) };
14986 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14987 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14988 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14989 X86ISD::LCMPXCHG8_DAG;
14990 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14991 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14992 Regs64bit ? X86::RAX : X86::EAX,
14993 HalfT, Result.getValue(1));
14994 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14995 Regs64bit ? X86::RDX : X86::EDX,
14996 HalfT, cpOutL.getValue(2));
14997 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14999 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
15000 MVT::i32, cpOutH.getValue(2));
15002 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15003 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15004 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
15006 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
15007 Results.push_back(Success);
15008 Results.push_back(EFLAGS.getValue(1));
15011 case ISD::ATOMIC_LOAD_ADD:
15012 case ISD::ATOMIC_LOAD_AND:
15013 case ISD::ATOMIC_LOAD_NAND:
15014 case ISD::ATOMIC_LOAD_OR:
15015 case ISD::ATOMIC_LOAD_SUB:
15016 case ISD::ATOMIC_LOAD_XOR:
15017 case ISD::ATOMIC_LOAD_MAX:
15018 case ISD::ATOMIC_LOAD_MIN:
15019 case ISD::ATOMIC_LOAD_UMAX:
15020 case ISD::ATOMIC_LOAD_UMIN:
15021 case ISD::ATOMIC_SWAP: {
15023 switch (N->getOpcode()) {
15024 default: llvm_unreachable("Unexpected opcode");
15025 case ISD::ATOMIC_LOAD_ADD:
15026 Opc = X86ISD::ATOMADD64_DAG;
15028 case ISD::ATOMIC_LOAD_AND:
15029 Opc = X86ISD::ATOMAND64_DAG;
15031 case ISD::ATOMIC_LOAD_NAND:
15032 Opc = X86ISD::ATOMNAND64_DAG;
15034 case ISD::ATOMIC_LOAD_OR:
15035 Opc = X86ISD::ATOMOR64_DAG;
15037 case ISD::ATOMIC_LOAD_SUB:
15038 Opc = X86ISD::ATOMSUB64_DAG;
15040 case ISD::ATOMIC_LOAD_XOR:
15041 Opc = X86ISD::ATOMXOR64_DAG;
15043 case ISD::ATOMIC_LOAD_MAX:
15044 Opc = X86ISD::ATOMMAX64_DAG;
15046 case ISD::ATOMIC_LOAD_MIN:
15047 Opc = X86ISD::ATOMMIN64_DAG;
15049 case ISD::ATOMIC_LOAD_UMAX:
15050 Opc = X86ISD::ATOMUMAX64_DAG;
15052 case ISD::ATOMIC_LOAD_UMIN:
15053 Opc = X86ISD::ATOMUMIN64_DAG;
15055 case ISD::ATOMIC_SWAP:
15056 Opc = X86ISD::ATOMSWAP64_DAG;
15059 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15062 case ISD::ATOMIC_LOAD: {
15063 ReplaceATOMIC_LOAD(N, Results, DAG);
15066 case ISD::BITCAST: {
15067 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15068 EVT DstVT = N->getValueType(0);
15069 EVT SrcVT = N->getOperand(0)->getValueType(0);
15071 if (SrcVT != MVT::f64 ||
15072 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15075 unsigned NumElts = DstVT.getVectorNumElements();
15076 EVT SVT = DstVT.getVectorElementType();
15077 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15078 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15079 MVT::v2f64, N->getOperand(0));
15080 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15082 SmallVector<SDValue, 8> Elts;
15083 for (unsigned i = 0, e = NumElts; i != e; ++i)
15084 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15085 ToVecInt, DAG.getIntPtrConstant(i)));
15087 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15092 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15094 default: return nullptr;
15095 case X86ISD::BSF: return "X86ISD::BSF";
15096 case X86ISD::BSR: return "X86ISD::BSR";
15097 case X86ISD::SHLD: return "X86ISD::SHLD";
15098 case X86ISD::SHRD: return "X86ISD::SHRD";
15099 case X86ISD::FAND: return "X86ISD::FAND";
15100 case X86ISD::FANDN: return "X86ISD::FANDN";
15101 case X86ISD::FOR: return "X86ISD::FOR";
15102 case X86ISD::FXOR: return "X86ISD::FXOR";
15103 case X86ISD::FSRL: return "X86ISD::FSRL";
15104 case X86ISD::FILD: return "X86ISD::FILD";
15105 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
15106 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15107 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15108 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15109 case X86ISD::FLD: return "X86ISD::FLD";
15110 case X86ISD::FST: return "X86ISD::FST";
15111 case X86ISD::CALL: return "X86ISD::CALL";
15112 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
15113 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
15114 case X86ISD::BT: return "X86ISD::BT";
15115 case X86ISD::CMP: return "X86ISD::CMP";
15116 case X86ISD::COMI: return "X86ISD::COMI";
15117 case X86ISD::UCOMI: return "X86ISD::UCOMI";
15118 case X86ISD::CMPM: return "X86ISD::CMPM";
15119 case X86ISD::CMPMU: return "X86ISD::CMPMU";
15120 case X86ISD::SETCC: return "X86ISD::SETCC";
15121 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
15122 case X86ISD::FSETCC: return "X86ISD::FSETCC";
15123 case X86ISD::CMOV: return "X86ISD::CMOV";
15124 case X86ISD::BRCOND: return "X86ISD::BRCOND";
15125 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
15126 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
15127 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
15128 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
15129 case X86ISD::Wrapper: return "X86ISD::Wrapper";
15130 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
15131 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
15132 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
15133 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
15134 case X86ISD::PINSRB: return "X86ISD::PINSRB";
15135 case X86ISD::PINSRW: return "X86ISD::PINSRW";
15136 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
15137 case X86ISD::ANDNP: return "X86ISD::ANDNP";
15138 case X86ISD::PSIGN: return "X86ISD::PSIGN";
15139 case X86ISD::BLENDV: return "X86ISD::BLENDV";
15140 case X86ISD::BLENDI: return "X86ISD::BLENDI";
15141 case X86ISD::SUBUS: return "X86ISD::SUBUS";
15142 case X86ISD::HADD: return "X86ISD::HADD";
15143 case X86ISD::HSUB: return "X86ISD::HSUB";
15144 case X86ISD::FHADD: return "X86ISD::FHADD";
15145 case X86ISD::FHSUB: return "X86ISD::FHSUB";
15146 case X86ISD::UMAX: return "X86ISD::UMAX";
15147 case X86ISD::UMIN: return "X86ISD::UMIN";
15148 case X86ISD::SMAX: return "X86ISD::SMAX";
15149 case X86ISD::SMIN: return "X86ISD::SMIN";
15150 case X86ISD::FMAX: return "X86ISD::FMAX";
15151 case X86ISD::FMIN: return "X86ISD::FMIN";
15152 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15153 case X86ISD::FMINC: return "X86ISD::FMINC";
15154 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15155 case X86ISD::FRCP: return "X86ISD::FRCP";
15156 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15157 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15158 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15159 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15160 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15161 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15162 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15163 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15164 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15165 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15166 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15167 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
15168 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15169 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15170 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15171 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15172 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15173 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15174 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15175 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15176 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15177 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15178 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15179 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15180 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15181 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15182 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15183 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15184 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15185 case X86ISD::VSHL: return "X86ISD::VSHL";
15186 case X86ISD::VSRL: return "X86ISD::VSRL";
15187 case X86ISD::VSRA: return "X86ISD::VSRA";
15188 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15189 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15190 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15191 case X86ISD::CMPP: return "X86ISD::CMPP";
15192 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15193 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15194 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15195 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15196 case X86ISD::ADD: return "X86ISD::ADD";
15197 case X86ISD::SUB: return "X86ISD::SUB";
15198 case X86ISD::ADC: return "X86ISD::ADC";
15199 case X86ISD::SBB: return "X86ISD::SBB";
15200 case X86ISD::SMUL: return "X86ISD::SMUL";
15201 case X86ISD::UMUL: return "X86ISD::UMUL";
15202 case X86ISD::INC: return "X86ISD::INC";
15203 case X86ISD::DEC: return "X86ISD::DEC";
15204 case X86ISD::OR: return "X86ISD::OR";
15205 case X86ISD::XOR: return "X86ISD::XOR";
15206 case X86ISD::AND: return "X86ISD::AND";
15207 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15208 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15209 case X86ISD::PTEST: return "X86ISD::PTEST";
15210 case X86ISD::TESTP: return "X86ISD::TESTP";
15211 case X86ISD::TESTM: return "X86ISD::TESTM";
15212 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15213 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15214 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15215 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15216 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15217 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15218 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15219 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15220 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15221 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15222 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15223 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15224 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15225 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15226 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15227 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15228 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15229 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15230 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15231 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15232 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15233 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15234 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15235 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15236 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15237 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15238 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15239 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15240 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15241 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15242 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15243 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15244 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15245 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15246 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15247 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15248 case X86ISD::SAHF: return "X86ISD::SAHF";
15249 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15250 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15251 case X86ISD::FMADD: return "X86ISD::FMADD";
15252 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15253 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15254 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15255 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15256 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15257 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15258 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15259 case X86ISD::XTEST: return "X86ISD::XTEST";
15263 // isLegalAddressingMode - Return true if the addressing mode represented
15264 // by AM is legal for this target, for a load/store of the specified type.
15265 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15267 // X86 supports extremely general addressing modes.
15268 CodeModel::Model M = getTargetMachine().getCodeModel();
15269 Reloc::Model R = getTargetMachine().getRelocationModel();
15271 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15272 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15277 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15279 // If a reference to this global requires an extra load, we can't fold it.
15280 if (isGlobalStubReference(GVFlags))
15283 // If BaseGV requires a register for the PIC base, we cannot also have a
15284 // BaseReg specified.
15285 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15288 // If lower 4G is not available, then we must use rip-relative addressing.
15289 if ((M != CodeModel::Small || R != Reloc::Static) &&
15290 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15294 switch (AM.Scale) {
15300 // These scales always work.
15305 // These scales are formed with basereg+scalereg. Only accept if there is
15310 default: // Other stuff never works.
15317 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15318 unsigned Bits = Ty->getScalarSizeInBits();
15320 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15321 // particularly cheaper than those without.
15325 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15326 // variable shifts just as cheap as scalar ones.
15327 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15330 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15331 // fully general vector.
15335 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15336 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15338 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15339 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15340 return NumBits1 > NumBits2;
15343 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15344 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15347 if (!isTypeLegal(EVT::getEVT(Ty1)))
15350 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15352 // Assuming the caller doesn't have a zeroext or signext return parameter,
15353 // truncation all the way down to i1 is valid.
15357 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15358 return isInt<32>(Imm);
15361 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15362 // Can also use sub to handle negated immediates.
15363 return isInt<32>(Imm);
15366 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15367 if (!VT1.isInteger() || !VT2.isInteger())
15369 unsigned NumBits1 = VT1.getSizeInBits();
15370 unsigned NumBits2 = VT2.getSizeInBits();
15371 return NumBits1 > NumBits2;
15374 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15375 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15376 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15379 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15380 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15381 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15384 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15385 EVT VT1 = Val.getValueType();
15386 if (isZExtFree(VT1, VT2))
15389 if (Val.getOpcode() != ISD::LOAD)
15392 if (!VT1.isSimple() || !VT1.isInteger() ||
15393 !VT2.isSimple() || !VT2.isInteger())
15396 switch (VT1.getSimpleVT().SimpleTy) {
15401 // X86 has 8, 16, and 32-bit zero-extending loads.
15409 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15410 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15413 VT = VT.getScalarType();
15415 if (!VT.isSimple())
15418 switch (VT.getSimpleVT().SimpleTy) {
15429 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15430 // i16 instructions are longer (0x66 prefix) and potentially slower.
15431 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15434 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15435 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15436 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15437 /// are assumed to be legal.
15439 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15441 if (!VT.isSimple())
15444 MVT SVT = VT.getSimpleVT();
15446 // Very little shuffling can be done for 64-bit vectors right now.
15447 if (VT.getSizeInBits() == 64)
15450 // If this is a single-input shuffle with no 128 bit lane crossings we can
15451 // lower it into pshufb.
15452 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15453 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15454 bool isLegal = true;
15455 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15456 if (M[I] >= (int)SVT.getVectorNumElements() ||
15457 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15466 // FIXME: blends, shifts.
15467 return (SVT.getVectorNumElements() == 2 ||
15468 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15469 isMOVLMask(M, SVT) ||
15470 isSHUFPMask(M, SVT) ||
15471 isPSHUFDMask(M, SVT) ||
15472 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15473 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15474 isPALIGNRMask(M, SVT, Subtarget) ||
15475 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15476 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15477 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15478 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15479 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15483 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15485 if (!VT.isSimple())
15488 MVT SVT = VT.getSimpleVT();
15489 unsigned NumElts = SVT.getVectorNumElements();
15490 // FIXME: This collection of masks seems suspect.
15493 if (NumElts == 4 && SVT.is128BitVector()) {
15494 return (isMOVLMask(Mask, SVT) ||
15495 isCommutedMOVLMask(Mask, SVT, true) ||
15496 isSHUFPMask(Mask, SVT) ||
15497 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15502 //===----------------------------------------------------------------------===//
15503 // X86 Scheduler Hooks
15504 //===----------------------------------------------------------------------===//
15506 /// Utility function to emit xbegin specifying the start of an RTM region.
15507 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15508 const TargetInstrInfo *TII) {
15509 DebugLoc DL = MI->getDebugLoc();
15511 const BasicBlock *BB = MBB->getBasicBlock();
15512 MachineFunction::iterator I = MBB;
15515 // For the v = xbegin(), we generate
15526 MachineBasicBlock *thisMBB = MBB;
15527 MachineFunction *MF = MBB->getParent();
15528 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15529 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15530 MF->insert(I, mainMBB);
15531 MF->insert(I, sinkMBB);
15533 // Transfer the remainder of BB and its successor edges to sinkMBB.
15534 sinkMBB->splice(sinkMBB->begin(), MBB,
15535 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15536 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15540 // # fallthrough to mainMBB
15541 // # abortion to sinkMBB
15542 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15543 thisMBB->addSuccessor(mainMBB);
15544 thisMBB->addSuccessor(sinkMBB);
15548 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15549 mainMBB->addSuccessor(sinkMBB);
15552 // EAX is live into the sinkMBB
15553 sinkMBB->addLiveIn(X86::EAX);
15554 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15555 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15558 MI->eraseFromParent();
15562 // Get CMPXCHG opcode for the specified data type.
15563 static unsigned getCmpXChgOpcode(EVT VT) {
15564 switch (VT.getSimpleVT().SimpleTy) {
15565 case MVT::i8: return X86::LCMPXCHG8;
15566 case MVT::i16: return X86::LCMPXCHG16;
15567 case MVT::i32: return X86::LCMPXCHG32;
15568 case MVT::i64: return X86::LCMPXCHG64;
15572 llvm_unreachable("Invalid operand size!");
15575 // Get LOAD opcode for the specified data type.
15576 static unsigned getLoadOpcode(EVT VT) {
15577 switch (VT.getSimpleVT().SimpleTy) {
15578 case MVT::i8: return X86::MOV8rm;
15579 case MVT::i16: return X86::MOV16rm;
15580 case MVT::i32: return X86::MOV32rm;
15581 case MVT::i64: return X86::MOV64rm;
15585 llvm_unreachable("Invalid operand size!");
15588 // Get opcode of the non-atomic one from the specified atomic instruction.
15589 static unsigned getNonAtomicOpcode(unsigned Opc) {
15591 case X86::ATOMAND8: return X86::AND8rr;
15592 case X86::ATOMAND16: return X86::AND16rr;
15593 case X86::ATOMAND32: return X86::AND32rr;
15594 case X86::ATOMAND64: return X86::AND64rr;
15595 case X86::ATOMOR8: return X86::OR8rr;
15596 case X86::ATOMOR16: return X86::OR16rr;
15597 case X86::ATOMOR32: return X86::OR32rr;
15598 case X86::ATOMOR64: return X86::OR64rr;
15599 case X86::ATOMXOR8: return X86::XOR8rr;
15600 case X86::ATOMXOR16: return X86::XOR16rr;
15601 case X86::ATOMXOR32: return X86::XOR32rr;
15602 case X86::ATOMXOR64: return X86::XOR64rr;
15604 llvm_unreachable("Unhandled atomic-load-op opcode!");
15607 // Get opcode of the non-atomic one from the specified atomic instruction with
15609 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15610 unsigned &ExtraOpc) {
15612 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15613 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15614 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15615 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15616 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15617 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15618 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15619 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15620 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15621 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15622 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15623 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15624 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15625 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15626 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15627 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15628 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15629 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15630 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15631 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15633 llvm_unreachable("Unhandled atomic-load-op opcode!");
15636 // Get opcode of the non-atomic one from the specified atomic instruction for
15637 // 64-bit data type on 32-bit target.
15638 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15640 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15641 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15642 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15643 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15644 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15645 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15646 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15647 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15648 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15649 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15651 llvm_unreachable("Unhandled atomic-load-op opcode!");
15654 // Get opcode of the non-atomic one from the specified atomic instruction for
15655 // 64-bit data type on 32-bit target with extra opcode.
15656 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15658 unsigned &ExtraOpc) {
15660 case X86::ATOMNAND6432:
15661 ExtraOpc = X86::NOT32r;
15662 HiOpc = X86::AND32rr;
15663 return X86::AND32rr;
15665 llvm_unreachable("Unhandled atomic-load-op opcode!");
15668 // Get pseudo CMOV opcode from the specified data type.
15669 static unsigned getPseudoCMOVOpc(EVT VT) {
15670 switch (VT.getSimpleVT().SimpleTy) {
15671 case MVT::i8: return X86::CMOV_GR8;
15672 case MVT::i16: return X86::CMOV_GR16;
15673 case MVT::i32: return X86::CMOV_GR32;
15677 llvm_unreachable("Unknown CMOV opcode!");
15680 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15681 // They will be translated into a spin-loop or compare-exchange loop from
15684 // dst = atomic-fetch-op MI.addr, MI.val
15690 // t1 = LOAD MI.addr
15692 // t4 = phi(t1, t3 / loop)
15693 // t2 = OP MI.val, t4
15695 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15701 MachineBasicBlock *
15702 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15703 MachineBasicBlock *MBB) const {
15704 MachineFunction *MF = MBB->getParent();
15705 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15706 DebugLoc DL = MI->getDebugLoc();
15708 MachineRegisterInfo &MRI = MF->getRegInfo();
15710 const BasicBlock *BB = MBB->getBasicBlock();
15711 MachineFunction::iterator I = MBB;
15714 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15715 "Unexpected number of operands");
15717 assert(MI->hasOneMemOperand() &&
15718 "Expected atomic-load-op to have one memoperand");
15720 // Memory Reference
15721 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15722 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15724 unsigned DstReg, SrcReg;
15725 unsigned MemOpndSlot;
15727 unsigned CurOp = 0;
15729 DstReg = MI->getOperand(CurOp++).getReg();
15730 MemOpndSlot = CurOp;
15731 CurOp += X86::AddrNumOperands;
15732 SrcReg = MI->getOperand(CurOp++).getReg();
15734 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15735 MVT::SimpleValueType VT = *RC->vt_begin();
15736 unsigned t1 = MRI.createVirtualRegister(RC);
15737 unsigned t2 = MRI.createVirtualRegister(RC);
15738 unsigned t3 = MRI.createVirtualRegister(RC);
15739 unsigned t4 = MRI.createVirtualRegister(RC);
15740 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15742 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15743 unsigned LOADOpc = getLoadOpcode(VT);
15745 // For the atomic load-arith operator, we generate
15748 // t1 = LOAD [MI.addr]
15750 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15751 // t1 = OP MI.val, EAX
15753 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15759 MachineBasicBlock *thisMBB = MBB;
15760 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15761 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15762 MF->insert(I, mainMBB);
15763 MF->insert(I, sinkMBB);
15765 MachineInstrBuilder MIB;
15767 // Transfer the remainder of BB and its successor edges to sinkMBB.
15768 sinkMBB->splice(sinkMBB->begin(), MBB,
15769 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15770 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15773 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15774 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15775 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15777 NewMO.setIsKill(false);
15778 MIB.addOperand(NewMO);
15780 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15781 unsigned flags = (*MMOI)->getFlags();
15782 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15783 MachineMemOperand *MMO =
15784 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15785 (*MMOI)->getSize(),
15786 (*MMOI)->getBaseAlignment(),
15787 (*MMOI)->getTBAAInfo(),
15788 (*MMOI)->getRanges());
15789 MIB.addMemOperand(MMO);
15792 thisMBB->addSuccessor(mainMBB);
15795 MachineBasicBlock *origMainMBB = mainMBB;
15798 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15799 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15801 unsigned Opc = MI->getOpcode();
15804 llvm_unreachable("Unhandled atomic-load-op opcode!");
15805 case X86::ATOMAND8:
15806 case X86::ATOMAND16:
15807 case X86::ATOMAND32:
15808 case X86::ATOMAND64:
15810 case X86::ATOMOR16:
15811 case X86::ATOMOR32:
15812 case X86::ATOMOR64:
15813 case X86::ATOMXOR8:
15814 case X86::ATOMXOR16:
15815 case X86::ATOMXOR32:
15816 case X86::ATOMXOR64: {
15817 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15818 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15822 case X86::ATOMNAND8:
15823 case X86::ATOMNAND16:
15824 case X86::ATOMNAND32:
15825 case X86::ATOMNAND64: {
15826 unsigned Tmp = MRI.createVirtualRegister(RC);
15828 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15829 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15831 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15834 case X86::ATOMMAX8:
15835 case X86::ATOMMAX16:
15836 case X86::ATOMMAX32:
15837 case X86::ATOMMAX64:
15838 case X86::ATOMMIN8:
15839 case X86::ATOMMIN16:
15840 case X86::ATOMMIN32:
15841 case X86::ATOMMIN64:
15842 case X86::ATOMUMAX8:
15843 case X86::ATOMUMAX16:
15844 case X86::ATOMUMAX32:
15845 case X86::ATOMUMAX64:
15846 case X86::ATOMUMIN8:
15847 case X86::ATOMUMIN16:
15848 case X86::ATOMUMIN32:
15849 case X86::ATOMUMIN64: {
15851 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15853 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15857 if (Subtarget->hasCMov()) {
15858 if (VT != MVT::i8) {
15860 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15864 // Promote i8 to i32 to use CMOV32
15865 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
15866 const TargetRegisterClass *RC32 =
15867 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15868 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15869 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15870 unsigned Tmp = MRI.createVirtualRegister(RC32);
15872 unsigned Undef = MRI.createVirtualRegister(RC32);
15873 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15875 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15878 .addImm(X86::sub_8bit);
15879 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15882 .addImm(X86::sub_8bit);
15884 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15888 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15889 .addReg(Tmp, 0, X86::sub_8bit);
15892 // Use pseudo select and lower them.
15893 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15894 "Invalid atomic-load-op transformation!");
15895 unsigned SelOpc = getPseudoCMOVOpc(VT);
15896 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15897 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15898 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15899 .addReg(SrcReg).addReg(t4)
15901 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15902 // Replace the original PHI node as mainMBB is changed after CMOV
15904 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15905 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15906 Phi->eraseFromParent();
15912 // Copy PhyReg back from virtual register.
15913 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15916 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15917 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15918 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15920 NewMO.setIsKill(false);
15921 MIB.addOperand(NewMO);
15924 MIB.setMemRefs(MMOBegin, MMOEnd);
15926 // Copy PhyReg back to virtual register.
15927 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15930 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15932 mainMBB->addSuccessor(origMainMBB);
15933 mainMBB->addSuccessor(sinkMBB);
15936 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15937 TII->get(TargetOpcode::COPY), DstReg)
15940 MI->eraseFromParent();
15944 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15945 // instructions. They will be translated into a spin-loop or compare-exchange
15949 // dst = atomic-fetch-op MI.addr, MI.val
15955 // t1L = LOAD [MI.addr + 0]
15956 // t1H = LOAD [MI.addr + 4]
15958 // t4L = phi(t1L, t3L / loop)
15959 // t4H = phi(t1H, t3H / loop)
15960 // t2L = OP MI.val.lo, t4L
15961 // t2H = OP MI.val.hi, t4H
15966 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15974 MachineBasicBlock *
15975 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15976 MachineBasicBlock *MBB) const {
15977 MachineFunction *MF = MBB->getParent();
15978 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15979 DebugLoc DL = MI->getDebugLoc();
15981 MachineRegisterInfo &MRI = MF->getRegInfo();
15983 const BasicBlock *BB = MBB->getBasicBlock();
15984 MachineFunction::iterator I = MBB;
15987 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15988 "Unexpected number of operands");
15990 assert(MI->hasOneMemOperand() &&
15991 "Expected atomic-load-op32 to have one memoperand");
15993 // Memory Reference
15994 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15995 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15997 unsigned DstLoReg, DstHiReg;
15998 unsigned SrcLoReg, SrcHiReg;
15999 unsigned MemOpndSlot;
16001 unsigned CurOp = 0;
16003 DstLoReg = MI->getOperand(CurOp++).getReg();
16004 DstHiReg = MI->getOperand(CurOp++).getReg();
16005 MemOpndSlot = CurOp;
16006 CurOp += X86::AddrNumOperands;
16007 SrcLoReg = MI->getOperand(CurOp++).getReg();
16008 SrcHiReg = MI->getOperand(CurOp++).getReg();
16010 const TargetRegisterClass *RC = &X86::GR32RegClass;
16011 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
16013 unsigned t1L = MRI.createVirtualRegister(RC);
16014 unsigned t1H = MRI.createVirtualRegister(RC);
16015 unsigned t2L = MRI.createVirtualRegister(RC);
16016 unsigned t2H = MRI.createVirtualRegister(RC);
16017 unsigned t3L = MRI.createVirtualRegister(RC);
16018 unsigned t3H = MRI.createVirtualRegister(RC);
16019 unsigned t4L = MRI.createVirtualRegister(RC);
16020 unsigned t4H = MRI.createVirtualRegister(RC);
16022 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
16023 unsigned LOADOpc = X86::MOV32rm;
16025 // For the atomic load-arith operator, we generate
16028 // t1L = LOAD [MI.addr + 0]
16029 // t1H = LOAD [MI.addr + 4]
16031 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
16032 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
16033 // t2L = OP MI.val.lo, t4L
16034 // t2H = OP MI.val.hi, t4H
16037 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16045 MachineBasicBlock *thisMBB = MBB;
16046 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16047 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16048 MF->insert(I, mainMBB);
16049 MF->insert(I, sinkMBB);
16051 MachineInstrBuilder MIB;
16053 // Transfer the remainder of BB and its successor edges to sinkMBB.
16054 sinkMBB->splice(sinkMBB->begin(), MBB,
16055 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16056 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16060 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
16061 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16062 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16064 NewMO.setIsKill(false);
16065 MIB.addOperand(NewMO);
16067 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16068 unsigned flags = (*MMOI)->getFlags();
16069 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16070 MachineMemOperand *MMO =
16071 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16072 (*MMOI)->getSize(),
16073 (*MMOI)->getBaseAlignment(),
16074 (*MMOI)->getTBAAInfo(),
16075 (*MMOI)->getRanges());
16076 MIB.addMemOperand(MMO);
16078 MachineInstr *LowMI = MIB;
16081 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16082 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16083 if (i == X86::AddrDisp) {
16084 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16086 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16088 NewMO.setIsKill(false);
16089 MIB.addOperand(NewMO);
16092 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16094 thisMBB->addSuccessor(mainMBB);
16097 MachineBasicBlock *origMainMBB = mainMBB;
16100 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16101 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16102 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16103 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16105 unsigned Opc = MI->getOpcode();
16108 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16109 case X86::ATOMAND6432:
16110 case X86::ATOMOR6432:
16111 case X86::ATOMXOR6432:
16112 case X86::ATOMADD6432:
16113 case X86::ATOMSUB6432: {
16115 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16116 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16118 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16122 case X86::ATOMNAND6432: {
16123 unsigned HiOpc, NOTOpc;
16124 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16125 unsigned TmpL = MRI.createVirtualRegister(RC);
16126 unsigned TmpH = MRI.createVirtualRegister(RC);
16127 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16129 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16131 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16132 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16135 case X86::ATOMMAX6432:
16136 case X86::ATOMMIN6432:
16137 case X86::ATOMUMAX6432:
16138 case X86::ATOMUMIN6432: {
16140 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16141 unsigned cL = MRI.createVirtualRegister(RC8);
16142 unsigned cH = MRI.createVirtualRegister(RC8);
16143 unsigned cL32 = MRI.createVirtualRegister(RC);
16144 unsigned cH32 = MRI.createVirtualRegister(RC);
16145 unsigned cc = MRI.createVirtualRegister(RC);
16146 // cl := cmp src_lo, lo
16147 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16148 .addReg(SrcLoReg).addReg(t4L);
16149 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16150 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16151 // ch := cmp src_hi, hi
16152 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16153 .addReg(SrcHiReg).addReg(t4H);
16154 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16155 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16156 // cc := if (src_hi == hi) ? cl : ch;
16157 if (Subtarget->hasCMov()) {
16158 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16159 .addReg(cH32).addReg(cL32);
16161 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16162 .addReg(cH32).addReg(cL32)
16163 .addImm(X86::COND_E);
16164 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16166 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16167 if (Subtarget->hasCMov()) {
16168 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16169 .addReg(SrcLoReg).addReg(t4L);
16170 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16171 .addReg(SrcHiReg).addReg(t4H);
16173 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16174 .addReg(SrcLoReg).addReg(t4L)
16175 .addImm(X86::COND_NE);
16176 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16177 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16178 // 2nd CMOV lowering.
16179 mainMBB->addLiveIn(X86::EFLAGS);
16180 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16181 .addReg(SrcHiReg).addReg(t4H)
16182 .addImm(X86::COND_NE);
16183 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16184 // Replace the original PHI node as mainMBB is changed after CMOV
16186 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16187 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16188 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16189 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16190 PhiL->eraseFromParent();
16191 PhiH->eraseFromParent();
16195 case X86::ATOMSWAP6432: {
16197 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16198 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16199 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16204 // Copy EDX:EAX back from HiReg:LoReg
16205 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16206 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16207 // Copy ECX:EBX from t1H:t1L
16208 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16209 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16211 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16212 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16213 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16215 NewMO.setIsKill(false);
16216 MIB.addOperand(NewMO);
16218 MIB.setMemRefs(MMOBegin, MMOEnd);
16220 // Copy EDX:EAX back to t3H:t3L
16221 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16222 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16224 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16226 mainMBB->addSuccessor(origMainMBB);
16227 mainMBB->addSuccessor(sinkMBB);
16230 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16231 TII->get(TargetOpcode::COPY), DstLoReg)
16233 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16234 TII->get(TargetOpcode::COPY), DstHiReg)
16237 MI->eraseFromParent();
16241 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16242 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16243 // in the .td file.
16244 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16245 const TargetInstrInfo *TII) {
16247 switch (MI->getOpcode()) {
16248 default: llvm_unreachable("illegal opcode!");
16249 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16250 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16251 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16252 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16253 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16254 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16255 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16256 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16259 DebugLoc dl = MI->getDebugLoc();
16260 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16262 unsigned NumArgs = MI->getNumOperands();
16263 for (unsigned i = 1; i < NumArgs; ++i) {
16264 MachineOperand &Op = MI->getOperand(i);
16265 if (!(Op.isReg() && Op.isImplicit()))
16266 MIB.addOperand(Op);
16268 if (MI->hasOneMemOperand())
16269 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16271 BuildMI(*BB, MI, dl,
16272 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16273 .addReg(X86::XMM0);
16275 MI->eraseFromParent();
16279 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16280 // defs in an instruction pattern
16281 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16282 const TargetInstrInfo *TII) {
16284 switch (MI->getOpcode()) {
16285 default: llvm_unreachable("illegal opcode!");
16286 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16287 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16288 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16289 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16290 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16291 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16292 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16293 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16296 DebugLoc dl = MI->getDebugLoc();
16297 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16299 unsigned NumArgs = MI->getNumOperands(); // remove the results
16300 for (unsigned i = 1; i < NumArgs; ++i) {
16301 MachineOperand &Op = MI->getOperand(i);
16302 if (!(Op.isReg() && Op.isImplicit()))
16303 MIB.addOperand(Op);
16305 if (MI->hasOneMemOperand())
16306 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16308 BuildMI(*BB, MI, dl,
16309 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16312 MI->eraseFromParent();
16316 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16317 const TargetInstrInfo *TII,
16318 const X86Subtarget* Subtarget) {
16319 DebugLoc dl = MI->getDebugLoc();
16321 // Address into RAX/EAX, other two args into ECX, EDX.
16322 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16323 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16324 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16325 for (int i = 0; i < X86::AddrNumOperands; ++i)
16326 MIB.addOperand(MI->getOperand(i));
16328 unsigned ValOps = X86::AddrNumOperands;
16329 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16330 .addReg(MI->getOperand(ValOps).getReg());
16331 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16332 .addReg(MI->getOperand(ValOps+1).getReg());
16334 // The instruction doesn't actually take any operands though.
16335 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16337 MI->eraseFromParent(); // The pseudo is gone now.
16341 MachineBasicBlock *
16342 X86TargetLowering::EmitVAARG64WithCustomInserter(
16344 MachineBasicBlock *MBB) const {
16345 // Emit va_arg instruction on X86-64.
16347 // Operands to this pseudo-instruction:
16348 // 0 ) Output : destination address (reg)
16349 // 1-5) Input : va_list address (addr, i64mem)
16350 // 6 ) ArgSize : Size (in bytes) of vararg type
16351 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16352 // 8 ) Align : Alignment of type
16353 // 9 ) EFLAGS (implicit-def)
16355 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16356 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16358 unsigned DestReg = MI->getOperand(0).getReg();
16359 MachineOperand &Base = MI->getOperand(1);
16360 MachineOperand &Scale = MI->getOperand(2);
16361 MachineOperand &Index = MI->getOperand(3);
16362 MachineOperand &Disp = MI->getOperand(4);
16363 MachineOperand &Segment = MI->getOperand(5);
16364 unsigned ArgSize = MI->getOperand(6).getImm();
16365 unsigned ArgMode = MI->getOperand(7).getImm();
16366 unsigned Align = MI->getOperand(8).getImm();
16368 // Memory Reference
16369 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16370 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16371 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16373 // Machine Information
16374 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16375 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16376 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16377 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16378 DebugLoc DL = MI->getDebugLoc();
16380 // struct va_list {
16383 // i64 overflow_area (address)
16384 // i64 reg_save_area (address)
16386 // sizeof(va_list) = 24
16387 // alignment(va_list) = 8
16389 unsigned TotalNumIntRegs = 6;
16390 unsigned TotalNumXMMRegs = 8;
16391 bool UseGPOffset = (ArgMode == 1);
16392 bool UseFPOffset = (ArgMode == 2);
16393 unsigned MaxOffset = TotalNumIntRegs * 8 +
16394 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16396 /* Align ArgSize to a multiple of 8 */
16397 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16398 bool NeedsAlign = (Align > 8);
16400 MachineBasicBlock *thisMBB = MBB;
16401 MachineBasicBlock *overflowMBB;
16402 MachineBasicBlock *offsetMBB;
16403 MachineBasicBlock *endMBB;
16405 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16406 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16407 unsigned OffsetReg = 0;
16409 if (!UseGPOffset && !UseFPOffset) {
16410 // If we only pull from the overflow region, we don't create a branch.
16411 // We don't need to alter control flow.
16412 OffsetDestReg = 0; // unused
16413 OverflowDestReg = DestReg;
16415 offsetMBB = nullptr;
16416 overflowMBB = thisMBB;
16419 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16420 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16421 // If not, pull from overflow_area. (branch to overflowMBB)
16426 // offsetMBB overflowMBB
16431 // Registers for the PHI in endMBB
16432 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16433 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16435 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16436 MachineFunction *MF = MBB->getParent();
16437 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16438 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16439 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16441 MachineFunction::iterator MBBIter = MBB;
16444 // Insert the new basic blocks
16445 MF->insert(MBBIter, offsetMBB);
16446 MF->insert(MBBIter, overflowMBB);
16447 MF->insert(MBBIter, endMBB);
16449 // Transfer the remainder of MBB and its successor edges to endMBB.
16450 endMBB->splice(endMBB->begin(), thisMBB,
16451 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16452 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16454 // Make offsetMBB and overflowMBB successors of thisMBB
16455 thisMBB->addSuccessor(offsetMBB);
16456 thisMBB->addSuccessor(overflowMBB);
16458 // endMBB is a successor of both offsetMBB and overflowMBB
16459 offsetMBB->addSuccessor(endMBB);
16460 overflowMBB->addSuccessor(endMBB);
16462 // Load the offset value into a register
16463 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16464 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16468 .addDisp(Disp, UseFPOffset ? 4 : 0)
16469 .addOperand(Segment)
16470 .setMemRefs(MMOBegin, MMOEnd);
16472 // Check if there is enough room left to pull this argument.
16473 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16475 .addImm(MaxOffset + 8 - ArgSizeA8);
16477 // Branch to "overflowMBB" if offset >= max
16478 // Fall through to "offsetMBB" otherwise
16479 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16480 .addMBB(overflowMBB);
16483 // In offsetMBB, emit code to use the reg_save_area.
16485 assert(OffsetReg != 0);
16487 // Read the reg_save_area address.
16488 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16489 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16494 .addOperand(Segment)
16495 .setMemRefs(MMOBegin, MMOEnd);
16497 // Zero-extend the offset
16498 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16499 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16502 .addImm(X86::sub_32bit);
16504 // Add the offset to the reg_save_area to get the final address.
16505 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16506 .addReg(OffsetReg64)
16507 .addReg(RegSaveReg);
16509 // Compute the offset for the next argument
16510 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16511 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16513 .addImm(UseFPOffset ? 16 : 8);
16515 // Store it back into the va_list.
16516 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16520 .addDisp(Disp, UseFPOffset ? 4 : 0)
16521 .addOperand(Segment)
16522 .addReg(NextOffsetReg)
16523 .setMemRefs(MMOBegin, MMOEnd);
16526 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16531 // Emit code to use overflow area
16534 // Load the overflow_area address into a register.
16535 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16536 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16541 .addOperand(Segment)
16542 .setMemRefs(MMOBegin, MMOEnd);
16544 // If we need to align it, do so. Otherwise, just copy the address
16545 // to OverflowDestReg.
16547 // Align the overflow address
16548 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16549 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16551 // aligned_addr = (addr + (align-1)) & ~(align-1)
16552 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16553 .addReg(OverflowAddrReg)
16556 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16558 .addImm(~(uint64_t)(Align-1));
16560 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16561 .addReg(OverflowAddrReg);
16564 // Compute the next overflow address after this argument.
16565 // (the overflow address should be kept 8-byte aligned)
16566 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16567 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16568 .addReg(OverflowDestReg)
16569 .addImm(ArgSizeA8);
16571 // Store the new overflow address.
16572 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16577 .addOperand(Segment)
16578 .addReg(NextAddrReg)
16579 .setMemRefs(MMOBegin, MMOEnd);
16581 // If we branched, emit the PHI to the front of endMBB.
16583 BuildMI(*endMBB, endMBB->begin(), DL,
16584 TII->get(X86::PHI), DestReg)
16585 .addReg(OffsetDestReg).addMBB(offsetMBB)
16586 .addReg(OverflowDestReg).addMBB(overflowMBB);
16589 // Erase the pseudo instruction
16590 MI->eraseFromParent();
16595 MachineBasicBlock *
16596 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16598 MachineBasicBlock *MBB) const {
16599 // Emit code to save XMM registers to the stack. The ABI says that the
16600 // number of registers to save is given in %al, so it's theoretically
16601 // possible to do an indirect jump trick to avoid saving all of them,
16602 // however this code takes a simpler approach and just executes all
16603 // of the stores if %al is non-zero. It's less code, and it's probably
16604 // easier on the hardware branch predictor, and stores aren't all that
16605 // expensive anyway.
16607 // Create the new basic blocks. One block contains all the XMM stores,
16608 // and one block is the final destination regardless of whether any
16609 // stores were performed.
16610 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16611 MachineFunction *F = MBB->getParent();
16612 MachineFunction::iterator MBBIter = MBB;
16614 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16615 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16616 F->insert(MBBIter, XMMSaveMBB);
16617 F->insert(MBBIter, EndMBB);
16619 // Transfer the remainder of MBB and its successor edges to EndMBB.
16620 EndMBB->splice(EndMBB->begin(), MBB,
16621 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16622 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16624 // The original block will now fall through to the XMM save block.
16625 MBB->addSuccessor(XMMSaveMBB);
16626 // The XMMSaveMBB will fall through to the end block.
16627 XMMSaveMBB->addSuccessor(EndMBB);
16629 // Now add the instructions.
16630 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16631 DebugLoc DL = MI->getDebugLoc();
16633 unsigned CountReg = MI->getOperand(0).getReg();
16634 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16635 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16637 if (!Subtarget->isTargetWin64()) {
16638 // If %al is 0, branch around the XMM save block.
16639 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16640 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16641 MBB->addSuccessor(EndMBB);
16644 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16645 // that was just emitted, but clearly shouldn't be "saved".
16646 assert((MI->getNumOperands() <= 3 ||
16647 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16648 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16649 && "Expected last argument to be EFLAGS");
16650 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16651 // In the XMM save block, save all the XMM argument registers.
16652 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16653 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16654 MachineMemOperand *MMO =
16655 F->getMachineMemOperand(
16656 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16657 MachineMemOperand::MOStore,
16658 /*Size=*/16, /*Align=*/16);
16659 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16660 .addFrameIndex(RegSaveFrameIndex)
16661 .addImm(/*Scale=*/1)
16662 .addReg(/*IndexReg=*/0)
16663 .addImm(/*Disp=*/Offset)
16664 .addReg(/*Segment=*/0)
16665 .addReg(MI->getOperand(i).getReg())
16666 .addMemOperand(MMO);
16669 MI->eraseFromParent(); // The pseudo instruction is gone now.
16674 // The EFLAGS operand of SelectItr might be missing a kill marker
16675 // because there were multiple uses of EFLAGS, and ISel didn't know
16676 // which to mark. Figure out whether SelectItr should have had a
16677 // kill marker, and set it if it should. Returns the correct kill
16679 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16680 MachineBasicBlock* BB,
16681 const TargetRegisterInfo* TRI) {
16682 // Scan forward through BB for a use/def of EFLAGS.
16683 MachineBasicBlock::iterator miI(std::next(SelectItr));
16684 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16685 const MachineInstr& mi = *miI;
16686 if (mi.readsRegister(X86::EFLAGS))
16688 if (mi.definesRegister(X86::EFLAGS))
16689 break; // Should have kill-flag - update below.
16692 // If we hit the end of the block, check whether EFLAGS is live into a
16694 if (miI == BB->end()) {
16695 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16696 sEnd = BB->succ_end();
16697 sItr != sEnd; ++sItr) {
16698 MachineBasicBlock* succ = *sItr;
16699 if (succ->isLiveIn(X86::EFLAGS))
16704 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16705 // out. SelectMI should have a kill flag on EFLAGS.
16706 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16710 MachineBasicBlock *
16711 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16712 MachineBasicBlock *BB) const {
16713 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16714 DebugLoc DL = MI->getDebugLoc();
16716 // To "insert" a SELECT_CC instruction, we actually have to insert the
16717 // diamond control-flow pattern. The incoming instruction knows the
16718 // destination vreg to set, the condition code register to branch on, the
16719 // true/false values to select between, and a branch opcode to use.
16720 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16721 MachineFunction::iterator It = BB;
16727 // cmpTY ccX, r1, r2
16729 // fallthrough --> copy0MBB
16730 MachineBasicBlock *thisMBB = BB;
16731 MachineFunction *F = BB->getParent();
16732 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16733 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16734 F->insert(It, copy0MBB);
16735 F->insert(It, sinkMBB);
16737 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16738 // live into the sink and copy blocks.
16739 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16740 if (!MI->killsRegister(X86::EFLAGS) &&
16741 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16742 copy0MBB->addLiveIn(X86::EFLAGS);
16743 sinkMBB->addLiveIn(X86::EFLAGS);
16746 // Transfer the remainder of BB and its successor edges to sinkMBB.
16747 sinkMBB->splice(sinkMBB->begin(), BB,
16748 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16749 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16751 // Add the true and fallthrough blocks as its successors.
16752 BB->addSuccessor(copy0MBB);
16753 BB->addSuccessor(sinkMBB);
16755 // Create the conditional branch instruction.
16757 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16758 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16761 // %FalseValue = ...
16762 // # fallthrough to sinkMBB
16763 copy0MBB->addSuccessor(sinkMBB);
16766 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16768 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16769 TII->get(X86::PHI), MI->getOperand(0).getReg())
16770 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16771 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16773 MI->eraseFromParent(); // The pseudo instruction is gone now.
16777 MachineBasicBlock *
16778 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16779 bool Is64Bit) const {
16780 MachineFunction *MF = BB->getParent();
16781 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16782 DebugLoc DL = MI->getDebugLoc();
16783 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16785 assert(MF->shouldSplitStack());
16787 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16788 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16791 // ... [Till the alloca]
16792 // If stacklet is not large enough, jump to mallocMBB
16795 // Allocate by subtracting from RSP
16796 // Jump to continueMBB
16799 // Allocate by call to runtime
16803 // [rest of original BB]
16806 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16807 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16808 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16810 MachineRegisterInfo &MRI = MF->getRegInfo();
16811 const TargetRegisterClass *AddrRegClass =
16812 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16814 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16815 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16816 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16817 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16818 sizeVReg = MI->getOperand(1).getReg(),
16819 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16821 MachineFunction::iterator MBBIter = BB;
16824 MF->insert(MBBIter, bumpMBB);
16825 MF->insert(MBBIter, mallocMBB);
16826 MF->insert(MBBIter, continueMBB);
16828 continueMBB->splice(continueMBB->begin(), BB,
16829 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16830 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16832 // Add code to the main basic block to check if the stack limit has been hit,
16833 // and if so, jump to mallocMBB otherwise to bumpMBB.
16834 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16835 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16836 .addReg(tmpSPVReg).addReg(sizeVReg);
16837 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16838 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16839 .addReg(SPLimitVReg);
16840 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16842 // bumpMBB simply decreases the stack pointer, since we know the current
16843 // stacklet has enough space.
16844 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16845 .addReg(SPLimitVReg);
16846 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16847 .addReg(SPLimitVReg);
16848 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16850 // Calls into a routine in libgcc to allocate more space from the heap.
16851 const uint32_t *RegMask =
16852 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16854 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16856 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16857 .addExternalSymbol("__morestack_allocate_stack_space")
16858 .addRegMask(RegMask)
16859 .addReg(X86::RDI, RegState::Implicit)
16860 .addReg(X86::RAX, RegState::ImplicitDefine);
16862 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16864 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16865 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16866 .addExternalSymbol("__morestack_allocate_stack_space")
16867 .addRegMask(RegMask)
16868 .addReg(X86::EAX, RegState::ImplicitDefine);
16872 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16875 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16876 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16877 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16879 // Set up the CFG correctly.
16880 BB->addSuccessor(bumpMBB);
16881 BB->addSuccessor(mallocMBB);
16882 mallocMBB->addSuccessor(continueMBB);
16883 bumpMBB->addSuccessor(continueMBB);
16885 // Take care of the PHI nodes.
16886 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16887 MI->getOperand(0).getReg())
16888 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16889 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16891 // Delete the original pseudo instruction.
16892 MI->eraseFromParent();
16895 return continueMBB;
16898 MachineBasicBlock *
16899 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16900 MachineBasicBlock *BB) const {
16901 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16902 DebugLoc DL = MI->getDebugLoc();
16904 assert(!Subtarget->isTargetMacho());
16906 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16907 // non-trivial part is impdef of ESP.
16909 if (Subtarget->isTargetWin64()) {
16910 if (Subtarget->isTargetCygMing()) {
16911 // ___chkstk(Mingw64):
16912 // Clobbers R10, R11, RAX and EFLAGS.
16914 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16915 .addExternalSymbol("___chkstk")
16916 .addReg(X86::RAX, RegState::Implicit)
16917 .addReg(X86::RSP, RegState::Implicit)
16918 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16919 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16920 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16922 // __chkstk(MSVCRT): does not update stack pointer.
16923 // Clobbers R10, R11 and EFLAGS.
16924 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16925 .addExternalSymbol("__chkstk")
16926 .addReg(X86::RAX, RegState::Implicit)
16927 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16928 // RAX has the offset to be subtracted from RSP.
16929 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16934 const char *StackProbeSymbol =
16935 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16937 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16938 .addExternalSymbol(StackProbeSymbol)
16939 .addReg(X86::EAX, RegState::Implicit)
16940 .addReg(X86::ESP, RegState::Implicit)
16941 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16942 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16943 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16946 MI->eraseFromParent(); // The pseudo instruction is gone now.
16950 MachineBasicBlock *
16951 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16952 MachineBasicBlock *BB) const {
16953 // This is pretty easy. We're taking the value that we received from
16954 // our load from the relocation, sticking it in either RDI (x86-64)
16955 // or EAX and doing an indirect call. The return value will then
16956 // be in the normal return register.
16957 MachineFunction *F = BB->getParent();
16958 const X86InstrInfo *TII
16959 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
16960 DebugLoc DL = MI->getDebugLoc();
16962 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16963 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16965 // Get a register mask for the lowered call.
16966 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16967 // proper register mask.
16968 const uint32_t *RegMask =
16969 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16970 if (Subtarget->is64Bit()) {
16971 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16972 TII->get(X86::MOV64rm), X86::RDI)
16974 .addImm(0).addReg(0)
16975 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16976 MI->getOperand(3).getTargetFlags())
16978 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16979 addDirectMem(MIB, X86::RDI);
16980 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16981 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
16982 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16983 TII->get(X86::MOV32rm), X86::EAX)
16985 .addImm(0).addReg(0)
16986 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16987 MI->getOperand(3).getTargetFlags())
16989 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16990 addDirectMem(MIB, X86::EAX);
16991 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16993 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16994 TII->get(X86::MOV32rm), X86::EAX)
16995 .addReg(TII->getGlobalBaseReg(F))
16996 .addImm(0).addReg(0)
16997 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16998 MI->getOperand(3).getTargetFlags())
17000 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17001 addDirectMem(MIB, X86::EAX);
17002 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17005 MI->eraseFromParent(); // The pseudo instruction is gone now.
17009 MachineBasicBlock *
17010 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17011 MachineBasicBlock *MBB) const {
17012 DebugLoc DL = MI->getDebugLoc();
17013 MachineFunction *MF = MBB->getParent();
17014 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17015 MachineRegisterInfo &MRI = MF->getRegInfo();
17017 const BasicBlock *BB = MBB->getBasicBlock();
17018 MachineFunction::iterator I = MBB;
17021 // Memory Reference
17022 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17023 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17026 unsigned MemOpndSlot = 0;
17028 unsigned CurOp = 0;
17030 DstReg = MI->getOperand(CurOp++).getReg();
17031 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17032 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17033 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17034 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17036 MemOpndSlot = CurOp;
17038 MVT PVT = getPointerTy();
17039 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17040 "Invalid Pointer Size!");
17042 // For v = setjmp(buf), we generate
17045 // buf[LabelOffset] = restoreMBB
17046 // SjLjSetup restoreMBB
17052 // v = phi(main, restore)
17057 MachineBasicBlock *thisMBB = MBB;
17058 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17059 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17060 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17061 MF->insert(I, mainMBB);
17062 MF->insert(I, sinkMBB);
17063 MF->push_back(restoreMBB);
17065 MachineInstrBuilder MIB;
17067 // Transfer the remainder of BB and its successor edges to sinkMBB.
17068 sinkMBB->splice(sinkMBB->begin(), MBB,
17069 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17070 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17073 unsigned PtrStoreOpc = 0;
17074 unsigned LabelReg = 0;
17075 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17076 Reloc::Model RM = MF->getTarget().getRelocationModel();
17077 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17078 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17080 // Prepare IP either in reg or imm.
17081 if (!UseImmLabel) {
17082 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17083 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17084 LabelReg = MRI.createVirtualRegister(PtrRC);
17085 if (Subtarget->is64Bit()) {
17086 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17090 .addMBB(restoreMBB)
17093 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17094 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17095 .addReg(XII->getGlobalBaseReg(MF))
17098 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17102 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17104 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17105 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17106 if (i == X86::AddrDisp)
17107 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17109 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17112 MIB.addReg(LabelReg);
17114 MIB.addMBB(restoreMBB);
17115 MIB.setMemRefs(MMOBegin, MMOEnd);
17117 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17118 .addMBB(restoreMBB);
17120 const X86RegisterInfo *RegInfo =
17121 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17122 MIB.addRegMask(RegInfo->getNoPreservedMask());
17123 thisMBB->addSuccessor(mainMBB);
17124 thisMBB->addSuccessor(restoreMBB);
17128 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17129 mainMBB->addSuccessor(sinkMBB);
17132 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17133 TII->get(X86::PHI), DstReg)
17134 .addReg(mainDstReg).addMBB(mainMBB)
17135 .addReg(restoreDstReg).addMBB(restoreMBB);
17138 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17139 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17140 restoreMBB->addSuccessor(sinkMBB);
17142 MI->eraseFromParent();
17146 MachineBasicBlock *
17147 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17148 MachineBasicBlock *MBB) const {
17149 DebugLoc DL = MI->getDebugLoc();
17150 MachineFunction *MF = MBB->getParent();
17151 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17152 MachineRegisterInfo &MRI = MF->getRegInfo();
17154 // Memory Reference
17155 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17156 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17158 MVT PVT = getPointerTy();
17159 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17160 "Invalid Pointer Size!");
17162 const TargetRegisterClass *RC =
17163 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17164 unsigned Tmp = MRI.createVirtualRegister(RC);
17165 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17166 const X86RegisterInfo *RegInfo =
17167 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17168 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17169 unsigned SP = RegInfo->getStackRegister();
17171 MachineInstrBuilder MIB;
17173 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17174 const int64_t SPOffset = 2 * PVT.getStoreSize();
17176 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17177 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17180 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17181 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17182 MIB.addOperand(MI->getOperand(i));
17183 MIB.setMemRefs(MMOBegin, MMOEnd);
17185 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17186 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17187 if (i == X86::AddrDisp)
17188 MIB.addDisp(MI->getOperand(i), LabelOffset);
17190 MIB.addOperand(MI->getOperand(i));
17192 MIB.setMemRefs(MMOBegin, MMOEnd);
17194 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17195 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17196 if (i == X86::AddrDisp)
17197 MIB.addDisp(MI->getOperand(i), SPOffset);
17199 MIB.addOperand(MI->getOperand(i));
17201 MIB.setMemRefs(MMOBegin, MMOEnd);
17203 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17205 MI->eraseFromParent();
17209 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17210 // accumulator loops. Writing back to the accumulator allows the coalescer
17211 // to remove extra copies in the loop.
17212 MachineBasicBlock *
17213 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17214 MachineBasicBlock *MBB) const {
17215 MachineOperand &AddendOp = MI->getOperand(3);
17217 // Bail out early if the addend isn't a register - we can't switch these.
17218 if (!AddendOp.isReg())
17221 MachineFunction &MF = *MBB->getParent();
17222 MachineRegisterInfo &MRI = MF.getRegInfo();
17224 // Check whether the addend is defined by a PHI:
17225 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17226 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17227 if (!AddendDef.isPHI())
17230 // Look for the following pattern:
17232 // %addend = phi [%entry, 0], [%loop, %result]
17234 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17238 // %addend = phi [%entry, 0], [%loop, %result]
17240 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17242 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17243 assert(AddendDef.getOperand(i).isReg());
17244 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17245 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17246 if (&PHISrcInst == MI) {
17247 // Found a matching instruction.
17248 unsigned NewFMAOpc = 0;
17249 switch (MI->getOpcode()) {
17250 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17251 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17252 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17253 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17254 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17255 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17256 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17257 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17258 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17259 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17260 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17261 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17262 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17263 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17264 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17265 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17266 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17267 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17268 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17269 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17270 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17271 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17272 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17273 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17274 default: llvm_unreachable("Unrecognized FMA variant.");
17277 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17278 MachineInstrBuilder MIB =
17279 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17280 .addOperand(MI->getOperand(0))
17281 .addOperand(MI->getOperand(3))
17282 .addOperand(MI->getOperand(2))
17283 .addOperand(MI->getOperand(1));
17284 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17285 MI->eraseFromParent();
17292 MachineBasicBlock *
17293 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17294 MachineBasicBlock *BB) const {
17295 switch (MI->getOpcode()) {
17296 default: llvm_unreachable("Unexpected instr type to insert");
17297 case X86::TAILJMPd64:
17298 case X86::TAILJMPr64:
17299 case X86::TAILJMPm64:
17300 llvm_unreachable("TAILJMP64 would not be touched here.");
17301 case X86::TCRETURNdi64:
17302 case X86::TCRETURNri64:
17303 case X86::TCRETURNmi64:
17305 case X86::WIN_ALLOCA:
17306 return EmitLoweredWinAlloca(MI, BB);
17307 case X86::SEG_ALLOCA_32:
17308 return EmitLoweredSegAlloca(MI, BB, false);
17309 case X86::SEG_ALLOCA_64:
17310 return EmitLoweredSegAlloca(MI, BB, true);
17311 case X86::TLSCall_32:
17312 case X86::TLSCall_64:
17313 return EmitLoweredTLSCall(MI, BB);
17314 case X86::CMOV_GR8:
17315 case X86::CMOV_FR32:
17316 case X86::CMOV_FR64:
17317 case X86::CMOV_V4F32:
17318 case X86::CMOV_V2F64:
17319 case X86::CMOV_V2I64:
17320 case X86::CMOV_V8F32:
17321 case X86::CMOV_V4F64:
17322 case X86::CMOV_V4I64:
17323 case X86::CMOV_V16F32:
17324 case X86::CMOV_V8F64:
17325 case X86::CMOV_V8I64:
17326 case X86::CMOV_GR16:
17327 case X86::CMOV_GR32:
17328 case X86::CMOV_RFP32:
17329 case X86::CMOV_RFP64:
17330 case X86::CMOV_RFP80:
17331 return EmitLoweredSelect(MI, BB);
17333 case X86::FP32_TO_INT16_IN_MEM:
17334 case X86::FP32_TO_INT32_IN_MEM:
17335 case X86::FP32_TO_INT64_IN_MEM:
17336 case X86::FP64_TO_INT16_IN_MEM:
17337 case X86::FP64_TO_INT32_IN_MEM:
17338 case X86::FP64_TO_INT64_IN_MEM:
17339 case X86::FP80_TO_INT16_IN_MEM:
17340 case X86::FP80_TO_INT32_IN_MEM:
17341 case X86::FP80_TO_INT64_IN_MEM: {
17342 MachineFunction *F = BB->getParent();
17343 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17344 DebugLoc DL = MI->getDebugLoc();
17346 // Change the floating point control register to use "round towards zero"
17347 // mode when truncating to an integer value.
17348 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17349 addFrameReference(BuildMI(*BB, MI, DL,
17350 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17352 // Load the old value of the high byte of the control word...
17354 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17355 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17358 // Set the high part to be round to zero...
17359 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17362 // Reload the modified control word now...
17363 addFrameReference(BuildMI(*BB, MI, DL,
17364 TII->get(X86::FLDCW16m)), CWFrameIdx);
17366 // Restore the memory image of control word to original value
17367 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17370 // Get the X86 opcode to use.
17372 switch (MI->getOpcode()) {
17373 default: llvm_unreachable("illegal opcode!");
17374 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17375 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17376 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17377 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17378 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17379 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17380 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17381 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17382 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17386 MachineOperand &Op = MI->getOperand(0);
17388 AM.BaseType = X86AddressMode::RegBase;
17389 AM.Base.Reg = Op.getReg();
17391 AM.BaseType = X86AddressMode::FrameIndexBase;
17392 AM.Base.FrameIndex = Op.getIndex();
17394 Op = MI->getOperand(1);
17396 AM.Scale = Op.getImm();
17397 Op = MI->getOperand(2);
17399 AM.IndexReg = Op.getImm();
17400 Op = MI->getOperand(3);
17401 if (Op.isGlobal()) {
17402 AM.GV = Op.getGlobal();
17404 AM.Disp = Op.getImm();
17406 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17407 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17409 // Reload the original control word now.
17410 addFrameReference(BuildMI(*BB, MI, DL,
17411 TII->get(X86::FLDCW16m)), CWFrameIdx);
17413 MI->eraseFromParent(); // The pseudo instruction is gone now.
17416 // String/text processing lowering.
17417 case X86::PCMPISTRM128REG:
17418 case X86::VPCMPISTRM128REG:
17419 case X86::PCMPISTRM128MEM:
17420 case X86::VPCMPISTRM128MEM:
17421 case X86::PCMPESTRM128REG:
17422 case X86::VPCMPESTRM128REG:
17423 case X86::PCMPESTRM128MEM:
17424 case X86::VPCMPESTRM128MEM:
17425 assert(Subtarget->hasSSE42() &&
17426 "Target must have SSE4.2 or AVX features enabled");
17427 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17429 // String/text processing lowering.
17430 case X86::PCMPISTRIREG:
17431 case X86::VPCMPISTRIREG:
17432 case X86::PCMPISTRIMEM:
17433 case X86::VPCMPISTRIMEM:
17434 case X86::PCMPESTRIREG:
17435 case X86::VPCMPESTRIREG:
17436 case X86::PCMPESTRIMEM:
17437 case X86::VPCMPESTRIMEM:
17438 assert(Subtarget->hasSSE42() &&
17439 "Target must have SSE4.2 or AVX features enabled");
17440 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17442 // Thread synchronization.
17444 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17448 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17450 // Atomic Lowering.
17451 case X86::ATOMAND8:
17452 case X86::ATOMAND16:
17453 case X86::ATOMAND32:
17454 case X86::ATOMAND64:
17457 case X86::ATOMOR16:
17458 case X86::ATOMOR32:
17459 case X86::ATOMOR64:
17461 case X86::ATOMXOR16:
17462 case X86::ATOMXOR8:
17463 case X86::ATOMXOR32:
17464 case X86::ATOMXOR64:
17466 case X86::ATOMNAND8:
17467 case X86::ATOMNAND16:
17468 case X86::ATOMNAND32:
17469 case X86::ATOMNAND64:
17471 case X86::ATOMMAX8:
17472 case X86::ATOMMAX16:
17473 case X86::ATOMMAX32:
17474 case X86::ATOMMAX64:
17476 case X86::ATOMMIN8:
17477 case X86::ATOMMIN16:
17478 case X86::ATOMMIN32:
17479 case X86::ATOMMIN64:
17481 case X86::ATOMUMAX8:
17482 case X86::ATOMUMAX16:
17483 case X86::ATOMUMAX32:
17484 case X86::ATOMUMAX64:
17486 case X86::ATOMUMIN8:
17487 case X86::ATOMUMIN16:
17488 case X86::ATOMUMIN32:
17489 case X86::ATOMUMIN64:
17490 return EmitAtomicLoadArith(MI, BB);
17492 // This group does 64-bit operations on a 32-bit host.
17493 case X86::ATOMAND6432:
17494 case X86::ATOMOR6432:
17495 case X86::ATOMXOR6432:
17496 case X86::ATOMNAND6432:
17497 case X86::ATOMADD6432:
17498 case X86::ATOMSUB6432:
17499 case X86::ATOMMAX6432:
17500 case X86::ATOMMIN6432:
17501 case X86::ATOMUMAX6432:
17502 case X86::ATOMUMIN6432:
17503 case X86::ATOMSWAP6432:
17504 return EmitAtomicLoadArith6432(MI, BB);
17506 case X86::VASTART_SAVE_XMM_REGS:
17507 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17509 case X86::VAARG_64:
17510 return EmitVAARG64WithCustomInserter(MI, BB);
17512 case X86::EH_SjLj_SetJmp32:
17513 case X86::EH_SjLj_SetJmp64:
17514 return emitEHSjLjSetJmp(MI, BB);
17516 case X86::EH_SjLj_LongJmp32:
17517 case X86::EH_SjLj_LongJmp64:
17518 return emitEHSjLjLongJmp(MI, BB);
17520 case TargetOpcode::STACKMAP:
17521 case TargetOpcode::PATCHPOINT:
17522 return emitPatchPoint(MI, BB);
17524 case X86::VFMADDPDr213r:
17525 case X86::VFMADDPSr213r:
17526 case X86::VFMADDSDr213r:
17527 case X86::VFMADDSSr213r:
17528 case X86::VFMSUBPDr213r:
17529 case X86::VFMSUBPSr213r:
17530 case X86::VFMSUBSDr213r:
17531 case X86::VFMSUBSSr213r:
17532 case X86::VFNMADDPDr213r:
17533 case X86::VFNMADDPSr213r:
17534 case X86::VFNMADDSDr213r:
17535 case X86::VFNMADDSSr213r:
17536 case X86::VFNMSUBPDr213r:
17537 case X86::VFNMSUBPSr213r:
17538 case X86::VFNMSUBSDr213r:
17539 case X86::VFNMSUBSSr213r:
17540 case X86::VFMADDPDr213rY:
17541 case X86::VFMADDPSr213rY:
17542 case X86::VFMSUBPDr213rY:
17543 case X86::VFMSUBPSr213rY:
17544 case X86::VFNMADDPDr213rY:
17545 case X86::VFNMADDPSr213rY:
17546 case X86::VFNMSUBPDr213rY:
17547 case X86::VFNMSUBPSr213rY:
17548 return emitFMA3Instr(MI, BB);
17552 //===----------------------------------------------------------------------===//
17553 // X86 Optimization Hooks
17554 //===----------------------------------------------------------------------===//
17556 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17559 const SelectionDAG &DAG,
17560 unsigned Depth) const {
17561 unsigned BitWidth = KnownZero.getBitWidth();
17562 unsigned Opc = Op.getOpcode();
17563 assert((Opc >= ISD::BUILTIN_OP_END ||
17564 Opc == ISD::INTRINSIC_WO_CHAIN ||
17565 Opc == ISD::INTRINSIC_W_CHAIN ||
17566 Opc == ISD::INTRINSIC_VOID) &&
17567 "Should use MaskedValueIsZero if you don't know whether Op"
17568 " is a target node!");
17570 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17584 // These nodes' second result is a boolean.
17585 if (Op.getResNo() == 0)
17588 case X86ISD::SETCC:
17589 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17591 case ISD::INTRINSIC_WO_CHAIN: {
17592 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17593 unsigned NumLoBits = 0;
17596 case Intrinsic::x86_sse_movmsk_ps:
17597 case Intrinsic::x86_avx_movmsk_ps_256:
17598 case Intrinsic::x86_sse2_movmsk_pd:
17599 case Intrinsic::x86_avx_movmsk_pd_256:
17600 case Intrinsic::x86_mmx_pmovmskb:
17601 case Intrinsic::x86_sse2_pmovmskb_128:
17602 case Intrinsic::x86_avx2_pmovmskb: {
17603 // High bits of movmskp{s|d}, pmovmskb are known zero.
17605 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17606 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17607 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17608 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17609 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17610 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17611 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17612 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17614 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17623 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17625 const SelectionDAG &,
17626 unsigned Depth) const {
17627 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17628 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17629 return Op.getValueType().getScalarType().getSizeInBits();
17635 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17636 /// node is a GlobalAddress + offset.
17637 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17638 const GlobalValue* &GA,
17639 int64_t &Offset) const {
17640 if (N->getOpcode() == X86ISD::Wrapper) {
17641 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17642 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17643 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17647 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17650 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17651 /// same as extracting the high 128-bit part of 256-bit vector and then
17652 /// inserting the result into the low part of a new 256-bit vector
17653 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17654 EVT VT = SVOp->getValueType(0);
17655 unsigned NumElems = VT.getVectorNumElements();
17657 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17658 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17659 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17660 SVOp->getMaskElt(j) >= 0)
17666 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17667 /// same as extracting the low 128-bit part of 256-bit vector and then
17668 /// inserting the result into the high part of a new 256-bit vector
17669 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17670 EVT VT = SVOp->getValueType(0);
17671 unsigned NumElems = VT.getVectorNumElements();
17673 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17674 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17675 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17676 SVOp->getMaskElt(j) >= 0)
17682 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17683 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17684 TargetLowering::DAGCombinerInfo &DCI,
17685 const X86Subtarget* Subtarget) {
17687 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17688 SDValue V1 = SVOp->getOperand(0);
17689 SDValue V2 = SVOp->getOperand(1);
17690 EVT VT = SVOp->getValueType(0);
17691 unsigned NumElems = VT.getVectorNumElements();
17693 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17694 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17698 // V UNDEF BUILD_VECTOR UNDEF
17700 // CONCAT_VECTOR CONCAT_VECTOR
17703 // RESULT: V + zero extended
17705 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17706 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17707 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17710 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17713 // To match the shuffle mask, the first half of the mask should
17714 // be exactly the first vector, and all the rest a splat with the
17715 // first element of the second one.
17716 for (unsigned i = 0; i != NumElems/2; ++i)
17717 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17718 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17721 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17722 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17723 if (Ld->hasNUsesOfValue(1, 0)) {
17724 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17725 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17727 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17729 Ld->getPointerInfo(),
17730 Ld->getAlignment(),
17731 false/*isVolatile*/, true/*ReadMem*/,
17732 false/*WriteMem*/);
17734 // Make sure the newly-created LOAD is in the same position as Ld in
17735 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17736 // and update uses of Ld's output chain to use the TokenFactor.
17737 if (Ld->hasAnyUseOfValue(1)) {
17738 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17739 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17740 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17741 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17742 SDValue(ResNode.getNode(), 1));
17745 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17749 // Emit a zeroed vector and insert the desired subvector on its
17751 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17752 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17753 return DCI.CombineTo(N, InsV);
17756 //===--------------------------------------------------------------------===//
17757 // Combine some shuffles into subvector extracts and inserts:
17760 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17761 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17762 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17763 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17764 return DCI.CombineTo(N, InsV);
17767 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17768 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17769 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17770 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17771 return DCI.CombineTo(N, InsV);
17777 /// PerformShuffleCombine - Performs several different shuffle combines.
17778 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17779 TargetLowering::DAGCombinerInfo &DCI,
17780 const X86Subtarget *Subtarget) {
17782 SDValue N0 = N->getOperand(0);
17783 SDValue N1 = N->getOperand(1);
17784 EVT VT = N->getValueType(0);
17786 // Don't create instructions with illegal types after legalize types has run.
17787 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17788 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17791 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17792 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17793 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17794 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17796 // During Type Legalization, when promoting illegal vector types,
17797 // the backend might introduce new shuffle dag nodes and bitcasts.
17799 // This code performs the following transformation:
17800 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17801 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17803 // We do this only if both the bitcast and the BINOP dag nodes have
17804 // one use. Also, perform this transformation only if the new binary
17805 // operation is legal. This is to avoid introducing dag nodes that
17806 // potentially need to be further expanded (or custom lowered) into a
17807 // less optimal sequence of dag nodes.
17808 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17809 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17810 N0.getOpcode() == ISD::BITCAST) {
17811 SDValue BC0 = N0.getOperand(0);
17812 EVT SVT = BC0.getValueType();
17813 unsigned Opcode = BC0.getOpcode();
17814 unsigned NumElts = VT.getVectorNumElements();
17816 if (BC0.hasOneUse() && SVT.isVector() &&
17817 SVT.getVectorNumElements() * 2 == NumElts &&
17818 TLI.isOperationLegal(Opcode, VT)) {
17819 bool CanFold = false;
17831 unsigned SVTNumElts = SVT.getVectorNumElements();
17832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17833 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17834 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17835 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17836 CanFold = SVOp->getMaskElt(i) < 0;
17839 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17840 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17841 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17842 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17847 // Only handle 128 wide vector from here on.
17848 if (!VT.is128BitVector())
17851 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17852 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17853 // consecutive, non-overlapping, and in the right order.
17854 SmallVector<SDValue, 16> Elts;
17855 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17856 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17858 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17861 /// PerformTruncateCombine - Converts truncate operation to
17862 /// a sequence of vector shuffle operations.
17863 /// It is possible when we truncate 256-bit vector to 128-bit vector
17864 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17865 TargetLowering::DAGCombinerInfo &DCI,
17866 const X86Subtarget *Subtarget) {
17870 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17871 /// specific shuffle of a load can be folded into a single element load.
17872 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17873 /// shuffles have been customed lowered so we need to handle those here.
17874 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17875 TargetLowering::DAGCombinerInfo &DCI) {
17876 if (DCI.isBeforeLegalizeOps())
17879 SDValue InVec = N->getOperand(0);
17880 SDValue EltNo = N->getOperand(1);
17882 if (!isa<ConstantSDNode>(EltNo))
17885 EVT VT = InVec.getValueType();
17887 bool HasShuffleIntoBitcast = false;
17888 if (InVec.getOpcode() == ISD::BITCAST) {
17889 // Don't duplicate a load with other uses.
17890 if (!InVec.hasOneUse())
17892 EVT BCVT = InVec.getOperand(0).getValueType();
17893 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17895 InVec = InVec.getOperand(0);
17896 HasShuffleIntoBitcast = true;
17899 if (!isTargetShuffle(InVec.getOpcode()))
17902 // Don't duplicate a load with other uses.
17903 if (!InVec.hasOneUse())
17906 SmallVector<int, 16> ShuffleMask;
17908 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17912 // Select the input vector, guarding against out of range extract vector.
17913 unsigned NumElems = VT.getVectorNumElements();
17914 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17915 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17916 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17917 : InVec.getOperand(1);
17919 // If inputs to shuffle are the same for both ops, then allow 2 uses
17920 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17922 if (LdNode.getOpcode() == ISD::BITCAST) {
17923 // Don't duplicate a load with other uses.
17924 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17927 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17928 LdNode = LdNode.getOperand(0);
17931 if (!ISD::isNormalLoad(LdNode.getNode()))
17934 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17936 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17939 if (HasShuffleIntoBitcast) {
17940 // If there's a bitcast before the shuffle, check if the load type and
17941 // alignment is valid.
17942 unsigned Align = LN0->getAlignment();
17943 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17944 unsigned NewAlign = TLI.getDataLayout()->
17945 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17947 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17951 // All checks match so transform back to vector_shuffle so that DAG combiner
17952 // can finish the job
17955 // Create shuffle node taking into account the case that its a unary shuffle
17956 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17957 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17958 InVec.getOperand(0), Shuffle,
17960 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17961 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17965 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17966 /// generation and convert it from being a bunch of shuffles and extracts
17967 /// to a simple store and scalar loads to extract the elements.
17968 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17969 TargetLowering::DAGCombinerInfo &DCI) {
17970 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17971 if (NewOp.getNode())
17974 SDValue InputVector = N->getOperand(0);
17976 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17977 // from mmx to v2i32 has a single usage.
17978 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17979 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17980 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17981 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17982 N->getValueType(0),
17983 InputVector.getNode()->getOperand(0));
17985 // Only operate on vectors of 4 elements, where the alternative shuffling
17986 // gets to be more expensive.
17987 if (InputVector.getValueType() != MVT::v4i32)
17990 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17991 // single use which is a sign-extend or zero-extend, and all elements are
17993 SmallVector<SDNode *, 4> Uses;
17994 unsigned ExtractedElements = 0;
17995 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17996 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17997 if (UI.getUse().getResNo() != InputVector.getResNo())
18000 SDNode *Extract = *UI;
18001 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18004 if (Extract->getValueType(0) != MVT::i32)
18006 if (!Extract->hasOneUse())
18008 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18009 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18011 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18014 // Record which element was extracted.
18015 ExtractedElements |=
18016 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18018 Uses.push_back(Extract);
18021 // If not all the elements were used, this may not be worthwhile.
18022 if (ExtractedElements != 15)
18025 // Ok, we've now decided to do the transformation.
18026 SDLoc dl(InputVector);
18028 // Store the value to a temporary stack slot.
18029 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18030 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18031 MachinePointerInfo(), false, false, 0);
18033 // Replace each use (extract) with a load of the appropriate element.
18034 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18035 UE = Uses.end(); UI != UE; ++UI) {
18036 SDNode *Extract = *UI;
18038 // cOMpute the element's address.
18039 SDValue Idx = Extract->getOperand(1);
18041 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18042 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18043 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18044 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18046 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18047 StackPtr, OffsetVal);
18049 // Load the scalar.
18050 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18051 ScalarAddr, MachinePointerInfo(),
18052 false, false, false, 0);
18054 // Replace the exact with the load.
18055 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18058 // The replacement was made in place; don't return anything.
18062 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18063 static std::pair<unsigned, bool>
18064 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18065 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18066 if (!VT.isVector())
18067 return std::make_pair(0, false);
18069 bool NeedSplit = false;
18070 switch (VT.getSimpleVT().SimpleTy) {
18071 default: return std::make_pair(0, false);
18075 if (!Subtarget->hasAVX2())
18077 if (!Subtarget->hasAVX())
18078 return std::make_pair(0, false);
18083 if (!Subtarget->hasSSE2())
18084 return std::make_pair(0, false);
18087 // SSE2 has only a small subset of the operations.
18088 bool hasUnsigned = Subtarget->hasSSE41() ||
18089 (Subtarget->hasSSE2() && VT == MVT::v16i8);
18090 bool hasSigned = Subtarget->hasSSE41() ||
18091 (Subtarget->hasSSE2() && VT == MVT::v8i16);
18093 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18096 // Check for x CC y ? x : y.
18097 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18098 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18103 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18106 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18109 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18112 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18114 // Check for x CC y ? y : x -- a min/max with reversed arms.
18115 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18116 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18121 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18124 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18127 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18130 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18134 return std::make_pair(Opc, NeedSplit);
18138 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18139 const X86Subtarget *Subtarget) {
18141 SDValue Cond = N->getOperand(0);
18142 SDValue LHS = N->getOperand(1);
18143 SDValue RHS = N->getOperand(2);
18145 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18146 SDValue CondSrc = Cond->getOperand(0);
18147 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18148 Cond = CondSrc->getOperand(0);
18151 MVT VT = N->getSimpleValueType(0);
18152 MVT EltVT = VT.getVectorElementType();
18153 unsigned NumElems = VT.getVectorNumElements();
18154 // There is no blend with immediate in AVX-512.
18155 if (VT.is512BitVector())
18158 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18160 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18163 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18166 unsigned MaskValue = 0;
18167 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18170 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18171 for (unsigned i = 0; i < NumElems; ++i) {
18172 // Be sure we emit undef where we can.
18173 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18174 ShuffleMask[i] = -1;
18176 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18179 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18182 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18184 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18185 TargetLowering::DAGCombinerInfo &DCI,
18186 const X86Subtarget *Subtarget) {
18188 SDValue Cond = N->getOperand(0);
18189 // Get the LHS/RHS of the select.
18190 SDValue LHS = N->getOperand(1);
18191 SDValue RHS = N->getOperand(2);
18192 EVT VT = LHS.getValueType();
18193 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18195 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18196 // instructions match the semantics of the common C idiom x<y?x:y but not
18197 // x<=y?x:y, because of how they handle negative zero (which can be
18198 // ignored in unsafe-math mode).
18199 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18200 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18201 (Subtarget->hasSSE2() ||
18202 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18203 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18205 unsigned Opcode = 0;
18206 // Check for x CC y ? x : y.
18207 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18208 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18212 // Converting this to a min would handle NaNs incorrectly, and swapping
18213 // the operands would cause it to handle comparisons between positive
18214 // and negative zero incorrectly.
18215 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18216 if (!DAG.getTarget().Options.UnsafeFPMath &&
18217 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18219 std::swap(LHS, RHS);
18221 Opcode = X86ISD::FMIN;
18224 // Converting this to a min would handle comparisons between positive
18225 // and negative zero incorrectly.
18226 if (!DAG.getTarget().Options.UnsafeFPMath &&
18227 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18229 Opcode = X86ISD::FMIN;
18232 // Converting this to a min would handle both negative zeros and NaNs
18233 // incorrectly, but we can swap the operands to fix both.
18234 std::swap(LHS, RHS);
18238 Opcode = X86ISD::FMIN;
18242 // Converting this to a max would handle comparisons between positive
18243 // and negative zero incorrectly.
18244 if (!DAG.getTarget().Options.UnsafeFPMath &&
18245 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18247 Opcode = X86ISD::FMAX;
18250 // Converting this to a max would handle NaNs incorrectly, and swapping
18251 // the operands would cause it to handle comparisons between positive
18252 // and negative zero incorrectly.
18253 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18254 if (!DAG.getTarget().Options.UnsafeFPMath &&
18255 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18257 std::swap(LHS, RHS);
18259 Opcode = X86ISD::FMAX;
18262 // Converting this to a max would handle both negative zeros and NaNs
18263 // incorrectly, but we can swap the operands to fix both.
18264 std::swap(LHS, RHS);
18268 Opcode = X86ISD::FMAX;
18271 // Check for x CC y ? y : x -- a min/max with reversed arms.
18272 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18273 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18277 // Converting this to a min would handle comparisons between positive
18278 // and negative zero incorrectly, and swapping the operands would
18279 // cause it to handle NaNs incorrectly.
18280 if (!DAG.getTarget().Options.UnsafeFPMath &&
18281 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18282 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18284 std::swap(LHS, RHS);
18286 Opcode = X86ISD::FMIN;
18289 // Converting this to a min would handle NaNs incorrectly.
18290 if (!DAG.getTarget().Options.UnsafeFPMath &&
18291 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18293 Opcode = X86ISD::FMIN;
18296 // Converting this to a min would handle both negative zeros and NaNs
18297 // incorrectly, but we can swap the operands to fix both.
18298 std::swap(LHS, RHS);
18302 Opcode = X86ISD::FMIN;
18306 // Converting this to a max would handle NaNs incorrectly.
18307 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18309 Opcode = X86ISD::FMAX;
18312 // Converting this to a max would handle comparisons between positive
18313 // and negative zero incorrectly, and swapping the operands would
18314 // cause it to handle NaNs incorrectly.
18315 if (!DAG.getTarget().Options.UnsafeFPMath &&
18316 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18317 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18319 std::swap(LHS, RHS);
18321 Opcode = X86ISD::FMAX;
18324 // Converting this to a max would handle both negative zeros and NaNs
18325 // incorrectly, but we can swap the operands to fix both.
18326 std::swap(LHS, RHS);
18330 Opcode = X86ISD::FMAX;
18336 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18339 EVT CondVT = Cond.getValueType();
18340 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18341 CondVT.getVectorElementType() == MVT::i1) {
18342 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18343 // lowering on AVX-512. In this case we convert it to
18344 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18345 // The same situation for all 128 and 256-bit vectors of i8 and i16
18346 EVT OpVT = LHS.getValueType();
18347 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18348 (OpVT.getVectorElementType() == MVT::i8 ||
18349 OpVT.getVectorElementType() == MVT::i16)) {
18350 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18351 DCI.AddToWorklist(Cond.getNode());
18352 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18355 // If this is a select between two integer constants, try to do some
18357 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18358 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18359 // Don't do this for crazy integer types.
18360 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18361 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18362 // so that TrueC (the true value) is larger than FalseC.
18363 bool NeedsCondInvert = false;
18365 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18366 // Efficiently invertible.
18367 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18368 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18369 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18370 NeedsCondInvert = true;
18371 std::swap(TrueC, FalseC);
18374 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18375 if (FalseC->getAPIntValue() == 0 &&
18376 TrueC->getAPIntValue().isPowerOf2()) {
18377 if (NeedsCondInvert) // Invert the condition if needed.
18378 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18379 DAG.getConstant(1, Cond.getValueType()));
18381 // Zero extend the condition if needed.
18382 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18384 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18385 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18386 DAG.getConstant(ShAmt, MVT::i8));
18389 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18390 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18391 if (NeedsCondInvert) // Invert the condition if needed.
18392 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18393 DAG.getConstant(1, Cond.getValueType()));
18395 // Zero extend the condition if needed.
18396 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18397 FalseC->getValueType(0), Cond);
18398 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18399 SDValue(FalseC, 0));
18402 // Optimize cases that will turn into an LEA instruction. This requires
18403 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18404 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18405 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18406 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18408 bool isFastMultiplier = false;
18410 switch ((unsigned char)Diff) {
18412 case 1: // result = add base, cond
18413 case 2: // result = lea base( , cond*2)
18414 case 3: // result = lea base(cond, cond*2)
18415 case 4: // result = lea base( , cond*4)
18416 case 5: // result = lea base(cond, cond*4)
18417 case 8: // result = lea base( , cond*8)
18418 case 9: // result = lea base(cond, cond*8)
18419 isFastMultiplier = true;
18424 if (isFastMultiplier) {
18425 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18426 if (NeedsCondInvert) // Invert the condition if needed.
18427 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18428 DAG.getConstant(1, Cond.getValueType()));
18430 // Zero extend the condition if needed.
18431 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18433 // Scale the condition by the difference.
18435 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18436 DAG.getConstant(Diff, Cond.getValueType()));
18438 // Add the base if non-zero.
18439 if (FalseC->getAPIntValue() != 0)
18440 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18441 SDValue(FalseC, 0));
18448 // Canonicalize max and min:
18449 // (x > y) ? x : y -> (x >= y) ? x : y
18450 // (x < y) ? x : y -> (x <= y) ? x : y
18451 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18452 // the need for an extra compare
18453 // against zero. e.g.
18454 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18456 // testl %edi, %edi
18458 // cmovgl %edi, %eax
18462 // cmovsl %eax, %edi
18463 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18464 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18465 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18466 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18471 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18472 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18473 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18474 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18479 // Early exit check
18480 if (!TLI.isTypeLegal(VT))
18483 // Match VSELECTs into subs with unsigned saturation.
18484 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18485 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18486 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18487 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18488 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18490 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18491 // left side invert the predicate to simplify logic below.
18493 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18495 CC = ISD::getSetCCInverse(CC, true);
18496 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18500 if (Other.getNode() && Other->getNumOperands() == 2 &&
18501 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18502 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18503 SDValue CondRHS = Cond->getOperand(1);
18505 // Look for a general sub with unsigned saturation first.
18506 // x >= y ? x-y : 0 --> subus x, y
18507 // x > y ? x-y : 0 --> subus x, y
18508 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18509 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18510 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18512 // If the RHS is a constant we have to reverse the const canonicalization.
18513 // x > C-1 ? x+-C : 0 --> subus x, C
18514 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18515 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18516 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18517 if (CondRHS.getConstantOperandVal(0) == -A-1)
18518 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18519 DAG.getConstant(-A, VT));
18522 // Another special case: If C was a sign bit, the sub has been
18523 // canonicalized into a xor.
18524 // FIXME: Would it be better to use computeKnownBits to determine whether
18525 // it's safe to decanonicalize the xor?
18526 // x s< 0 ? x^C : 0 --> subus x, C
18527 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18528 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18529 isSplatVector(OpRHS.getNode())) {
18530 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18532 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18537 // Try to match a min/max vector operation.
18538 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18539 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18540 unsigned Opc = ret.first;
18541 bool NeedSplit = ret.second;
18543 if (Opc && NeedSplit) {
18544 unsigned NumElems = VT.getVectorNumElements();
18545 // Extract the LHS vectors
18546 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18547 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18549 // Extract the RHS vectors
18550 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18551 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18553 // Create min/max for each subvector
18554 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18555 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18557 // Merge the result
18558 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18560 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18563 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18564 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18565 // Check if SETCC has already been promoted
18566 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18567 // Check that condition value type matches vselect operand type
18570 assert(Cond.getValueType().isVector() &&
18571 "vector select expects a vector selector!");
18573 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18574 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18576 if (!TValIsAllOnes && !FValIsAllZeros) {
18577 // Try invert the condition if true value is not all 1s and false value
18579 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18580 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18582 if (TValIsAllZeros || FValIsAllOnes) {
18583 SDValue CC = Cond.getOperand(2);
18584 ISD::CondCode NewCC =
18585 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18586 Cond.getOperand(0).getValueType().isInteger());
18587 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18588 std::swap(LHS, RHS);
18589 TValIsAllOnes = FValIsAllOnes;
18590 FValIsAllZeros = TValIsAllZeros;
18594 if (TValIsAllOnes || FValIsAllZeros) {
18597 if (TValIsAllOnes && FValIsAllZeros)
18599 else if (TValIsAllOnes)
18600 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18601 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18602 else if (FValIsAllZeros)
18603 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18604 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18606 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18610 // Try to fold this VSELECT into a MOVSS/MOVSD
18611 if (N->getOpcode() == ISD::VSELECT &&
18612 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18613 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18614 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18615 bool CanFold = false;
18616 unsigned NumElems = Cond.getNumOperands();
18620 if (isZero(Cond.getOperand(0))) {
18623 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18624 // fold (vselect <0,-1> -> (movsd A, B)
18625 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18626 CanFold = isAllOnes(Cond.getOperand(i));
18627 } else if (isAllOnes(Cond.getOperand(0))) {
18631 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18632 // fold (vselect <-1,0> -> (movsd B, A)
18633 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18634 CanFold = isZero(Cond.getOperand(i));
18638 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18639 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18640 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18643 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18644 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18645 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18646 // (v2i64 (bitcast B)))))
18648 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18649 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18650 // (v2f64 (bitcast B)))))
18652 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18653 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18654 // (v2i64 (bitcast A)))))
18656 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18657 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18658 // (v2f64 (bitcast A)))))
18660 CanFold = (isZero(Cond.getOperand(0)) &&
18661 isZero(Cond.getOperand(1)) &&
18662 isAllOnes(Cond.getOperand(2)) &&
18663 isAllOnes(Cond.getOperand(3)));
18665 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18666 isAllOnes(Cond.getOperand(1)) &&
18667 isZero(Cond.getOperand(2)) &&
18668 isZero(Cond.getOperand(3))) {
18670 std::swap(LHS, RHS);
18674 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18675 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18676 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18677 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18679 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18685 // If we know that this node is legal then we know that it is going to be
18686 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18687 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18688 // to simplify previous instructions.
18689 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18690 !DCI.isBeforeLegalize() &&
18691 // We explicitly check against v8i16 and v16i16 because, although
18692 // they're marked as Custom, they might only be legal when Cond is a
18693 // build_vector of constants. This will be taken care in a later
18695 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18696 VT != MVT::v8i16)) {
18697 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18699 // Don't optimize vector selects that map to mask-registers.
18703 // Check all uses of that condition operand to check whether it will be
18704 // consumed by non-BLEND instructions, which may depend on all bits are set
18706 for (SDNode::use_iterator I = Cond->use_begin(),
18707 E = Cond->use_end(); I != E; ++I)
18708 if (I->getOpcode() != ISD::VSELECT)
18709 // TODO: Add other opcodes eventually lowered into BLEND.
18712 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18713 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18715 APInt KnownZero, KnownOne;
18716 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18717 DCI.isBeforeLegalizeOps());
18718 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18719 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18720 DCI.CommitTargetLoweringOpt(TLO);
18723 // We should generate an X86ISD::BLENDI from a vselect if its argument
18724 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18725 // constants. This specific pattern gets generated when we split a
18726 // selector for a 512 bit vector in a machine without AVX512 (but with
18727 // 256-bit vectors), during legalization:
18729 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18731 // Iff we find this pattern and the build_vectors are built from
18732 // constants, we translate the vselect into a shuffle_vector that we
18733 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18734 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18735 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18736 if (Shuffle.getNode())
18743 // Check whether a boolean test is testing a boolean value generated by
18744 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18747 // Simplify the following patterns:
18748 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18749 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18750 // to (Op EFLAGS Cond)
18752 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18753 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18754 // to (Op EFLAGS !Cond)
18756 // where Op could be BRCOND or CMOV.
18758 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18759 // Quit if not CMP and SUB with its value result used.
18760 if (Cmp.getOpcode() != X86ISD::CMP &&
18761 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18764 // Quit if not used as a boolean value.
18765 if (CC != X86::COND_E && CC != X86::COND_NE)
18768 // Check CMP operands. One of them should be 0 or 1 and the other should be
18769 // an SetCC or extended from it.
18770 SDValue Op1 = Cmp.getOperand(0);
18771 SDValue Op2 = Cmp.getOperand(1);
18774 const ConstantSDNode* C = nullptr;
18775 bool needOppositeCond = (CC == X86::COND_E);
18776 bool checkAgainstTrue = false; // Is it a comparison against 1?
18778 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18780 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18782 else // Quit if all operands are not constants.
18785 if (C->getZExtValue() == 1) {
18786 needOppositeCond = !needOppositeCond;
18787 checkAgainstTrue = true;
18788 } else if (C->getZExtValue() != 0)
18789 // Quit if the constant is neither 0 or 1.
18792 bool truncatedToBoolWithAnd = false;
18793 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18794 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18795 SetCC.getOpcode() == ISD::TRUNCATE ||
18796 SetCC.getOpcode() == ISD::AND) {
18797 if (SetCC.getOpcode() == ISD::AND) {
18799 ConstantSDNode *CS;
18800 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18801 CS->getZExtValue() == 1)
18803 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18804 CS->getZExtValue() == 1)
18808 SetCC = SetCC.getOperand(OpIdx);
18809 truncatedToBoolWithAnd = true;
18811 SetCC = SetCC.getOperand(0);
18814 switch (SetCC.getOpcode()) {
18815 case X86ISD::SETCC_CARRY:
18816 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18817 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18818 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18819 // truncated to i1 using 'and'.
18820 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18822 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18823 "Invalid use of SETCC_CARRY!");
18825 case X86ISD::SETCC:
18826 // Set the condition code or opposite one if necessary.
18827 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18828 if (needOppositeCond)
18829 CC = X86::GetOppositeBranchCondition(CC);
18830 return SetCC.getOperand(1);
18831 case X86ISD::CMOV: {
18832 // Check whether false/true value has canonical one, i.e. 0 or 1.
18833 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18834 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18835 // Quit if true value is not a constant.
18838 // Quit if false value is not a constant.
18840 SDValue Op = SetCC.getOperand(0);
18841 // Skip 'zext' or 'trunc' node.
18842 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18843 Op.getOpcode() == ISD::TRUNCATE)
18844 Op = Op.getOperand(0);
18845 // A special case for rdrand/rdseed, where 0 is set if false cond is
18847 if ((Op.getOpcode() != X86ISD::RDRAND &&
18848 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18851 // Quit if false value is not the constant 0 or 1.
18852 bool FValIsFalse = true;
18853 if (FVal && FVal->getZExtValue() != 0) {
18854 if (FVal->getZExtValue() != 1)
18856 // If FVal is 1, opposite cond is needed.
18857 needOppositeCond = !needOppositeCond;
18858 FValIsFalse = false;
18860 // Quit if TVal is not the constant opposite of FVal.
18861 if (FValIsFalse && TVal->getZExtValue() != 1)
18863 if (!FValIsFalse && TVal->getZExtValue() != 0)
18865 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18866 if (needOppositeCond)
18867 CC = X86::GetOppositeBranchCondition(CC);
18868 return SetCC.getOperand(3);
18875 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18876 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18877 TargetLowering::DAGCombinerInfo &DCI,
18878 const X86Subtarget *Subtarget) {
18881 // If the flag operand isn't dead, don't touch this CMOV.
18882 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18885 SDValue FalseOp = N->getOperand(0);
18886 SDValue TrueOp = N->getOperand(1);
18887 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18888 SDValue Cond = N->getOperand(3);
18890 if (CC == X86::COND_E || CC == X86::COND_NE) {
18891 switch (Cond.getOpcode()) {
18895 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18896 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18897 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18903 Flags = checkBoolTestSetCCCombine(Cond, CC);
18904 if (Flags.getNode() &&
18905 // Extra check as FCMOV only supports a subset of X86 cond.
18906 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18907 SDValue Ops[] = { FalseOp, TrueOp,
18908 DAG.getConstant(CC, MVT::i8), Flags };
18909 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18912 // If this is a select between two integer constants, try to do some
18913 // optimizations. Note that the operands are ordered the opposite of SELECT
18915 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18916 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18917 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18918 // larger than FalseC (the false value).
18919 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18920 CC = X86::GetOppositeBranchCondition(CC);
18921 std::swap(TrueC, FalseC);
18922 std::swap(TrueOp, FalseOp);
18925 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18926 // This is efficient for any integer data type (including i8/i16) and
18928 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18929 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18930 DAG.getConstant(CC, MVT::i8), Cond);
18932 // Zero extend the condition if needed.
18933 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18935 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18936 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18937 DAG.getConstant(ShAmt, MVT::i8));
18938 if (N->getNumValues() == 2) // Dead flag value?
18939 return DCI.CombineTo(N, Cond, SDValue());
18943 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18944 // for any integer data type, including i8/i16.
18945 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18946 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18947 DAG.getConstant(CC, MVT::i8), Cond);
18949 // Zero extend the condition if needed.
18950 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18951 FalseC->getValueType(0), Cond);
18952 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18953 SDValue(FalseC, 0));
18955 if (N->getNumValues() == 2) // Dead flag value?
18956 return DCI.CombineTo(N, Cond, SDValue());
18960 // Optimize cases that will turn into an LEA instruction. This requires
18961 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18962 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18963 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18964 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18966 bool isFastMultiplier = false;
18968 switch ((unsigned char)Diff) {
18970 case 1: // result = add base, cond
18971 case 2: // result = lea base( , cond*2)
18972 case 3: // result = lea base(cond, cond*2)
18973 case 4: // result = lea base( , cond*4)
18974 case 5: // result = lea base(cond, cond*4)
18975 case 8: // result = lea base( , cond*8)
18976 case 9: // result = lea base(cond, cond*8)
18977 isFastMultiplier = true;
18982 if (isFastMultiplier) {
18983 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18984 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18985 DAG.getConstant(CC, MVT::i8), Cond);
18986 // Zero extend the condition if needed.
18987 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18989 // Scale the condition by the difference.
18991 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18992 DAG.getConstant(Diff, Cond.getValueType()));
18994 // Add the base if non-zero.
18995 if (FalseC->getAPIntValue() != 0)
18996 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18997 SDValue(FalseC, 0));
18998 if (N->getNumValues() == 2) // Dead flag value?
18999 return DCI.CombineTo(N, Cond, SDValue());
19006 // Handle these cases:
19007 // (select (x != c), e, c) -> select (x != c), e, x),
19008 // (select (x == c), c, e) -> select (x == c), x, e)
19009 // where the c is an integer constant, and the "select" is the combination
19010 // of CMOV and CMP.
19012 // The rationale for this change is that the conditional-move from a constant
19013 // needs two instructions, however, conditional-move from a register needs
19014 // only one instruction.
19016 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19017 // some instruction-combining opportunities. This opt needs to be
19018 // postponed as late as possible.
19020 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19021 // the DCI.xxxx conditions are provided to postpone the optimization as
19022 // late as possible.
19024 ConstantSDNode *CmpAgainst = nullptr;
19025 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19026 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19027 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19029 if (CC == X86::COND_NE &&
19030 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19031 CC = X86::GetOppositeBranchCondition(CC);
19032 std::swap(TrueOp, FalseOp);
19035 if (CC == X86::COND_E &&
19036 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19037 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19038 DAG.getConstant(CC, MVT::i8), Cond };
19039 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19047 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19048 const X86Subtarget *Subtarget) {
19049 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19051 default: return SDValue();
19052 // SSE/AVX/AVX2 blend intrinsics.
19053 case Intrinsic::x86_avx2_pblendvb:
19054 case Intrinsic::x86_avx2_pblendw:
19055 case Intrinsic::x86_avx2_pblendd_128:
19056 case Intrinsic::x86_avx2_pblendd_256:
19057 // Don't try to simplify this intrinsic if we don't have AVX2.
19058 if (!Subtarget->hasAVX2())
19061 case Intrinsic::x86_avx_blend_pd_256:
19062 case Intrinsic::x86_avx_blend_ps_256:
19063 case Intrinsic::x86_avx_blendv_pd_256:
19064 case Intrinsic::x86_avx_blendv_ps_256:
19065 // Don't try to simplify this intrinsic if we don't have AVX.
19066 if (!Subtarget->hasAVX())
19069 case Intrinsic::x86_sse41_pblendw:
19070 case Intrinsic::x86_sse41_blendpd:
19071 case Intrinsic::x86_sse41_blendps:
19072 case Intrinsic::x86_sse41_blendvps:
19073 case Intrinsic::x86_sse41_blendvpd:
19074 case Intrinsic::x86_sse41_pblendvb: {
19075 SDValue Op0 = N->getOperand(1);
19076 SDValue Op1 = N->getOperand(2);
19077 SDValue Mask = N->getOperand(3);
19079 // Don't try to simplify this intrinsic if we don't have SSE4.1.
19080 if (!Subtarget->hasSSE41())
19083 // fold (blend A, A, Mask) -> A
19086 // fold (blend A, B, allZeros) -> A
19087 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19089 // fold (blend A, B, allOnes) -> B
19090 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19093 // Simplify the case where the mask is a constant i32 value.
19094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19095 if (C->isNullValue())
19097 if (C->isAllOnesValue())
19102 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19103 case Intrinsic::x86_sse2_psrai_w:
19104 case Intrinsic::x86_sse2_psrai_d:
19105 case Intrinsic::x86_avx2_psrai_w:
19106 case Intrinsic::x86_avx2_psrai_d:
19107 case Intrinsic::x86_sse2_psra_w:
19108 case Intrinsic::x86_sse2_psra_d:
19109 case Intrinsic::x86_avx2_psra_w:
19110 case Intrinsic::x86_avx2_psra_d: {
19111 SDValue Op0 = N->getOperand(1);
19112 SDValue Op1 = N->getOperand(2);
19113 EVT VT = Op0.getValueType();
19114 assert(VT.isVector() && "Expected a vector type!");
19116 if (isa<BuildVectorSDNode>(Op1))
19117 Op1 = Op1.getOperand(0);
19119 if (!isa<ConstantSDNode>(Op1))
19122 EVT SVT = VT.getVectorElementType();
19123 unsigned SVTBits = SVT.getSizeInBits();
19125 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19126 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19127 uint64_t ShAmt = C.getZExtValue();
19129 // Don't try to convert this shift into a ISD::SRA if the shift
19130 // count is bigger than or equal to the element size.
19131 if (ShAmt >= SVTBits)
19134 // Trivial case: if the shift count is zero, then fold this
19135 // into the first operand.
19139 // Replace this packed shift intrinsic with a target independent
19141 SDValue Splat = DAG.getConstant(C, VT);
19142 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19147 /// PerformMulCombine - Optimize a single multiply with constant into two
19148 /// in order to implement it with two cheaper instructions, e.g.
19149 /// LEA + SHL, LEA + LEA.
19150 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19151 TargetLowering::DAGCombinerInfo &DCI) {
19152 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19155 EVT VT = N->getValueType(0);
19156 if (VT != MVT::i64)
19159 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19162 uint64_t MulAmt = C->getZExtValue();
19163 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19166 uint64_t MulAmt1 = 0;
19167 uint64_t MulAmt2 = 0;
19168 if ((MulAmt % 9) == 0) {
19170 MulAmt2 = MulAmt / 9;
19171 } else if ((MulAmt % 5) == 0) {
19173 MulAmt2 = MulAmt / 5;
19174 } else if ((MulAmt % 3) == 0) {
19176 MulAmt2 = MulAmt / 3;
19179 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19182 if (isPowerOf2_64(MulAmt2) &&
19183 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19184 // If second multiplifer is pow2, issue it first. We want the multiply by
19185 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19187 std::swap(MulAmt1, MulAmt2);
19190 if (isPowerOf2_64(MulAmt1))
19191 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19192 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19194 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19195 DAG.getConstant(MulAmt1, VT));
19197 if (isPowerOf2_64(MulAmt2))
19198 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19199 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19201 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19202 DAG.getConstant(MulAmt2, VT));
19204 // Do not add new nodes to DAG combiner worklist.
19205 DCI.CombineTo(N, NewMul, false);
19210 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19211 SDValue N0 = N->getOperand(0);
19212 SDValue N1 = N->getOperand(1);
19213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19214 EVT VT = N0.getValueType();
19216 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19217 // since the result of setcc_c is all zero's or all ones.
19218 if (VT.isInteger() && !VT.isVector() &&
19219 N1C && N0.getOpcode() == ISD::AND &&
19220 N0.getOperand(1).getOpcode() == ISD::Constant) {
19221 SDValue N00 = N0.getOperand(0);
19222 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19223 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19224 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19225 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19226 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19227 APInt ShAmt = N1C->getAPIntValue();
19228 Mask = Mask.shl(ShAmt);
19230 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19231 N00, DAG.getConstant(Mask, VT));
19235 // Hardware support for vector shifts is sparse which makes us scalarize the
19236 // vector operations in many cases. Also, on sandybridge ADD is faster than
19238 // (shl V, 1) -> add V,V
19239 if (isSplatVector(N1.getNode())) {
19240 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19241 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19242 // We shift all of the values by one. In many cases we do not have
19243 // hardware support for this operation. This is better expressed as an ADD
19245 if (N1C && (1 == N1C->getZExtValue())) {
19246 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19253 /// \brief Returns a vector of 0s if the node in input is a vector logical
19254 /// shift by a constant amount which is known to be bigger than or equal
19255 /// to the vector element size in bits.
19256 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19257 const X86Subtarget *Subtarget) {
19258 EVT VT = N->getValueType(0);
19260 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19261 (!Subtarget->hasInt256() ||
19262 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19265 SDValue Amt = N->getOperand(1);
19267 if (isSplatVector(Amt.getNode())) {
19268 SDValue SclrAmt = Amt->getOperand(0);
19269 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19270 APInt ShiftAmt = C->getAPIntValue();
19271 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19273 // SSE2/AVX2 logical shifts always return a vector of 0s
19274 // if the shift amount is bigger than or equal to
19275 // the element size. The constant shift amount will be
19276 // encoded as a 8-bit immediate.
19277 if (ShiftAmt.trunc(8).uge(MaxAmount))
19278 return getZeroVector(VT, Subtarget, DAG, DL);
19285 /// PerformShiftCombine - Combine shifts.
19286 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19287 TargetLowering::DAGCombinerInfo &DCI,
19288 const X86Subtarget *Subtarget) {
19289 if (N->getOpcode() == ISD::SHL) {
19290 SDValue V = PerformSHLCombine(N, DAG);
19291 if (V.getNode()) return V;
19294 if (N->getOpcode() != ISD::SRA) {
19295 // Try to fold this logical shift into a zero vector.
19296 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19297 if (V.getNode()) return V;
19303 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19304 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19305 // and friends. Likewise for OR -> CMPNEQSS.
19306 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19307 TargetLowering::DAGCombinerInfo &DCI,
19308 const X86Subtarget *Subtarget) {
19311 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19312 // we're requiring SSE2 for both.
19313 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19314 SDValue N0 = N->getOperand(0);
19315 SDValue N1 = N->getOperand(1);
19316 SDValue CMP0 = N0->getOperand(1);
19317 SDValue CMP1 = N1->getOperand(1);
19320 // The SETCCs should both refer to the same CMP.
19321 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19324 SDValue CMP00 = CMP0->getOperand(0);
19325 SDValue CMP01 = CMP0->getOperand(1);
19326 EVT VT = CMP00.getValueType();
19328 if (VT == MVT::f32 || VT == MVT::f64) {
19329 bool ExpectingFlags = false;
19330 // Check for any users that want flags:
19331 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19332 !ExpectingFlags && UI != UE; ++UI)
19333 switch (UI->getOpcode()) {
19338 ExpectingFlags = true;
19340 case ISD::CopyToReg:
19341 case ISD::SIGN_EXTEND:
19342 case ISD::ZERO_EXTEND:
19343 case ISD::ANY_EXTEND:
19347 if (!ExpectingFlags) {
19348 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19349 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19351 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19352 X86::CondCode tmp = cc0;
19357 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19358 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19359 // FIXME: need symbolic constants for these magic numbers.
19360 // See X86ATTInstPrinter.cpp:printSSECC().
19361 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19362 if (Subtarget->hasAVX512()) {
19363 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19364 CMP01, DAG.getConstant(x86cc, MVT::i8));
19365 if (N->getValueType(0) != MVT::i1)
19366 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19370 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19371 CMP00.getValueType(), CMP00, CMP01,
19372 DAG.getConstant(x86cc, MVT::i8));
19374 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19375 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19377 if (is64BitFP && !Subtarget->is64Bit()) {
19378 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19379 // 64-bit integer, since that's not a legal type. Since
19380 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19381 // bits, but can do this little dance to extract the lowest 32 bits
19382 // and work with those going forward.
19383 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19385 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19387 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19388 Vector32, DAG.getIntPtrConstant(0));
19392 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19393 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19394 DAG.getConstant(1, IntVT));
19395 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19396 return OneBitOfTruth;
19404 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19405 /// so it can be folded inside ANDNP.
19406 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19407 EVT VT = N->getValueType(0);
19409 // Match direct AllOnes for 128 and 256-bit vectors
19410 if (ISD::isBuildVectorAllOnes(N))
19413 // Look through a bit convert.
19414 if (N->getOpcode() == ISD::BITCAST)
19415 N = N->getOperand(0).getNode();
19417 // Sometimes the operand may come from a insert_subvector building a 256-bit
19419 if (VT.is256BitVector() &&
19420 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19421 SDValue V1 = N->getOperand(0);
19422 SDValue V2 = N->getOperand(1);
19424 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19425 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19426 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19427 ISD::isBuildVectorAllOnes(V2.getNode()))
19434 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19435 // register. In most cases we actually compare or select YMM-sized registers
19436 // and mixing the two types creates horrible code. This method optimizes
19437 // some of the transition sequences.
19438 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19439 TargetLowering::DAGCombinerInfo &DCI,
19440 const X86Subtarget *Subtarget) {
19441 EVT VT = N->getValueType(0);
19442 if (!VT.is256BitVector())
19445 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19446 N->getOpcode() == ISD::ZERO_EXTEND ||
19447 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19449 SDValue Narrow = N->getOperand(0);
19450 EVT NarrowVT = Narrow->getValueType(0);
19451 if (!NarrowVT.is128BitVector())
19454 if (Narrow->getOpcode() != ISD::XOR &&
19455 Narrow->getOpcode() != ISD::AND &&
19456 Narrow->getOpcode() != ISD::OR)
19459 SDValue N0 = Narrow->getOperand(0);
19460 SDValue N1 = Narrow->getOperand(1);
19463 // The Left side has to be a trunc.
19464 if (N0.getOpcode() != ISD::TRUNCATE)
19467 // The type of the truncated inputs.
19468 EVT WideVT = N0->getOperand(0)->getValueType(0);
19472 // The right side has to be a 'trunc' or a constant vector.
19473 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19474 bool RHSConst = (isSplatVector(N1.getNode()) &&
19475 isa<ConstantSDNode>(N1->getOperand(0)));
19476 if (!RHSTrunc && !RHSConst)
19479 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19481 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19484 // Set N0 and N1 to hold the inputs to the new wide operation.
19485 N0 = N0->getOperand(0);
19487 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19488 N1->getOperand(0));
19489 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19490 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19491 } else if (RHSTrunc) {
19492 N1 = N1->getOperand(0);
19495 // Generate the wide operation.
19496 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19497 unsigned Opcode = N->getOpcode();
19499 case ISD::ANY_EXTEND:
19501 case ISD::ZERO_EXTEND: {
19502 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19503 APInt Mask = APInt::getAllOnesValue(InBits);
19504 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19505 return DAG.getNode(ISD::AND, DL, VT,
19506 Op, DAG.getConstant(Mask, VT));
19508 case ISD::SIGN_EXTEND:
19509 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19510 Op, DAG.getValueType(NarrowVT));
19512 llvm_unreachable("Unexpected opcode");
19516 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19517 TargetLowering::DAGCombinerInfo &DCI,
19518 const X86Subtarget *Subtarget) {
19519 EVT VT = N->getValueType(0);
19520 if (DCI.isBeforeLegalizeOps())
19523 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19527 // Create BEXTR instructions
19528 // BEXTR is ((X >> imm) & (2**size-1))
19529 if (VT == MVT::i32 || VT == MVT::i64) {
19530 SDValue N0 = N->getOperand(0);
19531 SDValue N1 = N->getOperand(1);
19534 // Check for BEXTR.
19535 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19536 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19537 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19538 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19539 if (MaskNode && ShiftNode) {
19540 uint64_t Mask = MaskNode->getZExtValue();
19541 uint64_t Shift = ShiftNode->getZExtValue();
19542 if (isMask_64(Mask)) {
19543 uint64_t MaskSize = CountPopulation_64(Mask);
19544 if (Shift + MaskSize <= VT.getSizeInBits())
19545 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19546 DAG.getConstant(Shift | (MaskSize << 8), VT));
19554 // Want to form ANDNP nodes:
19555 // 1) In the hopes of then easily combining them with OR and AND nodes
19556 // to form PBLEND/PSIGN.
19557 // 2) To match ANDN packed intrinsics
19558 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19561 SDValue N0 = N->getOperand(0);
19562 SDValue N1 = N->getOperand(1);
19565 // Check LHS for vnot
19566 if (N0.getOpcode() == ISD::XOR &&
19567 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19568 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19569 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19571 // Check RHS for vnot
19572 if (N1.getOpcode() == ISD::XOR &&
19573 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19574 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19575 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19580 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19581 TargetLowering::DAGCombinerInfo &DCI,
19582 const X86Subtarget *Subtarget) {
19583 if (DCI.isBeforeLegalizeOps())
19586 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19590 SDValue N0 = N->getOperand(0);
19591 SDValue N1 = N->getOperand(1);
19592 EVT VT = N->getValueType(0);
19594 // look for psign/blend
19595 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19596 if (!Subtarget->hasSSSE3() ||
19597 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19600 // Canonicalize pandn to RHS
19601 if (N0.getOpcode() == X86ISD::ANDNP)
19603 // or (and (m, y), (pandn m, x))
19604 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19605 SDValue Mask = N1.getOperand(0);
19606 SDValue X = N1.getOperand(1);
19608 if (N0.getOperand(0) == Mask)
19609 Y = N0.getOperand(1);
19610 if (N0.getOperand(1) == Mask)
19611 Y = N0.getOperand(0);
19613 // Check to see if the mask appeared in both the AND and ANDNP and
19617 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19618 // Look through mask bitcast.
19619 if (Mask.getOpcode() == ISD::BITCAST)
19620 Mask = Mask.getOperand(0);
19621 if (X.getOpcode() == ISD::BITCAST)
19622 X = X.getOperand(0);
19623 if (Y.getOpcode() == ISD::BITCAST)
19624 Y = Y.getOperand(0);
19626 EVT MaskVT = Mask.getValueType();
19628 // Validate that the Mask operand is a vector sra node.
19629 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19630 // there is no psrai.b
19631 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19632 unsigned SraAmt = ~0;
19633 if (Mask.getOpcode() == ISD::SRA) {
19634 SDValue Amt = Mask.getOperand(1);
19635 if (isSplatVector(Amt.getNode())) {
19636 SDValue SclrAmt = Amt->getOperand(0);
19637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19638 SraAmt = C->getZExtValue();
19640 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19641 SDValue SraC = Mask.getOperand(1);
19642 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19644 if ((SraAmt + 1) != EltBits)
19649 // Now we know we at least have a plendvb with the mask val. See if
19650 // we can form a psignb/w/d.
19651 // psign = x.type == y.type == mask.type && y = sub(0, x);
19652 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19653 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19654 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19655 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19656 "Unsupported VT for PSIGN");
19657 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19658 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19660 // PBLENDVB only available on SSE 4.1
19661 if (!Subtarget->hasSSE41())
19664 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19666 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19667 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19668 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19669 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19670 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19674 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19677 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19678 MachineFunction &MF = DAG.getMachineFunction();
19679 bool OptForSize = MF.getFunction()->getAttributes().
19680 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19682 // SHLD/SHRD instructions have lower register pressure, but on some
19683 // platforms they have higher latency than the equivalent
19684 // series of shifts/or that would otherwise be generated.
19685 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19686 // have higher latencies and we are not optimizing for size.
19687 if (!OptForSize && Subtarget->isSHLDSlow())
19690 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19692 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19694 if (!N0.hasOneUse() || !N1.hasOneUse())
19697 SDValue ShAmt0 = N0.getOperand(1);
19698 if (ShAmt0.getValueType() != MVT::i8)
19700 SDValue ShAmt1 = N1.getOperand(1);
19701 if (ShAmt1.getValueType() != MVT::i8)
19703 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19704 ShAmt0 = ShAmt0.getOperand(0);
19705 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19706 ShAmt1 = ShAmt1.getOperand(0);
19709 unsigned Opc = X86ISD::SHLD;
19710 SDValue Op0 = N0.getOperand(0);
19711 SDValue Op1 = N1.getOperand(0);
19712 if (ShAmt0.getOpcode() == ISD::SUB) {
19713 Opc = X86ISD::SHRD;
19714 std::swap(Op0, Op1);
19715 std::swap(ShAmt0, ShAmt1);
19718 unsigned Bits = VT.getSizeInBits();
19719 if (ShAmt1.getOpcode() == ISD::SUB) {
19720 SDValue Sum = ShAmt1.getOperand(0);
19721 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19722 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19723 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19724 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19725 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19726 return DAG.getNode(Opc, DL, VT,
19728 DAG.getNode(ISD::TRUNCATE, DL,
19731 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19732 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19734 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19735 return DAG.getNode(Opc, DL, VT,
19736 N0.getOperand(0), N1.getOperand(0),
19737 DAG.getNode(ISD::TRUNCATE, DL,
19744 // Generate NEG and CMOV for integer abs.
19745 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19746 EVT VT = N->getValueType(0);
19748 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19749 // 8-bit integer abs to NEG and CMOV.
19750 if (VT.isInteger() && VT.getSizeInBits() == 8)
19753 SDValue N0 = N->getOperand(0);
19754 SDValue N1 = N->getOperand(1);
19757 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19758 // and change it to SUB and CMOV.
19759 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19760 N0.getOpcode() == ISD::ADD &&
19761 N0.getOperand(1) == N1 &&
19762 N1.getOpcode() == ISD::SRA &&
19763 N1.getOperand(0) == N0.getOperand(0))
19764 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19765 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19766 // Generate SUB & CMOV.
19767 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19768 DAG.getConstant(0, VT), N0.getOperand(0));
19770 SDValue Ops[] = { N0.getOperand(0), Neg,
19771 DAG.getConstant(X86::COND_GE, MVT::i8),
19772 SDValue(Neg.getNode(), 1) };
19773 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19778 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19779 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19780 TargetLowering::DAGCombinerInfo &DCI,
19781 const X86Subtarget *Subtarget) {
19782 if (DCI.isBeforeLegalizeOps())
19785 if (Subtarget->hasCMov()) {
19786 SDValue RV = performIntegerAbsCombine(N, DAG);
19794 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19795 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19796 TargetLowering::DAGCombinerInfo &DCI,
19797 const X86Subtarget *Subtarget) {
19798 LoadSDNode *Ld = cast<LoadSDNode>(N);
19799 EVT RegVT = Ld->getValueType(0);
19800 EVT MemVT = Ld->getMemoryVT();
19802 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19803 unsigned RegSz = RegVT.getSizeInBits();
19805 // On Sandybridge unaligned 256bit loads are inefficient.
19806 ISD::LoadExtType Ext = Ld->getExtensionType();
19807 unsigned Alignment = Ld->getAlignment();
19808 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19809 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19810 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19811 unsigned NumElems = RegVT.getVectorNumElements();
19815 SDValue Ptr = Ld->getBasePtr();
19816 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19818 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19820 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19821 Ld->getPointerInfo(), Ld->isVolatile(),
19822 Ld->isNonTemporal(), Ld->isInvariant(),
19824 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19825 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19826 Ld->getPointerInfo(), Ld->isVolatile(),
19827 Ld->isNonTemporal(), Ld->isInvariant(),
19828 std::min(16U, Alignment));
19829 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19831 Load2.getValue(1));
19833 SDValue NewVec = DAG.getUNDEF(RegVT);
19834 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19835 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19836 return DCI.CombineTo(N, NewVec, TF, true);
19839 // If this is a vector EXT Load then attempt to optimize it using a
19840 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19841 // expansion is still better than scalar code.
19842 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19843 // emit a shuffle and a arithmetic shift.
19844 // TODO: It is possible to support ZExt by zeroing the undef values
19845 // during the shuffle phase or after the shuffle.
19846 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19847 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19848 assert(MemVT != RegVT && "Cannot extend to the same type");
19849 assert(MemVT.isVector() && "Must load a vector from memory");
19851 unsigned NumElems = RegVT.getVectorNumElements();
19852 unsigned MemSz = MemVT.getSizeInBits();
19853 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19855 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19858 // All sizes must be a power of two.
19859 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19862 // Attempt to load the original value using scalar loads.
19863 // Find the largest scalar type that divides the total loaded size.
19864 MVT SclrLoadTy = MVT::i8;
19865 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19866 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19867 MVT Tp = (MVT::SimpleValueType)tp;
19868 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19873 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19874 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19876 SclrLoadTy = MVT::f64;
19878 // Calculate the number of scalar loads that we need to perform
19879 // in order to load our vector from memory.
19880 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19881 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19884 unsigned loadRegZize = RegSz;
19885 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19888 // Represent our vector as a sequence of elements which are the
19889 // largest scalar that we can load.
19890 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19891 loadRegZize/SclrLoadTy.getSizeInBits());
19893 // Represent the data using the same element type that is stored in
19894 // memory. In practice, we ''widen'' MemVT.
19896 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19897 loadRegZize/MemVT.getScalarType().getSizeInBits());
19899 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19900 "Invalid vector type");
19902 // We can't shuffle using an illegal type.
19903 if (!TLI.isTypeLegal(WideVecVT))
19906 SmallVector<SDValue, 8> Chains;
19907 SDValue Ptr = Ld->getBasePtr();
19908 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19909 TLI.getPointerTy());
19910 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19912 for (unsigned i = 0; i < NumLoads; ++i) {
19913 // Perform a single load.
19914 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19915 Ptr, Ld->getPointerInfo(),
19916 Ld->isVolatile(), Ld->isNonTemporal(),
19917 Ld->isInvariant(), Ld->getAlignment());
19918 Chains.push_back(ScalarLoad.getValue(1));
19919 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19920 // another round of DAGCombining.
19922 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19924 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19925 ScalarLoad, DAG.getIntPtrConstant(i));
19927 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19930 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19932 // Bitcast the loaded value to a vector of the original element type, in
19933 // the size of the target vector type.
19934 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19935 unsigned SizeRatio = RegSz/MemSz;
19937 if (Ext == ISD::SEXTLOAD) {
19938 // If we have SSE4.1 we can directly emit a VSEXT node.
19939 if (Subtarget->hasSSE41()) {
19940 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19941 return DCI.CombineTo(N, Sext, TF, true);
19944 // Otherwise we'll shuffle the small elements in the high bits of the
19945 // larger type and perform an arithmetic shift. If the shift is not legal
19946 // it's better to scalarize.
19947 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19950 // Redistribute the loaded elements into the different locations.
19951 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19952 for (unsigned i = 0; i != NumElems; ++i)
19953 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19955 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19956 DAG.getUNDEF(WideVecVT),
19959 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19961 // Build the arithmetic shift.
19962 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19963 MemVT.getVectorElementType().getSizeInBits();
19964 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19965 DAG.getConstant(Amt, RegVT));
19967 return DCI.CombineTo(N, Shuff, TF, true);
19970 // Redistribute the loaded elements into the different locations.
19971 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19972 for (unsigned i = 0; i != NumElems; ++i)
19973 ShuffleVec[i*SizeRatio] = i;
19975 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19976 DAG.getUNDEF(WideVecVT),
19979 // Bitcast to the requested type.
19980 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19981 // Replace the original load with the new sequence
19982 // and return the new chain.
19983 return DCI.CombineTo(N, Shuff, TF, true);
19989 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19990 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19991 const X86Subtarget *Subtarget) {
19992 StoreSDNode *St = cast<StoreSDNode>(N);
19993 EVT VT = St->getValue().getValueType();
19994 EVT StVT = St->getMemoryVT();
19996 SDValue StoredVal = St->getOperand(1);
19997 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19999 // If we are saving a concatenation of two XMM registers, perform two stores.
20000 // On Sandy Bridge, 256-bit memory operations are executed by two
20001 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20002 // memory operation.
20003 unsigned Alignment = St->getAlignment();
20004 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20005 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20006 StVT == VT && !IsAligned) {
20007 unsigned NumElems = VT.getVectorNumElements();
20011 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20012 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20014 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20015 SDValue Ptr0 = St->getBasePtr();
20016 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20018 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20019 St->getPointerInfo(), St->isVolatile(),
20020 St->isNonTemporal(), Alignment);
20021 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20022 St->getPointerInfo(), St->isVolatile(),
20023 St->isNonTemporal(),
20024 std::min(16U, Alignment));
20025 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20028 // Optimize trunc store (of multiple scalars) to shuffle and store.
20029 // First, pack all of the elements in one place. Next, store to memory
20030 // in fewer chunks.
20031 if (St->isTruncatingStore() && VT.isVector()) {
20032 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20033 unsigned NumElems = VT.getVectorNumElements();
20034 assert(StVT != VT && "Cannot truncate to the same type");
20035 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20036 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20038 // From, To sizes and ElemCount must be pow of two
20039 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20040 // We are going to use the original vector elt for storing.
20041 // Accumulated smaller vector elements must be a multiple of the store size.
20042 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20044 unsigned SizeRatio = FromSz / ToSz;
20046 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20048 // Create a type on which we perform the shuffle
20049 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20050 StVT.getScalarType(), NumElems*SizeRatio);
20052 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20054 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20055 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20056 for (unsigned i = 0; i != NumElems; ++i)
20057 ShuffleVec[i] = i * SizeRatio;
20059 // Can't shuffle using an illegal type.
20060 if (!TLI.isTypeLegal(WideVecVT))
20063 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20064 DAG.getUNDEF(WideVecVT),
20066 // At this point all of the data is stored at the bottom of the
20067 // register. We now need to save it to mem.
20069 // Find the largest store unit
20070 MVT StoreType = MVT::i8;
20071 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20072 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20073 MVT Tp = (MVT::SimpleValueType)tp;
20074 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20078 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20079 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20080 (64 <= NumElems * ToSz))
20081 StoreType = MVT::f64;
20083 // Bitcast the original vector into a vector of store-size units
20084 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20085 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20086 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20087 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20088 SmallVector<SDValue, 8> Chains;
20089 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20090 TLI.getPointerTy());
20091 SDValue Ptr = St->getBasePtr();
20093 // Perform one or more big stores into memory.
20094 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20095 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20096 StoreType, ShuffWide,
20097 DAG.getIntPtrConstant(i));
20098 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20099 St->getPointerInfo(), St->isVolatile(),
20100 St->isNonTemporal(), St->getAlignment());
20101 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20102 Chains.push_back(Ch);
20105 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20108 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
20109 // the FP state in cases where an emms may be missing.
20110 // A preferable solution to the general problem is to figure out the right
20111 // places to insert EMMS. This qualifies as a quick hack.
20113 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20114 if (VT.getSizeInBits() != 64)
20117 const Function *F = DAG.getMachineFunction().getFunction();
20118 bool NoImplicitFloatOps = F->getAttributes().
20119 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20120 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20121 && Subtarget->hasSSE2();
20122 if ((VT.isVector() ||
20123 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20124 isa<LoadSDNode>(St->getValue()) &&
20125 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20126 St->getChain().hasOneUse() && !St->isVolatile()) {
20127 SDNode* LdVal = St->getValue().getNode();
20128 LoadSDNode *Ld = nullptr;
20129 int TokenFactorIndex = -1;
20130 SmallVector<SDValue, 8> Ops;
20131 SDNode* ChainVal = St->getChain().getNode();
20132 // Must be a store of a load. We currently handle two cases: the load
20133 // is a direct child, and it's under an intervening TokenFactor. It is
20134 // possible to dig deeper under nested TokenFactors.
20135 if (ChainVal == LdVal)
20136 Ld = cast<LoadSDNode>(St->getChain());
20137 else if (St->getValue().hasOneUse() &&
20138 ChainVal->getOpcode() == ISD::TokenFactor) {
20139 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20140 if (ChainVal->getOperand(i).getNode() == LdVal) {
20141 TokenFactorIndex = i;
20142 Ld = cast<LoadSDNode>(St->getValue());
20144 Ops.push_back(ChainVal->getOperand(i));
20148 if (!Ld || !ISD::isNormalLoad(Ld))
20151 // If this is not the MMX case, i.e. we are just turning i64 load/store
20152 // into f64 load/store, avoid the transformation if there are multiple
20153 // uses of the loaded value.
20154 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20159 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20160 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20162 if (Subtarget->is64Bit() || F64IsLegal) {
20163 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20164 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20165 Ld->getPointerInfo(), Ld->isVolatile(),
20166 Ld->isNonTemporal(), Ld->isInvariant(),
20167 Ld->getAlignment());
20168 SDValue NewChain = NewLd.getValue(1);
20169 if (TokenFactorIndex != -1) {
20170 Ops.push_back(NewChain);
20171 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20173 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20174 St->getPointerInfo(),
20175 St->isVolatile(), St->isNonTemporal(),
20176 St->getAlignment());
20179 // Otherwise, lower to two pairs of 32-bit loads / stores.
20180 SDValue LoAddr = Ld->getBasePtr();
20181 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20182 DAG.getConstant(4, MVT::i32));
20184 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20185 Ld->getPointerInfo(),
20186 Ld->isVolatile(), Ld->isNonTemporal(),
20187 Ld->isInvariant(), Ld->getAlignment());
20188 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20189 Ld->getPointerInfo().getWithOffset(4),
20190 Ld->isVolatile(), Ld->isNonTemporal(),
20192 MinAlign(Ld->getAlignment(), 4));
20194 SDValue NewChain = LoLd.getValue(1);
20195 if (TokenFactorIndex != -1) {
20196 Ops.push_back(LoLd);
20197 Ops.push_back(HiLd);
20198 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20201 LoAddr = St->getBasePtr();
20202 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20203 DAG.getConstant(4, MVT::i32));
20205 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20206 St->getPointerInfo(),
20207 St->isVolatile(), St->isNonTemporal(),
20208 St->getAlignment());
20209 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20210 St->getPointerInfo().getWithOffset(4),
20212 St->isNonTemporal(),
20213 MinAlign(St->getAlignment(), 4));
20214 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20219 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20220 /// and return the operands for the horizontal operation in LHS and RHS. A
20221 /// horizontal operation performs the binary operation on successive elements
20222 /// of its first operand, then on successive elements of its second operand,
20223 /// returning the resulting values in a vector. For example, if
20224 /// A = < float a0, float a1, float a2, float a3 >
20226 /// B = < float b0, float b1, float b2, float b3 >
20227 /// then the result of doing a horizontal operation on A and B is
20228 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20229 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20230 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20231 /// set to A, RHS to B, and the routine returns 'true'.
20232 /// Note that the binary operation should have the property that if one of the
20233 /// operands is UNDEF then the result is UNDEF.
20234 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20235 // Look for the following pattern: if
20236 // A = < float a0, float a1, float a2, float a3 >
20237 // B = < float b0, float b1, float b2, float b3 >
20239 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20240 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20241 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20242 // which is A horizontal-op B.
20244 // At least one of the operands should be a vector shuffle.
20245 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20246 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20249 MVT VT = LHS.getSimpleValueType();
20251 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20252 "Unsupported vector type for horizontal add/sub");
20254 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20255 // operate independently on 128-bit lanes.
20256 unsigned NumElts = VT.getVectorNumElements();
20257 unsigned NumLanes = VT.getSizeInBits()/128;
20258 unsigned NumLaneElts = NumElts / NumLanes;
20259 assert((NumLaneElts % 2 == 0) &&
20260 "Vector type should have an even number of elements in each lane");
20261 unsigned HalfLaneElts = NumLaneElts/2;
20263 // View LHS in the form
20264 // LHS = VECTOR_SHUFFLE A, B, LMask
20265 // If LHS is not a shuffle then pretend it is the shuffle
20266 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20267 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20270 SmallVector<int, 16> LMask(NumElts);
20271 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20272 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20273 A = LHS.getOperand(0);
20274 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20275 B = LHS.getOperand(1);
20276 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20277 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20279 if (LHS.getOpcode() != ISD::UNDEF)
20281 for (unsigned i = 0; i != NumElts; ++i)
20285 // Likewise, view RHS in the form
20286 // RHS = VECTOR_SHUFFLE C, D, RMask
20288 SmallVector<int, 16> RMask(NumElts);
20289 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20290 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20291 C = RHS.getOperand(0);
20292 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20293 D = RHS.getOperand(1);
20294 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20295 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20297 if (RHS.getOpcode() != ISD::UNDEF)
20299 for (unsigned i = 0; i != NumElts; ++i)
20303 // Check that the shuffles are both shuffling the same vectors.
20304 if (!(A == C && B == D) && !(A == D && B == C))
20307 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20308 if (!A.getNode() && !B.getNode())
20311 // If A and B occur in reverse order in RHS, then "swap" them (which means
20312 // rewriting the mask).
20314 CommuteVectorShuffleMask(RMask, NumElts);
20316 // At this point LHS and RHS are equivalent to
20317 // LHS = VECTOR_SHUFFLE A, B, LMask
20318 // RHS = VECTOR_SHUFFLE A, B, RMask
20319 // Check that the masks correspond to performing a horizontal operation.
20320 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20321 for (unsigned i = 0; i != NumLaneElts; ++i) {
20322 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20324 // Ignore any UNDEF components.
20325 if (LIdx < 0 || RIdx < 0 ||
20326 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20327 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20330 // Check that successive elements are being operated on. If not, this is
20331 // not a horizontal operation.
20332 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20333 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20334 if (!(LIdx == Index && RIdx == Index + 1) &&
20335 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20340 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20341 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20345 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20346 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20347 const X86Subtarget *Subtarget) {
20348 EVT VT = N->getValueType(0);
20349 SDValue LHS = N->getOperand(0);
20350 SDValue RHS = N->getOperand(1);
20352 // Try to synthesize horizontal adds from adds of shuffles.
20353 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20354 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20355 isHorizontalBinOp(LHS, RHS, true))
20356 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20360 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20361 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20362 const X86Subtarget *Subtarget) {
20363 EVT VT = N->getValueType(0);
20364 SDValue LHS = N->getOperand(0);
20365 SDValue RHS = N->getOperand(1);
20367 // Try to synthesize horizontal subs from subs of shuffles.
20368 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20369 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20370 isHorizontalBinOp(LHS, RHS, false))
20371 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20375 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20376 /// X86ISD::FXOR nodes.
20377 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20378 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20379 // F[X]OR(0.0, x) -> x
20380 // F[X]OR(x, 0.0) -> x
20381 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20382 if (C->getValueAPF().isPosZero())
20383 return N->getOperand(1);
20384 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20385 if (C->getValueAPF().isPosZero())
20386 return N->getOperand(0);
20390 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20391 /// X86ISD::FMAX nodes.
20392 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20393 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20395 // Only perform optimizations if UnsafeMath is used.
20396 if (!DAG.getTarget().Options.UnsafeFPMath)
20399 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20400 // into FMINC and FMAXC, which are Commutative operations.
20401 unsigned NewOp = 0;
20402 switch (N->getOpcode()) {
20403 default: llvm_unreachable("unknown opcode");
20404 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20405 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20408 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20409 N->getOperand(0), N->getOperand(1));
20412 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20413 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20414 // FAND(0.0, x) -> 0.0
20415 // FAND(x, 0.0) -> 0.0
20416 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20417 if (C->getValueAPF().isPosZero())
20418 return N->getOperand(0);
20419 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20420 if (C->getValueAPF().isPosZero())
20421 return N->getOperand(1);
20425 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20426 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20427 // FANDN(x, 0.0) -> 0.0
20428 // FANDN(0.0, x) -> x
20429 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20430 if (C->getValueAPF().isPosZero())
20431 return N->getOperand(1);
20432 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20433 if (C->getValueAPF().isPosZero())
20434 return N->getOperand(1);
20438 static SDValue PerformBTCombine(SDNode *N,
20440 TargetLowering::DAGCombinerInfo &DCI) {
20441 // BT ignores high bits in the bit index operand.
20442 SDValue Op1 = N->getOperand(1);
20443 if (Op1.hasOneUse()) {
20444 unsigned BitWidth = Op1.getValueSizeInBits();
20445 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20446 APInt KnownZero, KnownOne;
20447 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20448 !DCI.isBeforeLegalizeOps());
20449 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20450 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20451 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20452 DCI.CommitTargetLoweringOpt(TLO);
20457 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20458 SDValue Op = N->getOperand(0);
20459 if (Op.getOpcode() == ISD::BITCAST)
20460 Op = Op.getOperand(0);
20461 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20462 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20463 VT.getVectorElementType().getSizeInBits() ==
20464 OpVT.getVectorElementType().getSizeInBits()) {
20465 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20470 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20471 const X86Subtarget *Subtarget) {
20472 EVT VT = N->getValueType(0);
20473 if (!VT.isVector())
20476 SDValue N0 = N->getOperand(0);
20477 SDValue N1 = N->getOperand(1);
20478 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20481 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20482 // both SSE and AVX2 since there is no sign-extended shift right
20483 // operation on a vector with 64-bit elements.
20484 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20485 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20486 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20487 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20488 SDValue N00 = N0.getOperand(0);
20490 // EXTLOAD has a better solution on AVX2,
20491 // it may be replaced with X86ISD::VSEXT node.
20492 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20493 if (!ISD::isNormalLoad(N00.getNode()))
20496 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20497 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20499 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20505 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20506 TargetLowering::DAGCombinerInfo &DCI,
20507 const X86Subtarget *Subtarget) {
20508 if (!DCI.isBeforeLegalizeOps())
20511 if (!Subtarget->hasFp256())
20514 EVT VT = N->getValueType(0);
20515 if (VT.isVector() && VT.getSizeInBits() == 256) {
20516 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20524 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20525 const X86Subtarget* Subtarget) {
20527 EVT VT = N->getValueType(0);
20529 // Let legalize expand this if it isn't a legal type yet.
20530 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20533 EVT ScalarVT = VT.getScalarType();
20534 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20535 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20538 SDValue A = N->getOperand(0);
20539 SDValue B = N->getOperand(1);
20540 SDValue C = N->getOperand(2);
20542 bool NegA = (A.getOpcode() == ISD::FNEG);
20543 bool NegB = (B.getOpcode() == ISD::FNEG);
20544 bool NegC = (C.getOpcode() == ISD::FNEG);
20546 // Negative multiplication when NegA xor NegB
20547 bool NegMul = (NegA != NegB);
20549 A = A.getOperand(0);
20551 B = B.getOperand(0);
20553 C = C.getOperand(0);
20557 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20559 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20561 return DAG.getNode(Opcode, dl, VT, A, B, C);
20564 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20565 TargetLowering::DAGCombinerInfo &DCI,
20566 const X86Subtarget *Subtarget) {
20567 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20568 // (and (i32 x86isd::setcc_carry), 1)
20569 // This eliminates the zext. This transformation is necessary because
20570 // ISD::SETCC is always legalized to i8.
20572 SDValue N0 = N->getOperand(0);
20573 EVT VT = N->getValueType(0);
20575 if (N0.getOpcode() == ISD::AND &&
20577 N0.getOperand(0).hasOneUse()) {
20578 SDValue N00 = N0.getOperand(0);
20579 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20580 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20581 if (!C || C->getZExtValue() != 1)
20583 return DAG.getNode(ISD::AND, dl, VT,
20584 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20585 N00.getOperand(0), N00.getOperand(1)),
20586 DAG.getConstant(1, VT));
20590 if (N0.getOpcode() == ISD::TRUNCATE &&
20592 N0.getOperand(0).hasOneUse()) {
20593 SDValue N00 = N0.getOperand(0);
20594 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20595 return DAG.getNode(ISD::AND, dl, VT,
20596 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20597 N00.getOperand(0), N00.getOperand(1)),
20598 DAG.getConstant(1, VT));
20601 if (VT.is256BitVector()) {
20602 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20610 // Optimize x == -y --> x+y == 0
20611 // x != -y --> x+y != 0
20612 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20613 const X86Subtarget* Subtarget) {
20614 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20615 SDValue LHS = N->getOperand(0);
20616 SDValue RHS = N->getOperand(1);
20617 EVT VT = N->getValueType(0);
20620 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20621 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20622 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20623 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20624 LHS.getValueType(), RHS, LHS.getOperand(1));
20625 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20626 addV, DAG.getConstant(0, addV.getValueType()), CC);
20628 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20629 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20630 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20631 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20632 RHS.getValueType(), LHS, RHS.getOperand(1));
20633 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20634 addV, DAG.getConstant(0, addV.getValueType()), CC);
20637 if (VT.getScalarType() == MVT::i1) {
20638 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20639 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20640 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20641 if (!IsSEXT0 && !IsVZero0)
20643 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20644 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20645 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20647 if (!IsSEXT1 && !IsVZero1)
20650 if (IsSEXT0 && IsVZero1) {
20651 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20652 if (CC == ISD::SETEQ)
20653 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20654 return LHS.getOperand(0);
20656 if (IsSEXT1 && IsVZero0) {
20657 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20658 if (CC == ISD::SETEQ)
20659 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20660 return RHS.getOperand(0);
20667 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20668 const X86Subtarget *Subtarget) {
20670 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20671 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20672 "X86insertps is only defined for v4x32");
20674 SDValue Ld = N->getOperand(1);
20675 if (MayFoldLoad(Ld)) {
20676 // Extract the countS bits from the immediate so we can get the proper
20677 // address when narrowing the vector load to a specific element.
20678 // When the second source op is a memory address, interps doesn't use
20679 // countS and just gets an f32 from that address.
20680 unsigned DestIndex =
20681 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20682 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20686 // Create this as a scalar to vector to match the instruction pattern.
20687 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20688 // countS bits are ignored when loading from memory on insertps, which
20689 // means we don't need to explicitly set them to 0.
20690 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20691 LoadScalarToVector, N->getOperand(2));
20694 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20695 // as "sbb reg,reg", since it can be extended without zext and produces
20696 // an all-ones bit which is more useful than 0/1 in some cases.
20697 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20700 return DAG.getNode(ISD::AND, DL, VT,
20701 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20702 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20703 DAG.getConstant(1, VT));
20704 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20705 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20706 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20707 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20710 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20711 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20712 TargetLowering::DAGCombinerInfo &DCI,
20713 const X86Subtarget *Subtarget) {
20715 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20716 SDValue EFLAGS = N->getOperand(1);
20718 if (CC == X86::COND_A) {
20719 // Try to convert COND_A into COND_B in an attempt to facilitate
20720 // materializing "setb reg".
20722 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20723 // cannot take an immediate as its first operand.
20725 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20726 EFLAGS.getValueType().isInteger() &&
20727 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20728 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20729 EFLAGS.getNode()->getVTList(),
20730 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20731 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20732 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20736 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20737 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20739 if (CC == X86::COND_B)
20740 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20744 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20745 if (Flags.getNode()) {
20746 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20747 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20753 // Optimize branch condition evaluation.
20755 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20756 TargetLowering::DAGCombinerInfo &DCI,
20757 const X86Subtarget *Subtarget) {
20759 SDValue Chain = N->getOperand(0);
20760 SDValue Dest = N->getOperand(1);
20761 SDValue EFLAGS = N->getOperand(3);
20762 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20766 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20767 if (Flags.getNode()) {
20768 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20769 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20776 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20777 const X86TargetLowering *XTLI) {
20778 SDValue Op0 = N->getOperand(0);
20779 EVT InVT = Op0->getValueType(0);
20781 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20782 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20784 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20785 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20786 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20789 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20790 // a 32-bit target where SSE doesn't support i64->FP operations.
20791 if (Op0.getOpcode() == ISD::LOAD) {
20792 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20793 EVT VT = Ld->getValueType(0);
20794 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20795 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20796 !XTLI->getSubtarget()->is64Bit() &&
20798 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20799 Ld->getChain(), Op0, DAG);
20800 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20807 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20808 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20809 X86TargetLowering::DAGCombinerInfo &DCI) {
20810 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20811 // the result is either zero or one (depending on the input carry bit).
20812 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20813 if (X86::isZeroNode(N->getOperand(0)) &&
20814 X86::isZeroNode(N->getOperand(1)) &&
20815 // We don't have a good way to replace an EFLAGS use, so only do this when
20817 SDValue(N, 1).use_empty()) {
20819 EVT VT = N->getValueType(0);
20820 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20821 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20822 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20823 DAG.getConstant(X86::COND_B,MVT::i8),
20825 DAG.getConstant(1, VT));
20826 return DCI.CombineTo(N, Res1, CarryOut);
20832 // fold (add Y, (sete X, 0)) -> adc 0, Y
20833 // (add Y, (setne X, 0)) -> sbb -1, Y
20834 // (sub (sete X, 0), Y) -> sbb 0, Y
20835 // (sub (setne X, 0), Y) -> adc -1, Y
20836 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20839 // Look through ZExts.
20840 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20841 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20844 SDValue SetCC = Ext.getOperand(0);
20845 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20848 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20849 if (CC != X86::COND_E && CC != X86::COND_NE)
20852 SDValue Cmp = SetCC.getOperand(1);
20853 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20854 !X86::isZeroNode(Cmp.getOperand(1)) ||
20855 !Cmp.getOperand(0).getValueType().isInteger())
20858 SDValue CmpOp0 = Cmp.getOperand(0);
20859 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20860 DAG.getConstant(1, CmpOp0.getValueType()));
20862 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20863 if (CC == X86::COND_NE)
20864 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20865 DL, OtherVal.getValueType(), OtherVal,
20866 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20867 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20868 DL, OtherVal.getValueType(), OtherVal,
20869 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20872 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20873 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20874 const X86Subtarget *Subtarget) {
20875 EVT VT = N->getValueType(0);
20876 SDValue Op0 = N->getOperand(0);
20877 SDValue Op1 = N->getOperand(1);
20879 // Try to synthesize horizontal adds from adds of shuffles.
20880 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20881 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20882 isHorizontalBinOp(Op0, Op1, true))
20883 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20885 return OptimizeConditionalInDecrement(N, DAG);
20888 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20889 const X86Subtarget *Subtarget) {
20890 SDValue Op0 = N->getOperand(0);
20891 SDValue Op1 = N->getOperand(1);
20893 // X86 can't encode an immediate LHS of a sub. See if we can push the
20894 // negation into a preceding instruction.
20895 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20896 // If the RHS of the sub is a XOR with one use and a constant, invert the
20897 // immediate. Then add one to the LHS of the sub so we can turn
20898 // X-Y -> X+~Y+1, saving one register.
20899 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20900 isa<ConstantSDNode>(Op1.getOperand(1))) {
20901 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20902 EVT VT = Op0.getValueType();
20903 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20905 DAG.getConstant(~XorC, VT));
20906 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20907 DAG.getConstant(C->getAPIntValue()+1, VT));
20911 // Try to synthesize horizontal adds from adds of shuffles.
20912 EVT VT = N->getValueType(0);
20913 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20914 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20915 isHorizontalBinOp(Op0, Op1, true))
20916 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20918 return OptimizeConditionalInDecrement(N, DAG);
20921 /// performVZEXTCombine - Performs build vector combines
20922 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20923 TargetLowering::DAGCombinerInfo &DCI,
20924 const X86Subtarget *Subtarget) {
20925 // (vzext (bitcast (vzext (x)) -> (vzext x)
20926 SDValue In = N->getOperand(0);
20927 while (In.getOpcode() == ISD::BITCAST)
20928 In = In.getOperand(0);
20930 if (In.getOpcode() != X86ISD::VZEXT)
20933 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20937 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20938 DAGCombinerInfo &DCI) const {
20939 SelectionDAG &DAG = DCI.DAG;
20940 switch (N->getOpcode()) {
20942 case ISD::EXTRACT_VECTOR_ELT:
20943 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20945 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20946 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20947 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20948 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20949 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20950 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20953 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20954 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20955 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20956 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20957 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20958 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20959 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20960 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20961 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20963 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20965 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20966 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20967 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20968 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20969 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20970 case ISD::ANY_EXTEND:
20971 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20972 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20973 case ISD::SIGN_EXTEND_INREG:
20974 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20975 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20976 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20977 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20978 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20979 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20980 case X86ISD::SHUFP: // Handle all target specific shuffles
20981 case X86ISD::PALIGNR:
20982 case X86ISD::UNPCKH:
20983 case X86ISD::UNPCKL:
20984 case X86ISD::MOVHLPS:
20985 case X86ISD::MOVLHPS:
20986 case X86ISD::PSHUFD:
20987 case X86ISD::PSHUFHW:
20988 case X86ISD::PSHUFLW:
20989 case X86ISD::MOVSS:
20990 case X86ISD::MOVSD:
20991 case X86ISD::VPERMILP:
20992 case X86ISD::VPERM2X128:
20993 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20994 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20995 case ISD::INTRINSIC_WO_CHAIN:
20996 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20997 case X86ISD::INSERTPS:
20998 return PerformINSERTPSCombine(N, DAG, Subtarget);
20999 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21005 /// isTypeDesirableForOp - Return true if the target has native support for
21006 /// the specified value type and it is 'desirable' to use the type for the
21007 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21008 /// instruction encodings are longer and some i16 instructions are slow.
21009 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21010 if (!isTypeLegal(VT))
21012 if (VT != MVT::i16)
21019 case ISD::SIGN_EXTEND:
21020 case ISD::ZERO_EXTEND:
21021 case ISD::ANY_EXTEND:
21034 /// IsDesirableToPromoteOp - This method query the target whether it is
21035 /// beneficial for dag combiner to promote the specified node. If true, it
21036 /// should return the desired promotion type by reference.
21037 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21038 EVT VT = Op.getValueType();
21039 if (VT != MVT::i16)
21042 bool Promote = false;
21043 bool Commute = false;
21044 switch (Op.getOpcode()) {
21047 LoadSDNode *LD = cast<LoadSDNode>(Op);
21048 // If the non-extending load has a single use and it's not live out, then it
21049 // might be folded.
21050 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21051 Op.hasOneUse()*/) {
21052 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21053 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21054 // The only case where we'd want to promote LOAD (rather then it being
21055 // promoted as an operand is when it's only use is liveout.
21056 if (UI->getOpcode() != ISD::CopyToReg)
21063 case ISD::SIGN_EXTEND:
21064 case ISD::ZERO_EXTEND:
21065 case ISD::ANY_EXTEND:
21070 SDValue N0 = Op.getOperand(0);
21071 // Look out for (store (shl (load), x)).
21072 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21085 SDValue N0 = Op.getOperand(0);
21086 SDValue N1 = Op.getOperand(1);
21087 if (!Commute && MayFoldLoad(N1))
21089 // Avoid disabling potential load folding opportunities.
21090 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21092 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21102 //===----------------------------------------------------------------------===//
21103 // X86 Inline Assembly Support
21104 //===----------------------------------------------------------------------===//
21107 // Helper to match a string separated by whitespace.
21108 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21109 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21111 for (unsigned i = 0, e = args.size(); i != e; ++i) {
21112 StringRef piece(*args[i]);
21113 if (!s.startswith(piece)) // Check if the piece matches.
21116 s = s.substr(piece.size());
21117 StringRef::size_type pos = s.find_first_not_of(" \t");
21118 if (pos == 0) // We matched a prefix.
21126 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21129 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21131 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21132 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21133 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21134 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21136 if (AsmPieces.size() == 3)
21138 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21145 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21146 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21148 std::string AsmStr = IA->getAsmString();
21150 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21151 if (!Ty || Ty->getBitWidth() % 16 != 0)
21154 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21155 SmallVector<StringRef, 4> AsmPieces;
21156 SplitString(AsmStr, AsmPieces, ";\n");
21158 switch (AsmPieces.size()) {
21159 default: return false;
21161 // FIXME: this should verify that we are targeting a 486 or better. If not,
21162 // we will turn this bswap into something that will be lowered to logical
21163 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21164 // lower so don't worry about this.
21166 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21167 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21168 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21169 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21170 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21171 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21172 // No need to check constraints, nothing other than the equivalent of
21173 // "=r,0" would be valid here.
21174 return IntrinsicLowering::LowerToByteSwap(CI);
21177 // rorw $$8, ${0:w} --> llvm.bswap.i16
21178 if (CI->getType()->isIntegerTy(16) &&
21179 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21180 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21181 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21183 const std::string &ConstraintsStr = IA->getConstraintString();
21184 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21185 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21186 if (clobbersFlagRegisters(AsmPieces))
21187 return IntrinsicLowering::LowerToByteSwap(CI);
21191 if (CI->getType()->isIntegerTy(32) &&
21192 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21193 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21194 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21195 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21197 const std::string &ConstraintsStr = IA->getConstraintString();
21198 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21199 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21200 if (clobbersFlagRegisters(AsmPieces))
21201 return IntrinsicLowering::LowerToByteSwap(CI);
21204 if (CI->getType()->isIntegerTy(64)) {
21205 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21206 if (Constraints.size() >= 2 &&
21207 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21208 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21209 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21210 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21211 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21212 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21213 return IntrinsicLowering::LowerToByteSwap(CI);
21221 /// getConstraintType - Given a constraint letter, return the type of
21222 /// constraint it is for this target.
21223 X86TargetLowering::ConstraintType
21224 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21225 if (Constraint.size() == 1) {
21226 switch (Constraint[0]) {
21237 return C_RegisterClass;
21261 return TargetLowering::getConstraintType(Constraint);
21264 /// Examine constraint type and operand type and determine a weight value.
21265 /// This object must already have been set up with the operand type
21266 /// and the current alternative constraint selected.
21267 TargetLowering::ConstraintWeight
21268 X86TargetLowering::getSingleConstraintMatchWeight(
21269 AsmOperandInfo &info, const char *constraint) const {
21270 ConstraintWeight weight = CW_Invalid;
21271 Value *CallOperandVal = info.CallOperandVal;
21272 // If we don't have a value, we can't do a match,
21273 // but allow it at the lowest weight.
21274 if (!CallOperandVal)
21276 Type *type = CallOperandVal->getType();
21277 // Look at the constraint type.
21278 switch (*constraint) {
21280 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21291 if (CallOperandVal->getType()->isIntegerTy())
21292 weight = CW_SpecificReg;
21297 if (type->isFloatingPointTy())
21298 weight = CW_SpecificReg;
21301 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21302 weight = CW_SpecificReg;
21306 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21307 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21308 weight = CW_Register;
21311 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21312 if (C->getZExtValue() <= 31)
21313 weight = CW_Constant;
21317 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21318 if (C->getZExtValue() <= 63)
21319 weight = CW_Constant;
21323 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21324 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21325 weight = CW_Constant;
21329 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21330 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21331 weight = CW_Constant;
21335 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21336 if (C->getZExtValue() <= 3)
21337 weight = CW_Constant;
21341 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21342 if (C->getZExtValue() <= 0xff)
21343 weight = CW_Constant;
21348 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21349 weight = CW_Constant;
21353 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21354 if ((C->getSExtValue() >= -0x80000000LL) &&
21355 (C->getSExtValue() <= 0x7fffffffLL))
21356 weight = CW_Constant;
21360 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21361 if (C->getZExtValue() <= 0xffffffff)
21362 weight = CW_Constant;
21369 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21370 /// with another that has more specific requirements based on the type of the
21371 /// corresponding operand.
21372 const char *X86TargetLowering::
21373 LowerXConstraint(EVT ConstraintVT) const {
21374 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21375 // 'f' like normal targets.
21376 if (ConstraintVT.isFloatingPoint()) {
21377 if (Subtarget->hasSSE2())
21379 if (Subtarget->hasSSE1())
21383 return TargetLowering::LowerXConstraint(ConstraintVT);
21386 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21387 /// vector. If it is invalid, don't add anything to Ops.
21388 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21389 std::string &Constraint,
21390 std::vector<SDValue>&Ops,
21391 SelectionDAG &DAG) const {
21394 // Only support length 1 constraints for now.
21395 if (Constraint.length() > 1) return;
21397 char ConstraintLetter = Constraint[0];
21398 switch (ConstraintLetter) {
21401 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21402 if (C->getZExtValue() <= 31) {
21403 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21410 if (C->getZExtValue() <= 63) {
21411 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21417 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21418 if (isInt<8>(C->getSExtValue())) {
21419 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21425 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21426 if (C->getZExtValue() <= 255) {
21427 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21433 // 32-bit signed value
21434 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21435 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21436 C->getSExtValue())) {
21437 // Widen to 64 bits here to get it sign extended.
21438 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21441 // FIXME gcc accepts some relocatable values here too, but only in certain
21442 // memory models; it's complicated.
21447 // 32-bit unsigned value
21448 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21449 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21450 C->getZExtValue())) {
21451 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21455 // FIXME gcc accepts some relocatable values here too, but only in certain
21456 // memory models; it's complicated.
21460 // Literal immediates are always ok.
21461 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21462 // Widen to 64 bits here to get it sign extended.
21463 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21467 // In any sort of PIC mode addresses need to be computed at runtime by
21468 // adding in a register or some sort of table lookup. These can't
21469 // be used as immediates.
21470 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21473 // If we are in non-pic codegen mode, we allow the address of a global (with
21474 // an optional displacement) to be used with 'i'.
21475 GlobalAddressSDNode *GA = nullptr;
21476 int64_t Offset = 0;
21478 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21480 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21481 Offset += GA->getOffset();
21483 } else if (Op.getOpcode() == ISD::ADD) {
21484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21485 Offset += C->getZExtValue();
21486 Op = Op.getOperand(0);
21489 } else if (Op.getOpcode() == ISD::SUB) {
21490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21491 Offset += -C->getZExtValue();
21492 Op = Op.getOperand(0);
21497 // Otherwise, this isn't something we can handle, reject it.
21501 const GlobalValue *GV = GA->getGlobal();
21502 // If we require an extra load to get this address, as in PIC mode, we
21503 // can't accept it.
21504 if (isGlobalStubReference(
21505 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21508 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21509 GA->getValueType(0), Offset);
21514 if (Result.getNode()) {
21515 Ops.push_back(Result);
21518 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21521 std::pair<unsigned, const TargetRegisterClass*>
21522 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21524 // First, see if this is a constraint that directly corresponds to an LLVM
21526 if (Constraint.size() == 1) {
21527 // GCC Constraint Letters
21528 switch (Constraint[0]) {
21530 // TODO: Slight differences here in allocation order and leaving
21531 // RIP in the class. Do they matter any more here than they do
21532 // in the normal allocation?
21533 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21534 if (Subtarget->is64Bit()) {
21535 if (VT == MVT::i32 || VT == MVT::f32)
21536 return std::make_pair(0U, &X86::GR32RegClass);
21537 if (VT == MVT::i16)
21538 return std::make_pair(0U, &X86::GR16RegClass);
21539 if (VT == MVT::i8 || VT == MVT::i1)
21540 return std::make_pair(0U, &X86::GR8RegClass);
21541 if (VT == MVT::i64 || VT == MVT::f64)
21542 return std::make_pair(0U, &X86::GR64RegClass);
21545 // 32-bit fallthrough
21546 case 'Q': // Q_REGS
21547 if (VT == MVT::i32 || VT == MVT::f32)
21548 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21549 if (VT == MVT::i16)
21550 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21551 if (VT == MVT::i8 || VT == MVT::i1)
21552 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21553 if (VT == MVT::i64)
21554 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21556 case 'r': // GENERAL_REGS
21557 case 'l': // INDEX_REGS
21558 if (VT == MVT::i8 || VT == MVT::i1)
21559 return std::make_pair(0U, &X86::GR8RegClass);
21560 if (VT == MVT::i16)
21561 return std::make_pair(0U, &X86::GR16RegClass);
21562 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21563 return std::make_pair(0U, &X86::GR32RegClass);
21564 return std::make_pair(0U, &X86::GR64RegClass);
21565 case 'R': // LEGACY_REGS
21566 if (VT == MVT::i8 || VT == MVT::i1)
21567 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21568 if (VT == MVT::i16)
21569 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21570 if (VT == MVT::i32 || !Subtarget->is64Bit())
21571 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21572 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21573 case 'f': // FP Stack registers.
21574 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21575 // value to the correct fpstack register class.
21576 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21577 return std::make_pair(0U, &X86::RFP32RegClass);
21578 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21579 return std::make_pair(0U, &X86::RFP64RegClass);
21580 return std::make_pair(0U, &X86::RFP80RegClass);
21581 case 'y': // MMX_REGS if MMX allowed.
21582 if (!Subtarget->hasMMX()) break;
21583 return std::make_pair(0U, &X86::VR64RegClass);
21584 case 'Y': // SSE_REGS if SSE2 allowed
21585 if (!Subtarget->hasSSE2()) break;
21587 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21588 if (!Subtarget->hasSSE1()) break;
21590 switch (VT.SimpleTy) {
21592 // Scalar SSE types.
21595 return std::make_pair(0U, &X86::FR32RegClass);
21598 return std::make_pair(0U, &X86::FR64RegClass);
21606 return std::make_pair(0U, &X86::VR128RegClass);
21614 return std::make_pair(0U, &X86::VR256RegClass);
21619 return std::make_pair(0U, &X86::VR512RegClass);
21625 // Use the default implementation in TargetLowering to convert the register
21626 // constraint into a member of a register class.
21627 std::pair<unsigned, const TargetRegisterClass*> Res;
21628 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21630 // Not found as a standard register?
21632 // Map st(0) -> st(7) -> ST0
21633 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21634 tolower(Constraint[1]) == 's' &&
21635 tolower(Constraint[2]) == 't' &&
21636 Constraint[3] == '(' &&
21637 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21638 Constraint[5] == ')' &&
21639 Constraint[6] == '}') {
21641 Res.first = X86::ST0+Constraint[4]-'0';
21642 Res.second = &X86::RFP80RegClass;
21646 // GCC allows "st(0)" to be called just plain "st".
21647 if (StringRef("{st}").equals_lower(Constraint)) {
21648 Res.first = X86::ST0;
21649 Res.second = &X86::RFP80RegClass;
21654 if (StringRef("{flags}").equals_lower(Constraint)) {
21655 Res.first = X86::EFLAGS;
21656 Res.second = &X86::CCRRegClass;
21660 // 'A' means EAX + EDX.
21661 if (Constraint == "A") {
21662 Res.first = X86::EAX;
21663 Res.second = &X86::GR32_ADRegClass;
21669 // Otherwise, check to see if this is a register class of the wrong value
21670 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21671 // turn into {ax},{dx}.
21672 if (Res.second->hasType(VT))
21673 return Res; // Correct type already, nothing to do.
21675 // All of the single-register GCC register classes map their values onto
21676 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21677 // really want an 8-bit or 32-bit register, map to the appropriate register
21678 // class and return the appropriate register.
21679 if (Res.second == &X86::GR16RegClass) {
21680 if (VT == MVT::i8 || VT == MVT::i1) {
21681 unsigned DestReg = 0;
21682 switch (Res.first) {
21684 case X86::AX: DestReg = X86::AL; break;
21685 case X86::DX: DestReg = X86::DL; break;
21686 case X86::CX: DestReg = X86::CL; break;
21687 case X86::BX: DestReg = X86::BL; break;
21690 Res.first = DestReg;
21691 Res.second = &X86::GR8RegClass;
21693 } else if (VT == MVT::i32 || VT == MVT::f32) {
21694 unsigned DestReg = 0;
21695 switch (Res.first) {
21697 case X86::AX: DestReg = X86::EAX; break;
21698 case X86::DX: DestReg = X86::EDX; break;
21699 case X86::CX: DestReg = X86::ECX; break;
21700 case X86::BX: DestReg = X86::EBX; break;
21701 case X86::SI: DestReg = X86::ESI; break;
21702 case X86::DI: DestReg = X86::EDI; break;
21703 case X86::BP: DestReg = X86::EBP; break;
21704 case X86::SP: DestReg = X86::ESP; break;
21707 Res.first = DestReg;
21708 Res.second = &X86::GR32RegClass;
21710 } else if (VT == MVT::i64 || VT == MVT::f64) {
21711 unsigned DestReg = 0;
21712 switch (Res.first) {
21714 case X86::AX: DestReg = X86::RAX; break;
21715 case X86::DX: DestReg = X86::RDX; break;
21716 case X86::CX: DestReg = X86::RCX; break;
21717 case X86::BX: DestReg = X86::RBX; break;
21718 case X86::SI: DestReg = X86::RSI; break;
21719 case X86::DI: DestReg = X86::RDI; break;
21720 case X86::BP: DestReg = X86::RBP; break;
21721 case X86::SP: DestReg = X86::RSP; break;
21724 Res.first = DestReg;
21725 Res.second = &X86::GR64RegClass;
21728 } else if (Res.second == &X86::FR32RegClass ||
21729 Res.second == &X86::FR64RegClass ||
21730 Res.second == &X86::VR128RegClass ||
21731 Res.second == &X86::VR256RegClass ||
21732 Res.second == &X86::FR32XRegClass ||
21733 Res.second == &X86::FR64XRegClass ||
21734 Res.second == &X86::VR128XRegClass ||
21735 Res.second == &X86::VR256XRegClass ||
21736 Res.second == &X86::VR512RegClass) {
21737 // Handle references to XMM physical registers that got mapped into the
21738 // wrong class. This can happen with constraints like {xmm0} where the
21739 // target independent register mapper will just pick the first match it can
21740 // find, ignoring the required type.
21742 if (VT == MVT::f32 || VT == MVT::i32)
21743 Res.second = &X86::FR32RegClass;
21744 else if (VT == MVT::f64 || VT == MVT::i64)
21745 Res.second = &X86::FR64RegClass;
21746 else if (X86::VR128RegClass.hasType(VT))
21747 Res.second = &X86::VR128RegClass;
21748 else if (X86::VR256RegClass.hasType(VT))
21749 Res.second = &X86::VR256RegClass;
21750 else if (X86::VR512RegClass.hasType(VT))
21751 Res.second = &X86::VR512RegClass;
21757 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21759 // Scaling factors are not free at all.
21760 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21761 // will take 2 allocations in the out of order engine instead of 1
21762 // for plain addressing mode, i.e. inst (reg1).
21764 // vaddps (%rsi,%drx), %ymm0, %ymm1
21765 // Requires two allocations (one for the load, one for the computation)
21767 // vaddps (%rsi), %ymm0, %ymm1
21768 // Requires just 1 allocation, i.e., freeing allocations for other operations
21769 // and having less micro operations to execute.
21771 // For some X86 architectures, this is even worse because for instance for
21772 // stores, the complex addressing mode forces the instruction to use the
21773 // "load" ports instead of the dedicated "store" port.
21774 // E.g., on Haswell:
21775 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21776 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21777 if (isLegalAddressingMode(AM, Ty))
21778 // Scale represents reg2 * scale, thus account for 1
21779 // as soon as we use a second register.
21780 return AM.Scale != 0;
21784 bool X86TargetLowering::isTargetFTOL() const {
21785 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();